]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Mention language in compile error message
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
32d0add0 3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
35b1e5cc 73
0df8b418 74/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
75static char *target_buf;
76static long target_buf_size;
35b1e5cc 77
6765f3e5
DJ
78/* The size to align memory write packets, when practical. The protocol
79 does not guarantee any alignment, and gdb will generate short
80 writes and unaligned writes, but even as a best-effort attempt this
81 can improve bulk transfers. For instance, if a write is misaligned
82 relative to the target's data bus, the stub may need to make an extra
83 round trip fetching data from the target. This doesn't make a
84 huge difference, but it's easy to do, so we try to be helpful.
85
86 The alignment chosen is arbitrary; usually data bus width is
87 important here, not the possibly larger cache line size. */
88enum { REMOTE_ALIGN_WRITES = 16 };
89
23860348 90/* Prototypes for local functions. */
934b9bac 91static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 92static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 93static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 94 int forever, int *is_notif);
6426a772 95
934b9bac
JK
96static void async_handle_remote_sigint (int);
97static void async_handle_remote_sigint_twice (int);
43ff13b4 98
a14ed312 99static void remote_files_info (struct target_ops *ignore);
c906108c 100
f32dbf8c
MM
101static void remote_prepare_to_store (struct target_ops *self,
102 struct regcache *regcache);
c906108c 103
014f9477
TT
104static void remote_open_1 (const char *, int, struct target_ops *,
105 int extended_p);
c906108c 106
de90e03d 107static void remote_close (struct target_ops *self);
c906108c 108
cbb8991c
DB
109struct remote_state;
110
111static int remote_vkill (int pid, struct remote_state *rs);
112
136d6dae 113static void remote_mourn (struct target_ops *ops);
c906108c 114
a14ed312 115static void extended_remote_restart (void);
c906108c 116
136d6dae 117static void extended_remote_mourn (struct target_ops *);
c906108c 118
6d820c5c 119static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 120
a14ed312 121static int readchar (int timeout);
c906108c 122
c33e31fd
PA
123static void remote_serial_write (const char *str, int len);
124
7d85a9c0 125static void remote_kill (struct target_ops *ops);
c906108c 126
6a109b6b 127static int remote_can_async_p (struct target_ops *);
75c99385 128
6a109b6b 129static int remote_is_async_p (struct target_ops *);
75c99385 130
6a3753b3 131static void remote_async (struct target_ops *ops, int enable);
75c99385 132
934b9bac 133static void sync_remote_interrupt_twice (int signo);
7a292a7a 134
a14ed312 135static void interrupt_query (void);
c906108c 136
79d7f229
PA
137static void set_general_thread (struct ptid ptid);
138static void set_continue_thread (struct ptid ptid);
c906108c 139
a14ed312 140static void get_offsets (void);
c906108c 141
6d820c5c
DJ
142static void skip_frame (void);
143
144static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 145
a14ed312 146static int hexnumlen (ULONGEST num);
c906108c 147
a14ed312 148static void init_remote_ops (void);
c906108c 149
a14ed312 150static void init_extended_remote_ops (void);
c906108c 151
1eab8a48 152static void remote_stop (struct target_ops *self, ptid_t);
c906108c 153
a14ed312 154static int stubhex (int ch);
c906108c 155
a14ed312 156static int hexnumstr (char *, ULONGEST);
c906108c 157
a14ed312 158static int hexnumnstr (char *, ULONGEST, int);
2df3850c 159
a14ed312 160static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 161
baa336ce 162static void print_packet (const char *);
c906108c 163
a14ed312 164static void compare_sections_command (char *, int);
c906108c 165
a14ed312 166static void packet_command (char *, int);
c906108c 167
a14ed312 168static int stub_unpack_int (char *buff, int fieldlength);
c906108c 169
39f77062 170static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 171
baa336ce 172static int putpkt_binary (const char *buf, int cnt);
c906108c 173
a14ed312 174static void check_binary_download (CORE_ADDR addr);
c906108c 175
5a2468f5 176struct packet_config;
5a2468f5 177
a14ed312 178static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 179
bb572ddd
DJ
180static void show_remote_protocol_packet_cmd (struct ui_file *file,
181 int from_tty,
182 struct cmd_list_element *c,
183 const char *value);
184
82f73884
PA
185static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
186static ptid_t read_ptid (char *buf, char **obuf);
187
c378d69d 188static void remote_set_permissions (struct target_ops *self);
d914c394 189
8bd200f1
TT
190static int remote_get_trace_status (struct target_ops *self,
191 struct trace_status *ts);
d5551862 192
ab6617cc
TT
193static int remote_upload_tracepoints (struct target_ops *self,
194 struct uploaded_tp **utpp);
00bf0b85 195
181e3713
TT
196static int remote_upload_trace_state_variables (struct target_ops *self,
197 struct uploaded_tsv **utsvp);
00bf0b85 198
c8d104ad
PA
199static void remote_query_supported (void);
200
36d25514 201static void remote_check_symbols (void);
c8d104ad 202
a14ed312 203void _initialize_remote (void);
c906108c 204
74531fed 205struct stop_reply;
74531fed 206static void stop_reply_xfree (struct stop_reply *);
722247f1 207static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 208static void push_stop_reply (struct stop_reply *);
bcc75809 209static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
210static int peek_stop_reply (ptid_t ptid);
211
cbb8991c
DB
212struct threads_listing_context;
213static void remove_new_fork_children (struct threads_listing_context *);
214
74531fed 215static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 216
e3594fd1 217static void remote_terminal_ours (struct target_ops *self);
d3fd5342 218
d962ef82
DJ
219static int remote_read_description_p (struct target_ops *target);
220
176a6961 221static void remote_console_output (char *msg);
dde08ee1 222
efcc2da7 223static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 224
78eff0ec 225static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 226
f4abbc16
MM
227static void remote_btrace_reset (void);
228
221e1a37
PA
229static int stop_reply_queue_length (void);
230
80152258
PA
231static void readahead_cache_invalidate (void);
232
a6b151f1
DJ
233/* For "remote". */
234
235static struct cmd_list_element *remote_cmdlist;
236
bb572ddd
DJ
237/* For "set remote" and "show remote". */
238
239static struct cmd_list_element *remote_set_cmdlist;
240static struct cmd_list_element *remote_show_cmdlist;
241
d458bd84
PA
242/* Stub vCont actions support.
243
244 Each field is a boolean flag indicating whether the stub reports
245 support for the corresponding action. */
246
247struct vCont_action_support
248{
249 /* vCont;t */
250 int t;
c1e36e3e
PA
251
252 /* vCont;r */
253 int r;
d458bd84
PA
254};
255
c1e36e3e
PA
256/* Controls whether GDB is willing to use range stepping. */
257
258static int use_range_stepping = 1;
259
0d031856
TT
260#define OPAQUETHREADBYTES 8
261
262/* a 64 bit opaque identifier */
263typedef unsigned char threadref[OPAQUETHREADBYTES];
264
265/* About this many threadisds fit in a packet. */
266
267#define MAXTHREADLISTRESULTS 32
268
80152258
PA
269/* Data for the vFile:pread readahead cache. */
270
271struct readahead_cache
272{
273 /* The file descriptor for the file that is being cached. -1 if the
274 cache is invalid. */
275 int fd;
276
277 /* The offset into the file that the cache buffer corresponds
278 to. */
279 ULONGEST offset;
280
281 /* The buffer holding the cache contents. */
282 gdb_byte *buf;
283 /* The buffer's size. We try to read as much as fits into a packet
284 at a time. */
285 size_t bufsize;
286
287 /* Cache hit and miss counters. */
288 ULONGEST hit_count;
289 ULONGEST miss_count;
290};
291
ea9c271d
DJ
292/* Description of the remote protocol state for the currently
293 connected target. This is per-target state, and independent of the
294 selected architecture. */
295
296struct remote_state
297{
298 /* A buffer to use for incoming packets, and its current size. The
299 buffer is grown dynamically for larger incoming packets.
300 Outgoing packets may also be constructed in this buffer.
301 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
302 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
303 packets. */
304 char *buf;
305 long buf_size;
be2a5f71 306
1e51243a
PA
307 /* True if we're going through initial connection setup (finding out
308 about the remote side's threads, relocating symbols, etc.). */
309 int starting_up;
310
be2a5f71
DJ
311 /* If we negotiated packet size explicitly (and thus can bypass
312 heuristics for the largest packet size that will not overflow
313 a buffer in the stub), this will be set to that packet size.
314 Otherwise zero, meaning to use the guessed size. */
315 long explicit_packet_size;
2d717e4f
DJ
316
317 /* remote_wait is normally called when the target is running and
318 waits for a stop reply packet. But sometimes we need to call it
319 when the target is already stopped. We can send a "?" packet
320 and have remote_wait read the response. Or, if we already have
321 the response, we can stash it in BUF and tell remote_wait to
322 skip calling getpkt. This flag is set when BUF contains a
323 stop reply packet and the target is not waiting. */
324 int cached_wait_status;
a6f3e723
SL
325
326 /* True, if in no ack mode. That is, neither GDB nor the stub will
327 expect acks from each other. The connection is assumed to be
328 reliable. */
329 int noack_mode;
82f73884
PA
330
331 /* True if we're connected in extended remote mode. */
332 int extended;
333
e24a49d8
PA
334 /* True if we resumed the target and we're waiting for the target to
335 stop. In the mean time, we can't start another command/query.
336 The remote server wouldn't be ready to process it, so we'd
337 timeout waiting for a reply that would never come and eventually
338 we'd close the connection. This can happen in asynchronous mode
339 because we allow GDB commands while the target is running. */
340 int waiting_for_stop_reply;
74531fed 341
d458bd84
PA
342 /* The status of the stub support for the various vCont actions. */
343 struct vCont_action_support supports_vCont;
782b2b07 344
3a29589a
DJ
345 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
346 responded to that. */
347 int ctrlc_pending_p;
5d93a237
TT
348
349 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
350 remote_open knows that we don't have a file open when the program
351 starts. */
352 struct serial *remote_desc;
47f8a51d
TT
353
354 /* These are the threads which we last sent to the remote system. The
355 TID member will be -1 for all or -2 for not sent yet. */
356 ptid_t general_thread;
357 ptid_t continue_thread;
262e1174
TT
358
359 /* This is the traceframe which we last selected on the remote system.
360 It will be -1 if no traceframe is selected. */
361 int remote_traceframe_number;
747dc59d
TT
362
363 char *last_pass_packet;
5e4a05c4
TT
364
365 /* The last QProgramSignals packet sent to the target. We bypass
366 sending a new program signals list down to the target if the new
367 packet is exactly the same as the last we sent. IOW, we only let
368 the target know about program signals list changes. */
369 char *last_program_signals_packet;
b73be471
TT
370
371 enum gdb_signal last_sent_signal;
280ceea3
TT
372
373 int last_sent_step;
8e88304f
TT
374
375 char *finished_object;
376 char *finished_annex;
377 ULONGEST finished_offset;
b80fafe3
TT
378
379 /* Should we try the 'ThreadInfo' query packet?
380
381 This variable (NOT available to the user: auto-detect only!)
382 determines whether GDB will use the new, simpler "ThreadInfo"
383 query or the older, more complex syntax for thread queries.
384 This is an auto-detect variable (set to true at each connect,
385 and set to false when the target fails to recognize it). */
386 int use_threadinfo_query;
387 int use_threadextra_query;
88b496c3 388
ee154bee
TT
389 /* This is set to the data address of the access causing the target
390 to stop for a watchpoint. */
391 CORE_ADDR remote_watch_data_address;
392
f7e6eed5
PA
393 /* Whether the target stopped for a breakpoint/watchpoint. */
394 enum target_stop_reason stop_reason;
0d031856
TT
395
396 threadref echo_nextthread;
397 threadref nextthread;
398 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
399
400 /* The state of remote notification. */
401 struct remote_notif_state *notif_state;
f4abbc16
MM
402
403 /* The branch trace configuration. */
404 struct btrace_config btrace_config;
15a201c8
GB
405
406 /* The argument to the last "vFile:setfs:" packet we sent, used
407 to avoid sending repeated unnecessary "vFile:setfs:" packets.
408 Initialized to -1 to indicate that no "vFile:setfs:" packet
409 has yet been sent. */
410 int fs_pid;
80152258
PA
411
412 /* A readahead cache for vFile:pread. Often, reading a binary
413 involves a sequence of small reads. E.g., when parsing an ELF
414 file. A readahead cache helps mostly the case of remote
415 debugging on a connection with higher latency, due to the
416 request/reply nature of the RSP. We only cache data for a single
417 file descriptor at a time. */
418 struct readahead_cache readahead_cache;
ea9c271d
DJ
419};
420
dc146f7c
VP
421/* Private data that we'll store in (struct thread_info)->private. */
422struct private_thread_info
423{
424 char *extra;
425 int core;
426};
427
428static void
429free_private_thread_info (struct private_thread_info *info)
430{
431 xfree (info->extra);
432 xfree (info);
433}
434
ea9c271d
DJ
435/* This data could be associated with a target, but we do not always
436 have access to the current target when we need it, so for now it is
437 static. This will be fine for as long as only one target is in use
438 at a time. */
cf792862 439static struct remote_state *remote_state;
ea9c271d
DJ
440
441static struct remote_state *
0b83947e 442get_remote_state_raw (void)
ea9c271d 443{
cf792862
TT
444 return remote_state;
445}
446
447/* Allocate a new struct remote_state with xmalloc, initialize it, and
448 return it. */
449
450static struct remote_state *
451new_remote_state (void)
452{
453 struct remote_state *result = XCNEW (struct remote_state);
454
455 /* The default buffer size is unimportant; it will be expanded
456 whenever a larger buffer is needed. */
457 result->buf_size = 400;
458 result->buf = xmalloc (result->buf_size);
262e1174 459 result->remote_traceframe_number = -1;
b73be471 460 result->last_sent_signal = GDB_SIGNAL_0;
15a201c8 461 result->fs_pid = -1;
cf792862
TT
462
463 return result;
ea9c271d
DJ
464}
465
466/* Description of the remote protocol for a given architecture. */
d01949b6 467
ad10f812
AC
468struct packet_reg
469{
470 long offset; /* Offset into G packet. */
471 long regnum; /* GDB's internal register number. */
472 LONGEST pnum; /* Remote protocol register number. */
b323314b 473 int in_g_packet; /* Always part of G packet. */
f5656ead 474 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 475 at present. */
f5656ead 476 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 477 at present. */
ad10f812
AC
478};
479
ea9c271d 480struct remote_arch_state
d01949b6 481{
ad10f812
AC
482 /* Description of the remote protocol registers. */
483 long sizeof_g_packet;
b323314b
AC
484
485 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 486 (making an array gdbarch_num_regs in size). */
b323314b 487 struct packet_reg *regs;
ad10f812 488
d01949b6
AC
489 /* This is the size (in chars) of the first response to the ``g''
490 packet. It is used as a heuristic when determining the maximum
491 size of memory-read and memory-write packets. A target will
492 typically only reserve a buffer large enough to hold the ``g''
493 packet. The size does not include packet overhead (headers and
23860348 494 trailers). */
d01949b6
AC
495 long actual_register_packet_size;
496
497 /* This is the maximum size (in chars) of a non read/write packet.
23860348 498 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
499 long remote_packet_size;
500};
501
35b1e5cc
SS
502/* Utility: generate error from an incoming stub packet. */
503static void
504trace_error (char *buf)
505{
506 if (*buf++ != 'E')
507 return; /* not an error msg */
508 switch (*buf)
509 {
510 case '1': /* malformed packet error */
511 if (*++buf == '0') /* general case: */
512 error (_("remote.c: error in outgoing packet."));
513 else
514 error (_("remote.c: error in outgoing packet at field #%ld."),
515 strtol (buf, NULL, 16));
35b1e5cc
SS
516 default:
517 error (_("Target returns error code '%s'."), buf);
518 }
519}
520
521/* Utility: wait for reply from stub, while accepting "O" packets. */
522static char *
523remote_get_noisy_reply (char **buf_p,
524 long *sizeof_buf)
525{
526 do /* Loop on reply from remote stub. */
527 {
528 char *buf;
a744cf53 529
0df8b418 530 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
531 getpkt (buf_p, sizeof_buf, 0);
532 buf = *buf_p;
ad91cd99 533 if (buf[0] == 'E')
35b1e5cc 534 trace_error (buf);
61012eef 535 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
536 {
537 ULONGEST ul;
538 CORE_ADDR from, to, org_to;
539 char *p, *pp;
540 int adjusted_size = 0;
7556d4a4 541 int relocated = 0;
dde08ee1
PA
542
543 p = buf + strlen ("qRelocInsn:");
544 pp = unpack_varlen_hex (p, &ul);
545 if (*pp != ';')
cb91c06a 546 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
547 from = ul;
548
549 p = pp + 1;
a9cbf802 550 unpack_varlen_hex (p, &ul);
dde08ee1
PA
551 to = ul;
552
553 org_to = to;
554
492d29ea 555 TRY
dde08ee1 556 {
f5656ead 557 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 558 relocated = 1;
dde08ee1 559 }
492d29ea 560 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
561 {
562 if (ex.error == MEMORY_ERROR)
563 {
564 /* Propagate memory errors silently back to the
565 target. The stub may have limited the range of
566 addresses we can write to, for example. */
567 }
568 else
569 {
570 /* Something unexpectedly bad happened. Be verbose
571 so we can tell what, and propagate the error back
572 to the stub, so it doesn't get stuck waiting for
573 a response. */
574 exception_fprintf (gdb_stderr, ex,
575 _("warning: relocating instruction: "));
576 }
577 putpkt ("E01");
578 }
492d29ea 579 END_CATCH
7556d4a4
PA
580
581 if (relocated)
dde08ee1
PA
582 {
583 adjusted_size = to - org_to;
584
bba74b36 585 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
586 putpkt (buf);
587 }
dde08ee1 588 }
ad91cd99 589 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
590 remote_console_output (buf + 1); /* 'O' message from stub */
591 else
0df8b418 592 return buf; /* Here's the actual reply. */
35b1e5cc
SS
593 }
594 while (1);
595}
3c3bea1c 596
d01949b6
AC
597/* Handle for retreving the remote protocol data from gdbarch. */
598static struct gdbarch_data *remote_gdbarch_data_handle;
599
ea9c271d
DJ
600static struct remote_arch_state *
601get_remote_arch_state (void)
d01949b6 602{
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
924/* Compute the current size of a read/write packet. Since this makes
925 use of ``actual_register_packet_size'' the computation is dynamic. */
926
927static long
928get_memory_packet_size (struct memory_packet_config *config)
929{
d01949b6 930 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
931 struct remote_arch_state *rsa = get_remote_arch_state ();
932
11cf8741
JM
933 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
934 law?) that some hosts don't cope very well with large alloca()
935 calls. Eventually the alloca() code will be replaced by calls to
936 xmalloc() and make_cleanups() allowing this restriction to either
23860348 937 be lifted or removed. */
11cf8741
JM
938#ifndef MAX_REMOTE_PACKET_SIZE
939#define MAX_REMOTE_PACKET_SIZE 16384
940#endif
3de11b2e 941 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 942#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 943#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
944#endif
945 long what_they_get;
946 if (config->fixed_p)
947 {
948 if (config->size <= 0)
949 what_they_get = MAX_REMOTE_PACKET_SIZE;
950 else
951 what_they_get = config->size;
952 }
953 else
954 {
ea9c271d 955 what_they_get = get_remote_packet_size ();
23860348 956 /* Limit the packet to the size specified by the user. */
11cf8741
JM
957 if (config->size > 0
958 && what_they_get > config->size)
959 what_they_get = config->size;
be2a5f71
DJ
960
961 /* Limit it to the size of the targets ``g'' response unless we have
962 permission from the stub to use a larger packet size. */
963 if (rs->explicit_packet_size == 0
964 && rsa->actual_register_packet_size > 0
965 && what_they_get > rsa->actual_register_packet_size)
966 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
967 }
968 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
969 what_they_get = MAX_REMOTE_PACKET_SIZE;
970 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
971 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
972
973 /* Make sure there is room in the global buffer for this packet
974 (including its trailing NUL byte). */
975 if (rs->buf_size < what_they_get + 1)
976 {
977 rs->buf_size = 2 * what_they_get;
978 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
979 }
980
11cf8741
JM
981 return what_they_get;
982}
983
0df8b418 984/* Update the size of a read/write packet. If they user wants
23860348 985 something really big then do a sanity check. */
11cf8741
JM
986
987static void
988set_memory_packet_size (char *args, struct memory_packet_config *config)
989{
990 int fixed_p = config->fixed_p;
991 long size = config->size;
a744cf53 992
11cf8741 993 if (args == NULL)
8a3fe4f8 994 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
995 else if (strcmp (args, "hard") == 0
996 || strcmp (args, "fixed") == 0)
997 fixed_p = 1;
998 else if (strcmp (args, "soft") == 0
999 || strcmp (args, "limit") == 0)
1000 fixed_p = 0;
1001 else
1002 {
1003 char *end;
a744cf53 1004
11cf8741
JM
1005 size = strtoul (args, &end, 0);
1006 if (args == end)
8a3fe4f8 1007 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
1008#if 0
1009 /* Instead of explicitly capping the size of a packet to
1010 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
1011 instead allowed to set the size to something arbitrarily
23860348 1012 large. */
11cf8741 1013 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 1014 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
1015#endif
1016 }
23860348 1017 /* Extra checks? */
11cf8741
JM
1018 if (fixed_p && !config->fixed_p)
1019 {
e2e0b3e5
AC
1020 if (! query (_("The target may not be able to correctly handle a %s\n"
1021 "of %ld bytes. Change the packet size? "),
11cf8741 1022 config->name, size))
8a3fe4f8 1023 error (_("Packet size not changed."));
11cf8741 1024 }
23860348 1025 /* Update the config. */
11cf8741
JM
1026 config->fixed_p = fixed_p;
1027 config->size = size;
1028}
1029
1030static void
1031show_memory_packet_size (struct memory_packet_config *config)
1032{
a3f17187 1033 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1034 if (config->fixed_p)
a3f17187 1035 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1036 get_memory_packet_size (config));
1037 else
a3f17187 1038 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1039 get_memory_packet_size (config));
1040}
1041
1042static struct memory_packet_config memory_write_packet_config =
1043{
1044 "memory-write-packet-size",
1045};
1046
1047static void
1048set_memory_write_packet_size (char *args, int from_tty)
1049{
1050 set_memory_packet_size (args, &memory_write_packet_config);
1051}
1052
1053static void
1054show_memory_write_packet_size (char *args, int from_tty)
1055{
1056 show_memory_packet_size (&memory_write_packet_config);
1057}
1058
1059static long
1060get_memory_write_packet_size (void)
1061{
1062 return get_memory_packet_size (&memory_write_packet_config);
1063}
1064
1065static struct memory_packet_config memory_read_packet_config =
1066{
1067 "memory-read-packet-size",
1068};
1069
1070static void
1071set_memory_read_packet_size (char *args, int from_tty)
1072{
1073 set_memory_packet_size (args, &memory_read_packet_config);
1074}
1075
1076static void
1077show_memory_read_packet_size (char *args, int from_tty)
1078{
1079 show_memory_packet_size (&memory_read_packet_config);
1080}
1081
1082static long
1083get_memory_read_packet_size (void)
1084{
1085 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1086
11cf8741
JM
1087 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1088 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1089 increased beyond this. */
1090 if (size > get_remote_packet_size ())
1091 size = get_remote_packet_size ();
11cf8741
JM
1092 return size;
1093}
1094
11cf8741 1095\f
5a2468f5 1096/* Generic configuration support for packets the stub optionally
0df8b418 1097 supports. Allows the user to specify the use of the packet as well
23860348 1098 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1099
1100enum packet_support
1101 {
1102 PACKET_SUPPORT_UNKNOWN = 0,
1103 PACKET_ENABLE,
1104 PACKET_DISABLE
1105 };
1106
5a2468f5
JM
1107struct packet_config
1108 {
bb572ddd
DJ
1109 const char *name;
1110 const char *title;
4082afcc
PA
1111
1112 /* If auto, GDB auto-detects support for this packet or feature,
1113 either through qSupported, or by trying the packet and looking
1114 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1115 packet. If false, the packet is disabled. Configs that don't
1116 have an associated command always have this set to auto. */
7f19b9a2 1117 enum auto_boolean detect;
4082afcc
PA
1118
1119 /* Does the target support this packet? */
5a2468f5
JM
1120 enum packet_support support;
1121 };
1122
d471ea57 1123/* Analyze a packet's return value and update the packet config
23860348 1124 accordingly. */
d471ea57
AC
1125
1126enum packet_result
1127{
1128 PACKET_ERROR,
1129 PACKET_OK,
1130 PACKET_UNKNOWN
1131};
1132
4082afcc
PA
1133static enum packet_support packet_config_support (struct packet_config *config);
1134static enum packet_support packet_support (int packet);
5a2468f5
JM
1135
1136static void
fba45db2 1137show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1138{
1139 char *support = "internal-error";
a744cf53 1140
4082afcc 1141 switch (packet_config_support (config))
5a2468f5
JM
1142 {
1143 case PACKET_ENABLE:
1144 support = "enabled";
1145 break;
1146 case PACKET_DISABLE:
1147 support = "disabled";
1148 break;
1149 case PACKET_SUPPORT_UNKNOWN:
1150 support = "unknown";
1151 break;
1152 }
1153 switch (config->detect)
1154 {
7f19b9a2 1155 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1156 printf_filtered (_("Support for the `%s' packet "
1157 "is auto-detected, currently %s.\n"),
37a105a1 1158 config->name, support);
5a2468f5 1159 break;
7f19b9a2
AC
1160 case AUTO_BOOLEAN_TRUE:
1161 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1162 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1163 config->name, support);
8e248173 1164 break;
5a2468f5
JM
1165 }
1166}
1167
1168static void
bb572ddd
DJ
1169add_packet_config_cmd (struct packet_config *config, const char *name,
1170 const char *title, int legacy)
d471ea57 1171{
5a2468f5
JM
1172 char *set_doc;
1173 char *show_doc;
d471ea57 1174 char *cmd_name;
3ed07be4 1175
5a2468f5
JM
1176 config->name = name;
1177 config->title = title;
b435e160
AC
1178 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1179 name, title);
3e43a32a
MS
1180 show_doc = xstrprintf ("Show current use of remote "
1181 "protocol `%s' (%s) packet",
b435e160 1182 name, title);
d471ea57 1183 /* set/show TITLE-packet {auto,on,off} */
b435e160 1184 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1185 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1186 &config->detect, set_doc,
1187 show_doc, NULL, /* help_doc */
4082afcc 1188 NULL,
bb572ddd
DJ
1189 show_remote_protocol_packet_cmd,
1190 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1191 /* The command code copies the documentation strings. */
1192 xfree (set_doc);
1193 xfree (show_doc);
23860348 1194 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1195 if (legacy)
1196 {
1197 char *legacy_name;
a744cf53 1198
b435e160 1199 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1200 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1201 &remote_set_cmdlist);
d471ea57 1202 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1203 &remote_show_cmdlist);
d471ea57 1204 }
5a2468f5
JM
1205}
1206
d471ea57 1207static enum packet_result
a76d924d 1208packet_check_result (const char *buf)
5a2468f5 1209{
d471ea57 1210 if (buf[0] != '\0')
5a2468f5 1211 {
d471ea57 1212 /* The stub recognized the packet request. Check that the
23860348 1213 operation succeeded. */
a76d924d
DJ
1214 if (buf[0] == 'E'
1215 && isxdigit (buf[1]) && isxdigit (buf[2])
1216 && buf[3] == '\0')
1217 /* "Enn" - definitly an error. */
1218 return PACKET_ERROR;
1219
1220 /* Always treat "E." as an error. This will be used for
1221 more verbose error messages, such as E.memtypes. */
1222 if (buf[0] == 'E' && buf[1] == '.')
1223 return PACKET_ERROR;
1224
1225 /* The packet may or may not be OK. Just assume it is. */
1226 return PACKET_OK;
1227 }
1228 else
1229 /* The stub does not support the packet. */
1230 return PACKET_UNKNOWN;
1231}
1232
1233static enum packet_result
1234packet_ok (const char *buf, struct packet_config *config)
1235{
1236 enum packet_result result;
1237
4082afcc
PA
1238 if (config->detect != AUTO_BOOLEAN_TRUE
1239 && config->support == PACKET_DISABLE)
1240 internal_error (__FILE__, __LINE__,
1241 _("packet_ok: attempt to use a disabled packet"));
1242
a76d924d
DJ
1243 result = packet_check_result (buf);
1244 switch (result)
1245 {
1246 case PACKET_OK:
1247 case PACKET_ERROR:
1248 /* The stub recognized the packet request. */
4082afcc 1249 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1250 {
d471ea57
AC
1251 if (remote_debug)
1252 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1253 "Packet %s (%s) is supported\n",
1254 config->name, config->title);
d471ea57 1255 config->support = PACKET_ENABLE;
d471ea57 1256 }
a76d924d
DJ
1257 break;
1258 case PACKET_UNKNOWN:
23860348 1259 /* The stub does not support the packet. */
4082afcc
PA
1260 if (config->detect == AUTO_BOOLEAN_AUTO
1261 && config->support == PACKET_ENABLE)
d471ea57 1262 {
4082afcc
PA
1263 /* If the stub previously indicated that the packet was
1264 supported then there is a protocol error. */
1265 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1266 config->name, config->title);
1267 }
1268 else if (config->detect == AUTO_BOOLEAN_TRUE)
1269 {
1270 /* The user set it wrong. */
1271 error (_("Enabled packet %s (%s) not recognized by stub"),
1272 config->name, config->title);
d471ea57 1273 }
4082afcc
PA
1274
1275 if (remote_debug)
1276 fprintf_unfiltered (gdb_stdlog,
1277 "Packet %s (%s) is NOT supported\n",
1278 config->name, config->title);
1279 config->support = PACKET_DISABLE;
a76d924d 1280 break;
5a2468f5 1281 }
a76d924d
DJ
1282
1283 return result;
5a2468f5
JM
1284}
1285
444abaca
DJ
1286enum {
1287 PACKET_vCont = 0,
1288 PACKET_X,
1289 PACKET_qSymbol,
1290 PACKET_P,
1291 PACKET_p,
1292 PACKET_Z0,
1293 PACKET_Z1,
1294 PACKET_Z2,
1295 PACKET_Z3,
1296 PACKET_Z4,
15a201c8 1297 PACKET_vFile_setfs,
a6b151f1
DJ
1298 PACKET_vFile_open,
1299 PACKET_vFile_pread,
1300 PACKET_vFile_pwrite,
1301 PACKET_vFile_close,
1302 PACKET_vFile_unlink,
b9e7b9c3 1303 PACKET_vFile_readlink,
0a93529c 1304 PACKET_vFile_fstat,
0876f84a 1305 PACKET_qXfer_auxv,
23181151 1306 PACKET_qXfer_features,
c78fa86a 1307 PACKET_qXfer_exec_file,
cfa9d6d9 1308 PACKET_qXfer_libraries,
2268b414 1309 PACKET_qXfer_libraries_svr4,
fd79ecee 1310 PACKET_qXfer_memory_map,
0e7f50da
UW
1311 PACKET_qXfer_spu_read,
1312 PACKET_qXfer_spu_write,
07e059b5 1313 PACKET_qXfer_osdata,
dc146f7c 1314 PACKET_qXfer_threads,
0fb4aa4b 1315 PACKET_qXfer_statictrace_read,
b3b9301e 1316 PACKET_qXfer_traceframe_info,
169081d0 1317 PACKET_qXfer_uib,
711e434b 1318 PACKET_qGetTIBAddr,
444abaca 1319 PACKET_qGetTLSAddr,
be2a5f71 1320 PACKET_qSupported,
bd3eecc3 1321 PACKET_qTStatus,
89be2091 1322 PACKET_QPassSignals,
9b224c5e 1323 PACKET_QProgramSignals,
936d2992 1324 PACKET_qCRC,
08388c79 1325 PACKET_qSearch_memory,
2d717e4f
DJ
1326 PACKET_vAttach,
1327 PACKET_vRun,
a6f3e723 1328 PACKET_QStartNoAckMode,
82f73884 1329 PACKET_vKill,
4aa995e1
PA
1330 PACKET_qXfer_siginfo_read,
1331 PACKET_qXfer_siginfo_write,
0b16c5cf 1332 PACKET_qAttached,
4082afcc
PA
1333
1334 /* Support for conditional tracepoints. */
782b2b07 1335 PACKET_ConditionalTracepoints,
4082afcc
PA
1336
1337 /* Support for target-side breakpoint conditions. */
3788aec7 1338 PACKET_ConditionalBreakpoints,
4082afcc
PA
1339
1340 /* Support for target-side breakpoint commands. */
d3ce09f5 1341 PACKET_BreakpointCommands,
4082afcc
PA
1342
1343 /* Support for fast tracepoints. */
7a697b8d 1344 PACKET_FastTracepoints,
4082afcc
PA
1345
1346 /* Support for static tracepoints. */
0fb4aa4b 1347 PACKET_StaticTracepoints,
4082afcc
PA
1348
1349 /* Support for installing tracepoints while a trace experiment is
1350 running. */
1e4d1764 1351 PACKET_InstallInTrace,
4082afcc 1352
40ab02ce
MS
1353 PACKET_bc,
1354 PACKET_bs,
409873ef 1355 PACKET_TracepointSource,
d914c394 1356 PACKET_QAllow,
78d85199 1357 PACKET_qXfer_fdpic,
03583c20 1358 PACKET_QDisableRandomization,
d1feda86 1359 PACKET_QAgent,
f6f899bf 1360 PACKET_QTBuffer_size,
9accd112
MM
1361 PACKET_Qbtrace_off,
1362 PACKET_Qbtrace_bts,
b20a6524 1363 PACKET_Qbtrace_pt,
9accd112 1364 PACKET_qXfer_btrace,
4082afcc
PA
1365
1366 /* Support for the QNonStop packet. */
1367 PACKET_QNonStop,
1368
1369 /* Support for multi-process extensions. */
1370 PACKET_multiprocess_feature,
1371
1372 /* Support for enabling and disabling tracepoints while a trace
1373 experiment is running. */
1374 PACKET_EnableDisableTracepoints_feature,
1375
1376 /* Support for collecting strings using the tracenz bytecode. */
1377 PACKET_tracenz_feature,
1378
1379 /* Support for continuing to run a trace experiment while GDB is
1380 disconnected. */
1381 PACKET_DisconnectedTracing_feature,
1382
1383 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1384 PACKET_augmented_libraries_svr4_read_feature,
1385
f4abbc16
MM
1386 /* Support for the qXfer:btrace-conf:read packet. */
1387 PACKET_qXfer_btrace_conf,
1388
d33501a5
MM
1389 /* Support for the Qbtrace-conf:bts:size packet. */
1390 PACKET_Qbtrace_conf_bts_size,
1391
f7e6eed5
PA
1392 /* Support for swbreak+ feature. */
1393 PACKET_swbreak_feature,
1394
1395 /* Support for hwbreak+ feature. */
1396 PACKET_hwbreak_feature,
1397
89245bc0
DB
1398 /* Support for fork events. */
1399 PACKET_fork_event_feature,
1400
1401 /* Support for vfork events. */
1402 PACKET_vfork_event_feature,
1403
b20a6524
MM
1404 /* Support for the Qbtrace-conf:pt:size packet. */
1405 PACKET_Qbtrace_conf_pt_size,
1406
444abaca
DJ
1407 PACKET_MAX
1408};
506fb367 1409
444abaca 1410static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1411
f7e6eed5
PA
1412/* Returns the packet's corresponding "set remote foo-packet" command
1413 state. See struct packet_config for more details. */
1414
1415static enum auto_boolean
1416packet_set_cmd_state (int packet)
1417{
1418 return remote_protocol_packets[packet].detect;
1419}
1420
4082afcc
PA
1421/* Returns whether a given packet or feature is supported. This takes
1422 into account the state of the corresponding "set remote foo-packet"
1423 command, which may be used to bypass auto-detection. */
dc8acb97 1424
4082afcc
PA
1425static enum packet_support
1426packet_config_support (struct packet_config *config)
1427{
1428 switch (config->detect)
444abaca 1429 {
4082afcc
PA
1430 case AUTO_BOOLEAN_TRUE:
1431 return PACKET_ENABLE;
1432 case AUTO_BOOLEAN_FALSE:
1433 return PACKET_DISABLE;
1434 case AUTO_BOOLEAN_AUTO:
1435 return config->support;
1436 default:
1437 gdb_assert_not_reached (_("bad switch"));
444abaca 1438 }
4082afcc
PA
1439}
1440
1441/* Same as packet_config_support, but takes the packet's enum value as
1442 argument. */
1443
1444static enum packet_support
1445packet_support (int packet)
1446{
1447 struct packet_config *config = &remote_protocol_packets[packet];
1448
1449 return packet_config_support (config);
dc8acb97
MS
1450}
1451
5a2468f5 1452static void
444abaca
DJ
1453show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1454 struct cmd_list_element *c,
1455 const char *value)
5a2468f5 1456{
444abaca 1457 struct packet_config *packet;
5a2468f5 1458
444abaca
DJ
1459 for (packet = remote_protocol_packets;
1460 packet < &remote_protocol_packets[PACKET_MAX];
1461 packet++)
1462 {
1463 if (&packet->detect == c->var)
1464 {
1465 show_packet_config_cmd (packet);
1466 return;
1467 }
1468 }
9b20d036 1469 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1470 c->name);
5a2468f5
JM
1471}
1472
d471ea57
AC
1473/* Should we try one of the 'Z' requests? */
1474
1475enum Z_packet_type
1476{
1477 Z_PACKET_SOFTWARE_BP,
1478 Z_PACKET_HARDWARE_BP,
1479 Z_PACKET_WRITE_WP,
1480 Z_PACKET_READ_WP,
1481 Z_PACKET_ACCESS_WP,
1482 NR_Z_PACKET_TYPES
1483};
96baa820 1484
d471ea57 1485/* For compatibility with older distributions. Provide a ``set remote
23860348 1486 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1487
7f19b9a2 1488static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1489
1490static void
fba45db2
KB
1491set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1492 struct cmd_list_element *c)
96baa820 1493{
d471ea57 1494 int i;
a744cf53 1495
d471ea57 1496 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1497 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1498}
1499
1500static void
08546159
AC
1501show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1502 struct cmd_list_element *c,
1503 const char *value)
96baa820 1504{
d471ea57 1505 int i;
a744cf53 1506
d471ea57
AC
1507 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1508 {
444abaca 1509 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1510 }
96baa820
JM
1511}
1512
4082afcc
PA
1513/* Returns true if the multi-process extensions are in effect. */
1514
1515static int
1516remote_multi_process_p (struct remote_state *rs)
1517{
1518 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1519}
1520
de0d863e
DB
1521/* Returns true if fork events are supported. */
1522
1523static int
1524remote_fork_event_p (struct remote_state *rs)
1525{
1526 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1527}
1528
c269dbdb
DB
1529/* Returns true if vfork events are supported. */
1530
1531static int
1532remote_vfork_event_p (struct remote_state *rs)
1533{
1534 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1535}
1536
cbb8991c
DB
1537/* Insert fork catchpoint target routine. If fork events are enabled
1538 then return success, nothing more to do. */
1539
1540static int
1541remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1542{
1543 struct remote_state *rs = get_remote_state ();
1544
1545 return !remote_fork_event_p (rs);
1546}
1547
1548/* Remove fork catchpoint target routine. Nothing to do, just
1549 return success. */
1550
1551static int
1552remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1553{
1554 return 0;
1555}
1556
1557/* Insert vfork catchpoint target routine. If vfork events are enabled
1558 then return success, nothing more to do. */
1559
1560static int
1561remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1562{
1563 struct remote_state *rs = get_remote_state ();
1564
1565 return !remote_vfork_event_p (rs);
1566}
1567
1568/* Remove vfork catchpoint target routine. Nothing to do, just
1569 return success. */
1570
1571static int
1572remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1573{
1574 return 0;
1575}
1576
23860348 1577/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1578static struct async_signal_handler *async_sigint_remote_twice_token;
1579static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1580
74531fed
PA
1581\f
1582/* Asynchronous signal handle registered as event loop source for
1583 when we have pending events ready to be passed to the core. */
1584
1585static struct async_event_handler *remote_async_inferior_event_token;
1586
c906108c
SS
1587\f
1588
79d7f229
PA
1589static ptid_t magic_null_ptid;
1590static ptid_t not_sent_ptid;
1591static ptid_t any_thread_ptid;
1592
0b16c5cf
PA
1593/* Find out if the stub attached to PID (and hence GDB should offer to
1594 detach instead of killing it when bailing out). */
1595
1596static int
1597remote_query_attached (int pid)
1598{
1599 struct remote_state *rs = get_remote_state ();
bba74b36 1600 size_t size = get_remote_packet_size ();
0b16c5cf 1601
4082afcc 1602 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1603 return 0;
1604
1605 if (remote_multi_process_p (rs))
bba74b36 1606 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1607 else
bba74b36 1608 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1609
1610 putpkt (rs->buf);
1611 getpkt (&rs->buf, &rs->buf_size, 0);
1612
1613 switch (packet_ok (rs->buf,
1554e9be 1614 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1615 {
1616 case PACKET_OK:
1617 if (strcmp (rs->buf, "1") == 0)
1618 return 1;
1619 break;
1620 case PACKET_ERROR:
1621 warning (_("Remote failure reply: %s"), rs->buf);
1622 break;
1623 case PACKET_UNKNOWN:
1624 break;
1625 }
1626
1627 return 0;
1628}
1629
49c62f2e
PA
1630/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1631 has been invented by GDB, instead of reported by the target. Since
1632 we can be connected to a remote system before before knowing about
1633 any inferior, mark the target with execution when we find the first
1634 inferior. If ATTACHED is 1, then we had just attached to this
1635 inferior. If it is 0, then we just created this inferior. If it
1636 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1637 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1638 attempt to open this inferior's executable as the main executable
1639 if no main executable is open already. */
1941c569
PA
1640
1641static struct inferior *
1b6e6f5c
GB
1642remote_add_inferior (int fake_pid_p, int pid, int attached,
1643 int try_open_exec)
1941c569 1644{
1941c569
PA
1645 struct inferior *inf;
1646
0b16c5cf
PA
1647 /* Check whether this process we're learning about is to be
1648 considered attached, or if is to be considered to have been
1649 spawned by the stub. */
1650 if (attached == -1)
1651 attached = remote_query_attached (pid);
1652
f5656ead 1653 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1654 {
1655 /* If the target shares code across all inferiors, then every
1656 attach adds a new inferior. */
1657 inf = add_inferior (pid);
1658
1659 /* ... and every inferior is bound to the same program space.
1660 However, each inferior may still have its own address
1661 space. */
1662 inf->aspace = maybe_new_address_space ();
1663 inf->pspace = current_program_space;
1664 }
1665 else
1666 {
1667 /* In the traditional debugging scenario, there's a 1-1 match
1668 between program/address spaces. We simply bind the inferior
1669 to the program space's address space. */
1670 inf = current_inferior ();
1671 inferior_appeared (inf, pid);
1672 }
1941c569 1673
0b16c5cf 1674 inf->attach_flag = attached;
49c62f2e 1675 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1676
1b6e6f5c
GB
1677 /* If no main executable is currently open then attempt to
1678 open the file that was executed to create this inferior. */
835205d0 1679 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1680 exec_file_locate_attach (pid, 1);
1681
1941c569
PA
1682 return inf;
1683}
1684
1685/* Add thread PTID to GDB's thread list. Tag it as executing/running
1686 according to RUNNING. */
1687
c906108c 1688static void
1941c569 1689remote_add_thread (ptid_t ptid, int running)
c906108c 1690{
b7ea362b
PA
1691 struct remote_state *rs = get_remote_state ();
1692
1693 /* GDB historically didn't pull threads in the initial connection
1694 setup. If the remote target doesn't even have a concept of
1695 threads (e.g., a bare-metal target), even if internally we
1696 consider that a single-threaded target, mentioning a new thread
1697 might be confusing to the user. Be silent then, preserving the
1698 age old behavior. */
1699 if (rs->starting_up)
1700 add_thread_silent (ptid);
1701 else
1702 add_thread (ptid);
1941c569
PA
1703
1704 set_executing (ptid, running);
1705 set_running (ptid, running);
1706}
1707
1708/* Come here when we learn about a thread id from the remote target.
1709 It may be the first time we hear about such thread, so take the
1710 opportunity to add it to GDB's thread list. In case this is the
1711 first time we're noticing its corresponding inferior, add it to
1712 GDB's inferior list as well. */
1713
1714static void
1715remote_notice_new_inferior (ptid_t currthread, int running)
1716{
c906108c
SS
1717 /* If this is a new thread, add it to GDB's thread list.
1718 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1719
1720 if (in_thread_list (currthread) && is_exited (currthread))
1721 {
1722 /* We're seeing an event on a thread id we knew had exited.
1723 This has to be a new thread reusing the old id. Add it. */
1941c569 1724 remote_add_thread (currthread, running);
82f73884
PA
1725 return;
1726 }
1727
79d7f229 1728 if (!in_thread_list (currthread))
c0a2216e 1729 {
1941c569 1730 struct inferior *inf = NULL;
bad34192 1731 int pid = ptid_get_pid (currthread);
1941c569 1732
bad34192
PA
1733 if (ptid_is_pid (inferior_ptid)
1734 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1735 {
1736 /* inferior_ptid has no thread member yet. This can happen
1737 with the vAttach -> remote_wait,"TAAthread:" path if the
1738 stub doesn't support qC. This is the first stop reported
1739 after an attach, so this is the main thread. Update the
1740 ptid in the thread list. */
bad34192
PA
1741 if (in_thread_list (pid_to_ptid (pid)))
1742 thread_change_ptid (inferior_ptid, currthread);
1743 else
1744 {
1745 remote_add_thread (currthread, running);
1746 inferior_ptid = currthread;
1747 }
dc146f7c 1748 return;
c0a2216e 1749 }
82f73884
PA
1750
1751 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1752 {
1753 /* inferior_ptid is not set yet. This can happen with the
1754 vRun -> remote_wait,"TAAthread:" path if the stub
1755 doesn't support qC. This is the first stop reported
1756 after an attach, so this is the main thread. Update the
1757 ptid in the thread list. */
dc146f7c 1758 thread_change_ptid (inferior_ptid, currthread);
82f73884 1759 return;
c0a2216e 1760 }
82f73884 1761
29c87f7f
PA
1762 /* When connecting to a target remote, or to a target
1763 extended-remote which already was debugging an inferior, we
1764 may not know about it yet. Add it before adding its child
1765 thread, so notifications are emitted in a sensible order. */
1766 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1767 {
1768 struct remote_state *rs = get_remote_state ();
1769 int fake_pid_p = !remote_multi_process_p (rs);
1770
1771 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1772 ptid_get_pid (currthread), -1, 1);
49c62f2e 1773 }
29c87f7f 1774
82f73884 1775 /* This is really a new thread. Add it. */
1941c569
PA
1776 remote_add_thread (currthread, running);
1777
1778 /* If we found a new inferior, let the common code do whatever
1779 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1780 breakpoints), unless we're just setting up an all-stop
1781 connection. */
1941c569 1782 if (inf != NULL)
b7ea362b
PA
1783 {
1784 struct remote_state *rs = get_remote_state ();
1785
1786 if (non_stop || !rs->starting_up)
1787 notice_new_inferior (currthread, running, 0);
1788 }
c0a2216e 1789 }
c906108c
SS
1790}
1791
dc146f7c
VP
1792/* Return the private thread data, creating it if necessary. */
1793
70221824 1794static struct private_thread_info *
dc146f7c
VP
1795demand_private_info (ptid_t ptid)
1796{
1797 struct thread_info *info = find_thread_ptid (ptid);
1798
1799 gdb_assert (info);
1800
fe978cb0 1801 if (!info->priv)
dc146f7c 1802 {
8d749320 1803 info->priv = XNEW (struct private_thread_info);
dc146f7c 1804 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1805 info->priv->core = -1;
1806 info->priv->extra = 0;
dc146f7c
VP
1807 }
1808
fe978cb0 1809 return info->priv;
dc146f7c
VP
1810}
1811
74531fed
PA
1812/* Call this function as a result of
1813 1) A halt indication (T packet) containing a thread id
1814 2) A direct query of currthread
0df8b418 1815 3) Successful execution of set thread */
74531fed
PA
1816
1817static void
47f8a51d 1818record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1819{
47f8a51d 1820 rs->general_thread = currthread;
74531fed
PA
1821}
1822
89be2091
DJ
1823/* If 'QPassSignals' is supported, tell the remote stub what signals
1824 it can simply pass through to the inferior without reporting. */
1825
1826static void
94bedb42
TT
1827remote_pass_signals (struct target_ops *self,
1828 int numsigs, unsigned char *pass_signals)
89be2091 1829{
4082afcc 1830 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1831 {
1832 char *pass_packet, *p;
89be2091 1833 int count = 0, i;
747dc59d 1834 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1835
1836 gdb_assert (numsigs < 256);
1837 for (i = 0; i < numsigs; i++)
1838 {
2455069d 1839 if (pass_signals[i])
89be2091
DJ
1840 count++;
1841 }
1842 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1843 strcpy (pass_packet, "QPassSignals:");
1844 p = pass_packet + strlen (pass_packet);
1845 for (i = 0; i < numsigs; i++)
1846 {
2455069d 1847 if (pass_signals[i])
89be2091
DJ
1848 {
1849 if (i >= 16)
1850 *p++ = tohex (i >> 4);
1851 *p++ = tohex (i & 15);
1852 if (count)
1853 *p++ = ';';
1854 else
1855 break;
1856 count--;
1857 }
1858 }
1859 *p = 0;
747dc59d 1860 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1861 {
89be2091
DJ
1862 putpkt (pass_packet);
1863 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1864 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1865 if (rs->last_pass_packet)
1866 xfree (rs->last_pass_packet);
1867 rs->last_pass_packet = pass_packet;
89be2091
DJ
1868 }
1869 else
1870 xfree (pass_packet);
1871 }
1872}
1873
9b224c5e
PA
1874/* If 'QProgramSignals' is supported, tell the remote stub what
1875 signals it should pass through to the inferior when detaching. */
1876
1877static void
daf5e9b6
TT
1878remote_program_signals (struct target_ops *self,
1879 int numsigs, unsigned char *signals)
9b224c5e 1880{
4082afcc 1881 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1882 {
1883 char *packet, *p;
1884 int count = 0, i;
5e4a05c4 1885 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1886
1887 gdb_assert (numsigs < 256);
1888 for (i = 0; i < numsigs; i++)
1889 {
1890 if (signals[i])
1891 count++;
1892 }
1893 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1894 strcpy (packet, "QProgramSignals:");
1895 p = packet + strlen (packet);
1896 for (i = 0; i < numsigs; i++)
1897 {
1898 if (signal_pass_state (i))
1899 {
1900 if (i >= 16)
1901 *p++ = tohex (i >> 4);
1902 *p++ = tohex (i & 15);
1903 if (count)
1904 *p++ = ';';
1905 else
1906 break;
1907 count--;
1908 }
1909 }
1910 *p = 0;
5e4a05c4
TT
1911 if (!rs->last_program_signals_packet
1912 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1913 {
9b224c5e
PA
1914 putpkt (packet);
1915 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1916 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1917 xfree (rs->last_program_signals_packet);
1918 rs->last_program_signals_packet = packet;
9b224c5e
PA
1919 }
1920 else
1921 xfree (packet);
1922 }
1923}
1924
79d7f229
PA
1925/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1926 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1927 thread. If GEN is set, set the general thread, if not, then set
1928 the step/continue thread. */
c906108c 1929static void
79d7f229 1930set_thread (struct ptid ptid, int gen)
c906108c 1931{
d01949b6 1932 struct remote_state *rs = get_remote_state ();
47f8a51d 1933 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1934 char *buf = rs->buf;
79d7f229 1935 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1936
79d7f229 1937 if (ptid_equal (state, ptid))
c906108c
SS
1938 return;
1939
79d7f229
PA
1940 *buf++ = 'H';
1941 *buf++ = gen ? 'g' : 'c';
1942 if (ptid_equal (ptid, magic_null_ptid))
1943 xsnprintf (buf, endbuf - buf, "0");
1944 else if (ptid_equal (ptid, any_thread_ptid))
1945 xsnprintf (buf, endbuf - buf, "0");
1946 else if (ptid_equal (ptid, minus_one_ptid))
1947 xsnprintf (buf, endbuf - buf, "-1");
1948 else
82f73884 1949 write_ptid (buf, endbuf, ptid);
79d7f229 1950 putpkt (rs->buf);
6d820c5c 1951 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1952 if (gen)
47f8a51d 1953 rs->general_thread = ptid;
c906108c 1954 else
47f8a51d 1955 rs->continue_thread = ptid;
c906108c 1956}
79d7f229
PA
1957
1958static void
1959set_general_thread (struct ptid ptid)
1960{
1961 set_thread (ptid, 1);
1962}
1963
1964static void
1965set_continue_thread (struct ptid ptid)
1966{
1967 set_thread (ptid, 0);
1968}
1969
3c9c4b83
PA
1970/* Change the remote current process. Which thread within the process
1971 ends up selected isn't important, as long as it is the same process
1972 as what INFERIOR_PTID points to.
1973
1974 This comes from that fact that there is no explicit notion of
1975 "selected process" in the protocol. The selected process for
1976 general operations is the process the selected general thread
1977 belongs to. */
1978
1979static void
1980set_general_process (void)
1981{
1982 struct remote_state *rs = get_remote_state ();
1983
1984 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1985 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1986 return;
1987
1988 /* We only need to change the remote current thread if it's pointing
1989 at some other process. */
47f8a51d 1990 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1991 set_general_thread (inferior_ptid);
1992}
1993
c906108c 1994\f
7d1a114c
PA
1995/* Return nonzero if this is the main thread that we made up ourselves
1996 to model non-threaded targets as single-threaded. */
c906108c
SS
1997
1998static int
7d1a114c 1999remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2000{
6d820c5c 2001 struct remote_state *rs = get_remote_state ();
82f73884 2002 char *p, *endp;
c906108c 2003
c0a2216e
PA
2004 if (ptid_equal (ptid, magic_null_ptid))
2005 /* The main thread is always alive. */
2006 return 1;
2007
ba348170 2008 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2009 /* The main thread is always alive. This can happen after a
2010 vAttach, if the remote side doesn't support
2011 multi-threading. */
2012 return 1;
2013
7d1a114c
PA
2014 return 0;
2015}
2016
2017/* Return nonzero if the thread PTID is still alive on the remote
2018 system. */
2019
2020static int
2021remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2022{
2023 struct remote_state *rs = get_remote_state ();
2024 char *p, *endp;
2025
2026 /* Check if this is a thread that we made up ourselves to model
2027 non-threaded targets as single-threaded. */
2028 if (remote_thread_always_alive (ops, ptid))
2029 return 1;
2030
82f73884
PA
2031 p = rs->buf;
2032 endp = rs->buf + get_remote_packet_size ();
2033
2034 *p++ = 'T';
2035 write_ptid (p, endp, ptid);
2036
2e9f7625 2037 putpkt (rs->buf);
6d820c5c 2038 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2039 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2040}
2041
2042/* About these extended threadlist and threadinfo packets. They are
2043 variable length packets but, the fields within them are often fixed
2044 length. They are redundent enough to send over UDP as is the
2045 remote protocol in general. There is a matching unit test module
2046 in libstub. */
2047
23860348 2048/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2049 libstub protocol encoding, and remote.c. It is not particularly
23860348 2050 changable. */
cce74817
JM
2051
2052/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2053 Plan to fix this. */
cce74817 2054
23860348 2055typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2056
9d1f7ab2 2057/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2058 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2059
2060struct gdb_ext_thread_info
c5aa993b 2061 {
23860348 2062 threadref threadid; /* External form of thread reference. */
2bc416ba 2063 int active; /* Has state interesting to GDB?
23860348 2064 regs, stack. */
2bc416ba 2065 char display[256]; /* Brief state display, name,
cedea757 2066 blocked/suspended. */
23860348 2067 char shortname[32]; /* To be used to name threads. */
2bc416ba 2068 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2069 whatever. */
c5aa993b 2070 };
cce74817
JM
2071
2072/* The volume of remote transfers can be limited by submitting
2073 a mask containing bits specifying the desired information.
2074 Use a union of these values as the 'selection' parameter to
0df8b418 2075 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2076
2077#define TAG_THREADID 1
2078#define TAG_EXISTS 2
2079#define TAG_DISPLAY 4
2080#define TAG_THREADNAME 8
c5aa993b 2081#define TAG_MOREDISPLAY 16
cce74817 2082
23860348 2083#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2084
a14ed312 2085static char *unpack_nibble (char *buf, int *val);
cce74817 2086
a14ed312 2087static char *unpack_byte (char *buf, int *value);
cce74817 2088
a14ed312 2089static char *pack_int (char *buf, int value);
cce74817 2090
a14ed312 2091static char *unpack_int (char *buf, int *value);
cce74817 2092
a14ed312 2093static char *unpack_string (char *src, char *dest, int length);
cce74817 2094
23860348 2095static char *pack_threadid (char *pkt, threadref *id);
cce74817 2096
23860348 2097static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2098
23860348 2099void int_to_threadref (threadref *id, int value);
cce74817 2100
23860348 2101static int threadref_to_int (threadref *ref);
cce74817 2102
23860348 2103static void copy_threadref (threadref *dest, threadref *src);
cce74817 2104
23860348 2105static int threadmatch (threadref *dest, threadref *src);
cce74817 2106
2bc416ba 2107static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2108 threadref *id);
cce74817 2109
a14ed312 2110static int remote_unpack_thread_info_response (char *pkt,
23860348 2111 threadref *expectedref,
a14ed312
KB
2112 struct gdb_ext_thread_info
2113 *info);
cce74817
JM
2114
2115
2bc416ba 2116static int remote_get_threadinfo (threadref *threadid,
23860348 2117 int fieldset, /*TAG mask */
a14ed312 2118 struct gdb_ext_thread_info *info);
cce74817 2119
a14ed312
KB
2120static char *pack_threadlist_request (char *pkt, int startflag,
2121 int threadcount,
23860348 2122 threadref *nextthread);
cce74817 2123
a14ed312
KB
2124static int parse_threadlist_response (char *pkt,
2125 int result_limit,
23860348 2126 threadref *original_echo,
2bc416ba 2127 threadref *resultlist,
23860348 2128 int *doneflag);
cce74817 2129
a14ed312 2130static int remote_get_threadlist (int startflag,
23860348 2131 threadref *nextthread,
a14ed312
KB
2132 int result_limit,
2133 int *done,
2bc416ba 2134 int *result_count,
23860348 2135 threadref *threadlist);
cce74817 2136
23860348 2137typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2138
a14ed312
KB
2139static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2140 void *context, int looplimit);
cce74817 2141
23860348 2142static int remote_newthread_step (threadref *ref, void *context);
cce74817 2143
82f73884
PA
2144
2145/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2146 buffer we're allowed to write to. Returns
2147 BUF+CHARACTERS_WRITTEN. */
2148
2149static char *
2150write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2151{
2152 int pid, tid;
2153 struct remote_state *rs = get_remote_state ();
2154
2155 if (remote_multi_process_p (rs))
2156 {
2157 pid = ptid_get_pid (ptid);
2158 if (pid < 0)
2159 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2160 else
2161 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2162 }
ba348170 2163 tid = ptid_get_lwp (ptid);
82f73884
PA
2164 if (tid < 0)
2165 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2166 else
2167 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2168
2169 return buf;
2170}
2171
2172/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2173 passed the last parsed char. Returns null_ptid on error. */
2174
2175static ptid_t
2176read_ptid (char *buf, char **obuf)
2177{
2178 char *p = buf;
2179 char *pp;
2180 ULONGEST pid = 0, tid = 0;
82f73884
PA
2181
2182 if (*p == 'p')
2183 {
2184 /* Multi-process ptid. */
2185 pp = unpack_varlen_hex (p + 1, &pid);
2186 if (*pp != '.')
b37520b6 2187 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2188
2189 p = pp;
2190 pp = unpack_varlen_hex (p + 1, &tid);
2191 if (obuf)
2192 *obuf = pp;
ba348170 2193 return ptid_build (pid, tid, 0);
82f73884
PA
2194 }
2195
2196 /* No multi-process. Just a tid. */
2197 pp = unpack_varlen_hex (p, &tid);
2198
c9f35b34
KB
2199 /* Return null_ptid when no thread id is found. */
2200 if (p == pp)
2201 {
2202 if (obuf)
2203 *obuf = pp;
2204 return null_ptid;
2205 }
2206
82f73884 2207 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2208 what's in inferior_ptid, unless it's null at this point. If so,
2209 then since there's no way to know the pid of the reported
2210 threads, use the magic number. */
2211 if (ptid_equal (inferior_ptid, null_ptid))
2212 pid = ptid_get_pid (magic_null_ptid);
2213 else
2214 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2215
2216 if (obuf)
2217 *obuf = pp;
ba348170 2218 return ptid_build (pid, tid, 0);
82f73884
PA
2219}
2220
c906108c 2221static int
fba45db2 2222stubhex (int ch)
c906108c
SS
2223{
2224 if (ch >= 'a' && ch <= 'f')
2225 return ch - 'a' + 10;
2226 if (ch >= '0' && ch <= '9')
2227 return ch - '0';
2228 if (ch >= 'A' && ch <= 'F')
2229 return ch - 'A' + 10;
2230 return -1;
2231}
2232
2233static int
fba45db2 2234stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2235{
2236 int nibble;
2237 int retval = 0;
2238
2239 while (fieldlength)
2240 {
2241 nibble = stubhex (*buff++);
2242 retval |= nibble;
2243 fieldlength--;
2244 if (fieldlength)
2245 retval = retval << 4;
2246 }
2247 return retval;
2248}
2249
c906108c 2250static char *
fba45db2 2251unpack_nibble (char *buf, int *val)
c906108c 2252{
b7589f7d 2253 *val = fromhex (*buf++);
c906108c
SS
2254 return buf;
2255}
2256
c906108c 2257static char *
fba45db2 2258unpack_byte (char *buf, int *value)
c906108c
SS
2259{
2260 *value = stub_unpack_int (buf, 2);
2261 return buf + 2;
2262}
2263
2264static char *
fba45db2 2265pack_int (char *buf, int value)
c906108c
SS
2266{
2267 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2268 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2269 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2270 buf = pack_hex_byte (buf, (value & 0xff));
2271 return buf;
2272}
2273
2274static char *
fba45db2 2275unpack_int (char *buf, int *value)
c906108c
SS
2276{
2277 *value = stub_unpack_int (buf, 8);
2278 return buf + 8;
2279}
2280
23860348 2281#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2282static char *pack_string (char *pkt, char *string);
c906108c
SS
2283
2284static char *
fba45db2 2285pack_string (char *pkt, char *string)
c906108c
SS
2286{
2287 char ch;
2288 int len;
2289
2290 len = strlen (string);
2291 if (len > 200)
23860348 2292 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2293 pkt = pack_hex_byte (pkt, len);
2294 while (len-- > 0)
2295 {
2296 ch = *string++;
2297 if ((ch == '\0') || (ch == '#'))
23860348 2298 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2299 *pkt++ = ch;
2300 }
2301 return pkt;
2302}
2303#endif /* 0 (unused) */
2304
2305static char *
fba45db2 2306unpack_string (char *src, char *dest, int length)
c906108c
SS
2307{
2308 while (length--)
2309 *dest++ = *src++;
2310 *dest = '\0';
2311 return src;
2312}
2313
2314static char *
fba45db2 2315pack_threadid (char *pkt, threadref *id)
c906108c
SS
2316{
2317 char *limit;
2318 unsigned char *altid;
2319
2320 altid = (unsigned char *) id;
2321 limit = pkt + BUF_THREAD_ID_SIZE;
2322 while (pkt < limit)
2323 pkt = pack_hex_byte (pkt, *altid++);
2324 return pkt;
2325}
2326
2327
2328static char *
fba45db2 2329unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2330{
2331 char *altref;
2332 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2333 int x, y;
2334
2335 altref = (char *) id;
2336
2337 while (inbuf < limit)
2338 {
2339 x = stubhex (*inbuf++);
2340 y = stubhex (*inbuf++);
2341 *altref++ = (x << 4) | y;
2342 }
2343 return inbuf;
2344}
2345
2346/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2347 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2348 to use 64bit thread references internally. This is an adapter
2349 function. */
2350
2351void
fba45db2 2352int_to_threadref (threadref *id, int value)
c906108c
SS
2353{
2354 unsigned char *scan;
2355
2356 scan = (unsigned char *) id;
2357 {
2358 int i = 4;
2359 while (i--)
2360 *scan++ = 0;
2361 }
2362 *scan++ = (value >> 24) & 0xff;
2363 *scan++ = (value >> 16) & 0xff;
2364 *scan++ = (value >> 8) & 0xff;
2365 *scan++ = (value & 0xff);
2366}
2367
2368static int
fba45db2 2369threadref_to_int (threadref *ref)
c906108c
SS
2370{
2371 int i, value = 0;
2372 unsigned char *scan;
2373
cfd77fa1 2374 scan = *ref;
c906108c
SS
2375 scan += 4;
2376 i = 4;
2377 while (i-- > 0)
2378 value = (value << 8) | ((*scan++) & 0xff);
2379 return value;
2380}
2381
2382static void
fba45db2 2383copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2384{
2385 int i;
2386 unsigned char *csrc, *cdest;
2387
2388 csrc = (unsigned char *) src;
2389 cdest = (unsigned char *) dest;
2390 i = 8;
2391 while (i--)
2392 *cdest++ = *csrc++;
2393}
2394
2395static int
fba45db2 2396threadmatch (threadref *dest, threadref *src)
c906108c 2397{
23860348 2398 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2399#if 0
2400 unsigned char *srcp, *destp;
2401 int i, result;
2402 srcp = (char *) src;
2403 destp = (char *) dest;
2404
2405 result = 1;
2406 while (i-- > 0)
2407 result &= (*srcp++ == *destp++) ? 1 : 0;
2408 return result;
2409#endif
2410 return 1;
2411}
2412
2413/*
c5aa993b
JM
2414 threadid:1, # always request threadid
2415 context_exists:2,
2416 display:4,
2417 unique_name:8,
2418 more_display:16
2419 */
c906108c
SS
2420
2421/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2422
2423static char *
fba45db2 2424pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2425{
23860348
MS
2426 *pkt++ = 'q'; /* Info Query */
2427 *pkt++ = 'P'; /* process or thread info */
2428 pkt = pack_int (pkt, mode); /* mode */
c906108c 2429 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2430 *pkt = '\0'; /* terminate */
c906108c
SS
2431 return pkt;
2432}
2433
23860348 2434/* These values tag the fields in a thread info response packet. */
c906108c 2435/* Tagging the fields allows us to request specific fields and to
23860348 2436 add more fields as time goes by. */
c906108c 2437
23860348 2438#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2439#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2440 fetch registers and its stack? */
c5aa993b 2441#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2442#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2443#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2444 the process. */
c906108c
SS
2445
2446static int
fba45db2
KB
2447remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2448 struct gdb_ext_thread_info *info)
c906108c 2449{
d01949b6 2450 struct remote_state *rs = get_remote_state ();
c906108c 2451 int mask, length;
cfd77fa1 2452 int tag;
c906108c 2453 threadref ref;
6d820c5c 2454 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2455 int retval = 1;
2456
23860348 2457 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2458 info->active = 0;
2459 info->display[0] = '\0';
2460 info->shortname[0] = '\0';
2461 info->more_display[0] = '\0';
2462
23860348
MS
2463 /* Assume the characters indicating the packet type have been
2464 stripped. */
c906108c
SS
2465 pkt = unpack_int (pkt, &mask); /* arg mask */
2466 pkt = unpack_threadid (pkt, &ref);
2467
2468 if (mask == 0)
8a3fe4f8 2469 warning (_("Incomplete response to threadinfo request."));
c906108c 2470 if (!threadmatch (&ref, expectedref))
23860348 2471 { /* This is an answer to a different request. */
8a3fe4f8 2472 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2473 return 0;
2474 }
2475 copy_threadref (&info->threadid, &ref);
2476
23860348 2477 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2478
23860348
MS
2479 /* Packets are terminated with nulls. */
2480 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2481 {
2482 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2483 pkt = unpack_byte (pkt, &length); /* length */
2484 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2485 {
8a3fe4f8 2486 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2487 retval = 0;
2488 break;
2489 }
2490 if (tag == TAG_THREADID)
2491 {
2492 if (length != 16)
2493 {
8a3fe4f8 2494 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2495 retval = 0;
2496 break;
2497 }
2498 pkt = unpack_threadid (pkt, &ref);
2499 mask = mask & ~TAG_THREADID;
2500 continue;
2501 }
2502 if (tag == TAG_EXISTS)
2503 {
2504 info->active = stub_unpack_int (pkt, length);
2505 pkt += length;
2506 mask = mask & ~(TAG_EXISTS);
2507 if (length > 8)
2508 {
8a3fe4f8 2509 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2510 retval = 0;
2511 break;
2512 }
2513 continue;
2514 }
2515 if (tag == TAG_THREADNAME)
2516 {
2517 pkt = unpack_string (pkt, &info->shortname[0], length);
2518 mask = mask & ~TAG_THREADNAME;
2519 continue;
2520 }
2521 if (tag == TAG_DISPLAY)
2522 {
2523 pkt = unpack_string (pkt, &info->display[0], length);
2524 mask = mask & ~TAG_DISPLAY;
2525 continue;
2526 }
2527 if (tag == TAG_MOREDISPLAY)
2528 {
2529 pkt = unpack_string (pkt, &info->more_display[0], length);
2530 mask = mask & ~TAG_MOREDISPLAY;
2531 continue;
2532 }
8a3fe4f8 2533 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2534 break; /* Not a tag we know about. */
c906108c
SS
2535 }
2536 return retval;
2537}
2538
2539static int
fba45db2
KB
2540remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2541 struct gdb_ext_thread_info *info)
c906108c 2542{
d01949b6 2543 struct remote_state *rs = get_remote_state ();
c906108c 2544 int result;
c906108c 2545
2e9f7625
DJ
2546 pack_threadinfo_request (rs->buf, fieldset, threadid);
2547 putpkt (rs->buf);
6d820c5c 2548 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2549
2550 if (rs->buf[0] == '\0')
2551 return 0;
2552
2e9f7625 2553 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2554 threadid, info);
c906108c
SS
2555 return result;
2556}
2557
c906108c
SS
2558/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2559
2560static char *
fba45db2
KB
2561pack_threadlist_request (char *pkt, int startflag, int threadcount,
2562 threadref *nextthread)
c906108c
SS
2563{
2564 *pkt++ = 'q'; /* info query packet */
2565 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2566 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2567 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2568 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2569 *pkt = '\0';
2570 return pkt;
2571}
2572
2573/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2574
2575static int
fba45db2
KB
2576parse_threadlist_response (char *pkt, int result_limit,
2577 threadref *original_echo, threadref *resultlist,
2578 int *doneflag)
c906108c 2579{
d01949b6 2580 struct remote_state *rs = get_remote_state ();
c906108c
SS
2581 char *limit;
2582 int count, resultcount, done;
2583
2584 resultcount = 0;
2585 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2586 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2587 /* done parse past here */
c906108c
SS
2588 pkt = unpack_byte (pkt, &count); /* count field */
2589 pkt = unpack_nibble (pkt, &done);
2590 /* The first threadid is the argument threadid. */
2591 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2592 while ((count-- > 0) && (pkt < limit))
2593 {
2594 pkt = unpack_threadid (pkt, resultlist++);
2595 if (resultcount++ >= result_limit)
2596 break;
2597 }
2598 if (doneflag)
2599 *doneflag = done;
2600 return resultcount;
2601}
2602
6dc54d91
PA
2603/* Fetch the next batch of threads from the remote. Returns -1 if the
2604 qL packet is not supported, 0 on error and 1 on success. */
2605
c906108c 2606static int
fba45db2
KB
2607remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2608 int *done, int *result_count, threadref *threadlist)
c906108c 2609{
d01949b6 2610 struct remote_state *rs = get_remote_state ();
c906108c
SS
2611 int result = 1;
2612
23860348 2613 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2614 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2615 >= get_remote_packet_size ())
ea9c271d 2616 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2617
6d820c5c
DJ
2618 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2619 putpkt (rs->buf);
2620 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2621 if (*rs->buf == '\0')
6dc54d91
PA
2622 {
2623 /* Packet not supported. */
2624 return -1;
2625 }
2626
2627 *result_count =
2628 parse_threadlist_response (rs->buf + 2, result_limit,
2629 &rs->echo_nextthread, threadlist, done);
c906108c 2630
0d031856 2631 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2632 {
23860348
MS
2633 /* FIXME: This is a good reason to drop the packet. */
2634 /* Possably, there is a duplicate response. */
c906108c
SS
2635 /* Possabilities :
2636 retransmit immediatly - race conditions
2637 retransmit after timeout - yes
2638 exit
2639 wait for packet, then exit
2640 */
8a3fe4f8 2641 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2642 return 0; /* I choose simply exiting. */
c906108c
SS
2643 }
2644 if (*result_count <= 0)
2645 {
2646 if (*done != 1)
2647 {
8a3fe4f8 2648 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2649 result = 0;
2650 }
2651 return result; /* break; */
2652 }
2653 if (*result_count > result_limit)
2654 {
2655 *result_count = 0;
8a3fe4f8 2656 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2657 return 0;
2658 }
2659 return result;
2660}
2661
6dc54d91
PA
2662/* Fetch the list of remote threads, with the qL packet, and call
2663 STEPFUNCTION for each thread found. Stops iterating and returns 1
2664 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2665 STEPFUNCTION returns false. If the packet is not supported,
2666 returns -1. */
c906108c 2667
c906108c 2668static int
fba45db2
KB
2669remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2670 int looplimit)
c906108c 2671{
0d031856 2672 struct remote_state *rs = get_remote_state ();
c906108c
SS
2673 int done, i, result_count;
2674 int startflag = 1;
2675 int result = 1;
2676 int loopcount = 0;
c906108c
SS
2677
2678 done = 0;
2679 while (!done)
2680 {
2681 if (loopcount++ > looplimit)
2682 {
2683 result = 0;
8a3fe4f8 2684 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2685 break;
2686 }
6dc54d91
PA
2687 result = remote_get_threadlist (startflag, &rs->nextthread,
2688 MAXTHREADLISTRESULTS,
2689 &done, &result_count,
2690 rs->resultthreadlist);
2691 if (result <= 0)
2692 break;
23860348 2693 /* Clear for later iterations. */
c906108c
SS
2694 startflag = 0;
2695 /* Setup to resume next batch of thread references, set nextthread. */
2696 if (result_count >= 1)
0d031856
TT
2697 copy_threadref (&rs->nextthread,
2698 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2699 i = 0;
2700 while (result_count--)
6dc54d91
PA
2701 {
2702 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2703 {
2704 result = 0;
2705 break;
2706 }
2707 }
c906108c
SS
2708 }
2709 return result;
2710}
2711
6dc54d91
PA
2712/* A thread found on the remote target. */
2713
2714typedef struct thread_item
2715{
2716 /* The thread's PTID. */
2717 ptid_t ptid;
2718
2719 /* The thread's extra info. May be NULL. */
2720 char *extra;
2721
2722 /* The core the thread was running on. -1 if not known. */
2723 int core;
2724} thread_item_t;
2725DEF_VEC_O(thread_item_t);
2726
2727/* Context passed around to the various methods listing remote
2728 threads. As new threads are found, they're added to the ITEMS
2729 vector. */
2730
2731struct threads_listing_context
2732{
2733 /* The threads found on the remote target. */
2734 VEC (thread_item_t) *items;
2735};
2736
80134cf5
PA
2737/* Discard the contents of the constructed thread listing context. */
2738
2739static void
2740clear_threads_listing_context (void *p)
2741{
2742 struct threads_listing_context *context = p;
2743 int i;
2744 struct thread_item *item;
2745
2746 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2747 xfree (item->extra);
2748
2749 VEC_free (thread_item_t, context->items);
2750}
2751
cbb8991c
DB
2752/* Remove the thread specified as the related_pid field of WS
2753 from the CONTEXT list. */
2754
2755static void
2756threads_listing_context_remove (struct target_waitstatus *ws,
2757 struct threads_listing_context *context)
2758{
2759 struct thread_item *item;
2760 int i;
2761 ptid_t child_ptid = ws->value.related_pid;
2762
2763 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2764 {
2765 if (ptid_equal (item->ptid, child_ptid))
2766 {
2767 VEC_ordered_remove (thread_item_t, context->items, i);
2768 break;
2769 }
2770 }
2771}
2772
c906108c 2773static int
6dc54d91 2774remote_newthread_step (threadref *ref, void *data)
c906108c 2775{
6dc54d91
PA
2776 struct threads_listing_context *context = data;
2777 struct thread_item item;
79d7f229 2778 int pid = ptid_get_pid (inferior_ptid);
39f77062 2779
6dc54d91
PA
2780 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2781 item.core = -1;
2782 item.extra = NULL;
2783
2784 VEC_safe_push (thread_item_t, context->items, &item);
2785
c906108c
SS
2786 return 1; /* continue iterator */
2787}
2788
2789#define CRAZY_MAX_THREADS 1000
2790
39f77062
KB
2791static ptid_t
2792remote_current_thread (ptid_t oldpid)
c906108c 2793{
d01949b6 2794 struct remote_state *rs = get_remote_state ();
c906108c
SS
2795
2796 putpkt ("qC");
6d820c5c 2797 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2798 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
2799 {
2800 char *obuf;
2801 ptid_t result;
2802
2803 result = read_ptid (&rs->buf[2], &obuf);
2804 if (*obuf != '\0' && remote_debug)
2805 fprintf_unfiltered (gdb_stdlog,
2806 "warning: garbage in qC reply\n");
2807
2808 return result;
2809 }
c906108c
SS
2810 else
2811 return oldpid;
2812}
2813
6dc54d91 2814/* List remote threads using the deprecated qL packet. */
cce74817 2815
6dc54d91
PA
2816static int
2817remote_get_threads_with_ql (struct target_ops *ops,
2818 struct threads_listing_context *context)
c906108c 2819{
6dc54d91
PA
2820 if (remote_threadlist_iterator (remote_newthread_step, context,
2821 CRAZY_MAX_THREADS) >= 0)
2822 return 1;
2823
2824 return 0;
c906108c
SS
2825}
2826
dc146f7c
VP
2827#if defined(HAVE_LIBEXPAT)
2828
dc146f7c
VP
2829static void
2830start_thread (struct gdb_xml_parser *parser,
2831 const struct gdb_xml_element *element,
2832 void *user_data, VEC(gdb_xml_value_s) *attributes)
2833{
6dc54d91 2834 struct threads_listing_context *data = user_data;
dc146f7c
VP
2835
2836 struct thread_item item;
2837 char *id;
3d2c1d41 2838 struct gdb_xml_value *attr;
dc146f7c 2839
3d2c1d41 2840 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2841 item.ptid = read_ptid (id, NULL);
2842
3d2c1d41
PA
2843 attr = xml_find_attribute (attributes, "core");
2844 if (attr != NULL)
2845 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2846 else
2847 item.core = -1;
2848
2849 item.extra = 0;
2850
2851 VEC_safe_push (thread_item_t, data->items, &item);
2852}
2853
2854static void
2855end_thread (struct gdb_xml_parser *parser,
2856 const struct gdb_xml_element *element,
2857 void *user_data, const char *body_text)
2858{
6dc54d91 2859 struct threads_listing_context *data = user_data;
dc146f7c
VP
2860
2861 if (body_text && *body_text)
2ae2a0b7 2862 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2863}
2864
2865const struct gdb_xml_attribute thread_attributes[] = {
2866 { "id", GDB_XML_AF_NONE, NULL, NULL },
2867 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2868 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2869};
2870
2871const struct gdb_xml_element thread_children[] = {
2872 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2873};
2874
2875const struct gdb_xml_element threads_children[] = {
2876 { "thread", thread_attributes, thread_children,
2877 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2878 start_thread, end_thread },
2879 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2880};
2881
2882const struct gdb_xml_element threads_elements[] = {
2883 { "threads", NULL, threads_children,
2884 GDB_XML_EF_NONE, NULL, NULL },
2885 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2886};
2887
2888#endif
2889
6dc54d91 2890/* List remote threads using qXfer:threads:read. */
9d1f7ab2 2891
6dc54d91
PA
2892static int
2893remote_get_threads_with_qxfer (struct target_ops *ops,
2894 struct threads_listing_context *context)
0f71a2f6 2895{
dc146f7c 2896#if defined(HAVE_LIBEXPAT)
4082afcc 2897 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 2898 {
6dc54d91 2899 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 2900 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2901
6dc54d91 2902 if (xml != NULL && *xml != '\0')
dc146f7c 2903 {
6dc54d91
PA
2904 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2905 threads_elements, xml, context);
dc146f7c
VP
2906 }
2907
2908 do_cleanups (back_to);
6dc54d91 2909 return 1;
dc146f7c
VP
2910 }
2911#endif
2912
6dc54d91
PA
2913 return 0;
2914}
2915
2916/* List remote threads using qfThreadInfo/qsThreadInfo. */
2917
2918static int
2919remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2920 struct threads_listing_context *context)
2921{
2922 struct remote_state *rs = get_remote_state ();
2923
b80fafe3 2924 if (rs->use_threadinfo_query)
9d1f7ab2 2925 {
6dc54d91
PA
2926 char *bufp;
2927
9d1f7ab2 2928 putpkt ("qfThreadInfo");
6d820c5c 2929 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2930 bufp = rs->buf;
9d1f7ab2 2931 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2932 {
9d1f7ab2
MS
2933 while (*bufp++ == 'm') /* reply contains one or more TID */
2934 {
2935 do
2936 {
6dc54d91
PA
2937 struct thread_item item;
2938
2939 item.ptid = read_ptid (bufp, &bufp);
2940 item.core = -1;
2941 item.extra = NULL;
2942
2943 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
2944 }
2945 while (*bufp++ == ','); /* comma-separated list */
2946 putpkt ("qsThreadInfo");
6d820c5c 2947 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 2948 bufp = rs->buf;
9d1f7ab2 2949 }
6dc54d91
PA
2950 return 1;
2951 }
2952 else
2953 {
2954 /* Packet not recognized. */
2955 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2956 }
2957 }
2958
6dc54d91
PA
2959 return 0;
2960}
2961
e8032dde 2962/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
2963 targets. */
2964
2965static void
e8032dde 2966remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
2967{
2968 struct remote_state *rs = get_remote_state ();
2969 struct threads_listing_context context;
2970 struct cleanup *old_chain;
ab970af1 2971 int got_list = 0;
e8032dde 2972
6dc54d91
PA
2973 context.items = NULL;
2974 old_chain = make_cleanup (clear_threads_listing_context, &context);
2975
2976 /* We have a few different mechanisms to fetch the thread list. Try
2977 them all, starting with the most preferred one first, falling
2978 back to older methods. */
2979 if (remote_get_threads_with_qxfer (ops, &context)
2980 || remote_get_threads_with_qthreadinfo (ops, &context)
2981 || remote_get_threads_with_ql (ops, &context))
2982 {
2983 int i;
2984 struct thread_item *item;
ab970af1
PA
2985 struct thread_info *tp, *tmp;
2986
2987 got_list = 1;
2988
7d1a114c
PA
2989 if (VEC_empty (thread_item_t, context.items)
2990 && remote_thread_always_alive (ops, inferior_ptid))
2991 {
2992 /* Some targets don't really support threads, but still
2993 reply an (empty) thread list in response to the thread
2994 listing packets, instead of replying "packet not
2995 supported". Exit early so we don't delete the main
2996 thread. */
2997 do_cleanups (old_chain);
2998 return;
2999 }
3000
ab970af1
PA
3001 /* CONTEXT now holds the current thread list on the remote
3002 target end. Delete GDB-side threads no longer found on the
3003 target. */
8a06aea7 3004 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3005 {
ab970af1
PA
3006 for (i = 0;
3007 VEC_iterate (thread_item_t, context.items, i, item);
3008 ++i)
3009 {
3010 if (ptid_equal (item->ptid, tp->ptid))
3011 break;
3012 }
3013
3014 if (i == VEC_length (thread_item_t, context.items))
3015 {
3016 /* Not found. */
3017 delete_thread (tp->ptid);
3018 }
cbb8991c
DB
3019 }
3020
3021 /* Remove any unreported fork child threads from CONTEXT so
3022 that we don't interfere with follow fork, which is where
3023 creation of such threads is handled. */
3024 remove_new_fork_children (&context);
74531fed 3025
ab970af1 3026 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3027 for (i = 0;
3028 VEC_iterate (thread_item_t, context.items, i, item);
3029 ++i)
3030 {
3031 if (!ptid_equal (item->ptid, null_ptid))
3032 {
3033 struct private_thread_info *info;
3034 /* In non-stop mode, we assume new found threads are
3035 running until proven otherwise with a stop reply. In
3036 all-stop, we can only get here if all threads are
3037 stopped. */
3038 int running = non_stop ? 1 : 0;
3039
3040 remote_notice_new_inferior (item->ptid, running);
3041
3042 info = demand_private_info (item->ptid);
3043 info->core = item->core;
3044 info->extra = item->extra;
3045 item->extra = NULL;
3046 }
3047 }
3048 }
3049
ab970af1
PA
3050 if (!got_list)
3051 {
3052 /* If no thread listing method is supported, then query whether
3053 each known thread is alive, one by one, with the T packet.
3054 If the target doesn't support threads at all, then this is a
3055 no-op. See remote_thread_alive. */
3056 prune_threads ();
3057 }
3058
6dc54d91 3059 do_cleanups (old_chain);
9d1f7ab2
MS
3060}
3061
802188a7 3062/*
9d1f7ab2
MS
3063 * Collect a descriptive string about the given thread.
3064 * The target may say anything it wants to about the thread
3065 * (typically info about its blocked / runnable state, name, etc.).
3066 * This string will appear in the info threads display.
802188a7 3067 *
9d1f7ab2
MS
3068 * Optional: targets are not required to implement this function.
3069 */
3070
3071static char *
c15906d8 3072remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3073{
d01949b6 3074 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3075 int result;
3076 int set;
3077 threadref id;
3078 struct gdb_ext_thread_info threadinfo;
23860348 3079 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3080 int n = 0; /* position in display_buf */
3081
5d93a237 3082 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3083 internal_error (__FILE__, __LINE__,
e2e0b3e5 3084 _("remote_threads_extra_info"));
9d1f7ab2 3085
60e569b9 3086 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3087 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3088 /* This is the main thread which was added by GDB. The remote
3089 server doesn't know about it. */
3090 return NULL;
3091
4082afcc 3092 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3093 {
3094 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3095
fe978cb0
PA
3096 if (info && info->priv)
3097 return info->priv->extra;
dc146f7c
VP
3098 else
3099 return NULL;
3100 }
3101
b80fafe3 3102 if (rs->use_threadextra_query)
9d1f7ab2 3103 {
82f73884
PA
3104 char *b = rs->buf;
3105 char *endb = rs->buf + get_remote_packet_size ();
3106
3107 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3108 b += strlen (b);
3109 write_ptid (b, endb, tp->ptid);
3110
2e9f7625 3111 putpkt (rs->buf);
6d820c5c 3112 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3113 if (rs->buf[0] != 0)
9d1f7ab2 3114 {
2e9f7625
DJ
3115 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3116 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3117 display_buf [result] = '\0';
9d1f7ab2
MS
3118 return display_buf;
3119 }
0f71a2f6 3120 }
9d1f7ab2
MS
3121
3122 /* If the above query fails, fall back to the old method. */
b80fafe3 3123 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3124 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3125 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3126 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3127 if (remote_get_threadinfo (&id, set, &threadinfo))
3128 if (threadinfo.active)
0f71a2f6 3129 {
9d1f7ab2 3130 if (*threadinfo.shortname)
2bc416ba 3131 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3132 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3133 if (*threadinfo.display)
2bc416ba 3134 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3135 " State: %s,", threadinfo.display);
9d1f7ab2 3136 if (*threadinfo.more_display)
2bc416ba 3137 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3138 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3139
3140 if (n > 0)
c5aa993b 3141 {
23860348 3142 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3143 if (',' == display_buf[n-1])
3144 display_buf[n-1] = ' ';
3145 return display_buf;
c5aa993b 3146 }
0f71a2f6 3147 }
9d1f7ab2 3148 return NULL;
0f71a2f6 3149}
c906108c 3150\f
c5aa993b 3151
0fb4aa4b 3152static int
61fc905d 3153remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3154 struct static_tracepoint_marker *marker)
3155{
3156 struct remote_state *rs = get_remote_state ();
3157 char *p = rs->buf;
3158
bba74b36 3159 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3160 p += strlen (p);
3161 p += hexnumstr (p, addr);
3162 putpkt (rs->buf);
3163 getpkt (&rs->buf, &rs->buf_size, 0);
3164 p = rs->buf;
3165
3166 if (*p == 'E')
3167 error (_("Remote failure reply: %s"), p);
3168
3169 if (*p++ == 'm')
3170 {
3171 parse_static_tracepoint_marker_definition (p, &p, marker);
3172 return 1;
3173 }
3174
3175 return 0;
3176}
3177
0fb4aa4b 3178static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3179remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3180 const char *strid)
0fb4aa4b
PA
3181{
3182 struct remote_state *rs = get_remote_state ();
3183 VEC(static_tracepoint_marker_p) *markers = NULL;
3184 struct static_tracepoint_marker *marker = NULL;
3185 struct cleanup *old_chain;
3186 char *p;
3187
3188 /* Ask for a first packet of static tracepoint marker
3189 definition. */
3190 putpkt ("qTfSTM");
3191 getpkt (&rs->buf, &rs->buf_size, 0);
3192 p = rs->buf;
3193 if (*p == 'E')
3194 error (_("Remote failure reply: %s"), p);
3195
3196 old_chain = make_cleanup (free_current_marker, &marker);
3197
3198 while (*p++ == 'm')
3199 {
3200 if (marker == NULL)
3201 marker = XCNEW (struct static_tracepoint_marker);
3202
3203 do
3204 {
3205 parse_static_tracepoint_marker_definition (p, &p, marker);
3206
3207 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3208 {
3209 VEC_safe_push (static_tracepoint_marker_p,
3210 markers, marker);
3211 marker = NULL;
3212 }
3213 else
3214 {
3215 release_static_tracepoint_marker (marker);
3216 memset (marker, 0, sizeof (*marker));
3217 }
3218 }
3219 while (*p++ == ','); /* comma-separated list */
3220 /* Ask for another packet of static tracepoint definition. */
3221 putpkt ("qTsSTM");
3222 getpkt (&rs->buf, &rs->buf_size, 0);
3223 p = rs->buf;
3224 }
3225
3226 do_cleanups (old_chain);
3227 return markers;
3228}
3229
3230\f
10760264
JB
3231/* Implement the to_get_ada_task_ptid function for the remote targets. */
3232
3233static ptid_t
1e6b91a4 3234remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3235{
ba348170 3236 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3237}
3238\f
3239
24b06219 3240/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3241
3242static void
fba45db2 3243extended_remote_restart (void)
c906108c 3244{
d01949b6 3245 struct remote_state *rs = get_remote_state ();
c906108c
SS
3246
3247 /* Send the restart command; for reasons I don't understand the
3248 remote side really expects a number after the "R". */
ea9c271d 3249 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3250 putpkt (rs->buf);
c906108c 3251
ad9a8f3f 3252 remote_fileio_reset ();
c906108c
SS
3253}
3254\f
3255/* Clean up connection to a remote debugger. */
3256
c906108c 3257static void
de90e03d 3258remote_close (struct target_ops *self)
c906108c 3259{
5d93a237
TT
3260 struct remote_state *rs = get_remote_state ();
3261
3262 if (rs->remote_desc == NULL)
d3fd5342
PA
3263 return; /* already closed */
3264
3265 /* Make sure we leave stdin registered in the event loop, and we
3266 don't leave the async SIGINT signal handler installed. */
e3594fd1 3267 remote_terminal_ours (self);
ce5ce7ed 3268
5d93a237
TT
3269 serial_close (rs->remote_desc);
3270 rs->remote_desc = NULL;
ce5ce7ed
PA
3271
3272 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3273 of all the inferiors and their threads we were controlling.
3274 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3275 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3276 inferior_ptid = null_ptid;
f67fd822 3277 discard_all_inferiors ();
ce5ce7ed 3278
f48ff2a7
YQ
3279 /* We are closing the remote target, so we should discard
3280 everything of this target. */
bcc75809 3281 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3282
3283 if (remote_async_inferior_event_token)
3284 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3285
5965e028 3286 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3287
3288 trace_reset_local_state ();
c906108c
SS
3289}
3290
23860348 3291/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3292
3293static void
fba45db2 3294get_offsets (void)
c906108c 3295{
d01949b6 3296 struct remote_state *rs = get_remote_state ();
2e9f7625 3297 char *buf;
085dd6e6 3298 char *ptr;
31d99776
DJ
3299 int lose, num_segments = 0, do_sections, do_segments;
3300 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3301 struct section_offsets *offs;
31d99776
DJ
3302 struct symfile_segment_data *data;
3303
3304 if (symfile_objfile == NULL)
3305 return;
c906108c
SS
3306
3307 putpkt ("qOffsets");
6d820c5c 3308 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3309 buf = rs->buf;
c906108c
SS
3310
3311 if (buf[0] == '\000')
3312 return; /* Return silently. Stub doesn't support
23860348 3313 this command. */
c906108c
SS
3314 if (buf[0] == 'E')
3315 {
8a3fe4f8 3316 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3317 return;
3318 }
3319
3320 /* Pick up each field in turn. This used to be done with scanf, but
3321 scanf will make trouble if CORE_ADDR size doesn't match
3322 conversion directives correctly. The following code will work
3323 with any size of CORE_ADDR. */
3324 text_addr = data_addr = bss_addr = 0;
3325 ptr = buf;
3326 lose = 0;
3327
61012eef 3328 if (startswith (ptr, "Text="))
c906108c
SS
3329 {
3330 ptr += 5;
3331 /* Don't use strtol, could lose on big values. */
3332 while (*ptr && *ptr != ';')
3333 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3334
61012eef 3335 if (startswith (ptr, ";Data="))
31d99776
DJ
3336 {
3337 ptr += 6;
3338 while (*ptr && *ptr != ';')
3339 data_addr = (data_addr << 4) + fromhex (*ptr++);
3340 }
3341 else
3342 lose = 1;
3343
61012eef 3344 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3345 {
3346 ptr += 5;
3347 while (*ptr && *ptr != ';')
3348 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3349
31d99776
DJ
3350 if (bss_addr != data_addr)
3351 warning (_("Target reported unsupported offsets: %s"), buf);
3352 }
3353 else
3354 lose = 1;
3355 }
61012eef 3356 else if (startswith (ptr, "TextSeg="))
c906108c 3357 {
31d99776
DJ
3358 ptr += 8;
3359 /* Don't use strtol, could lose on big values. */
c906108c 3360 while (*ptr && *ptr != ';')
31d99776
DJ
3361 text_addr = (text_addr << 4) + fromhex (*ptr++);
3362 num_segments = 1;
3363
61012eef 3364 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3365 {
3366 ptr += 9;
3367 while (*ptr && *ptr != ';')
3368 data_addr = (data_addr << 4) + fromhex (*ptr++);
3369 num_segments++;
3370 }
c906108c
SS
3371 }
3372 else
3373 lose = 1;
3374
3375 if (lose)
8a3fe4f8 3376 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3377 else if (*ptr != '\0')
3378 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3379
802188a7 3380 offs = ((struct section_offsets *)
a39a16c4 3381 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3382 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3383 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3384
31d99776
DJ
3385 data = get_symfile_segment_data (symfile_objfile->obfd);
3386 do_segments = (data != NULL);
3387 do_sections = num_segments == 0;
c906108c 3388
28c32713 3389 if (num_segments > 0)
31d99776 3390 {
31d99776
DJ
3391 segments[0] = text_addr;
3392 segments[1] = data_addr;
3393 }
28c32713
JB
3394 /* If we have two segments, we can still try to relocate everything
3395 by assuming that the .text and .data offsets apply to the whole
3396 text and data segments. Convert the offsets given in the packet
3397 to base addresses for symfile_map_offsets_to_segments. */
3398 else if (data && data->num_segments == 2)
3399 {
3400 segments[0] = data->segment_bases[0] + text_addr;
3401 segments[1] = data->segment_bases[1] + data_addr;
3402 num_segments = 2;
3403 }
8d385431
DJ
3404 /* If the object file has only one segment, assume that it is text
3405 rather than data; main programs with no writable data are rare,
3406 but programs with no code are useless. Of course the code might
3407 have ended up in the data segment... to detect that we would need
3408 the permissions here. */
3409 else if (data && data->num_segments == 1)
3410 {
3411 segments[0] = data->segment_bases[0] + text_addr;
3412 num_segments = 1;
3413 }
28c32713
JB
3414 /* There's no way to relocate by segment. */
3415 else
3416 do_segments = 0;
31d99776
DJ
3417
3418 if (do_segments)
3419 {
3420 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3421 offs, num_segments, segments);
3422
3423 if (ret == 0 && !do_sections)
3e43a32a
MS
3424 error (_("Can not handle qOffsets TextSeg "
3425 "response with this symbol file"));
31d99776
DJ
3426
3427 if (ret > 0)
3428 do_sections = 0;
3429 }
c906108c 3430
9ef895d6
DJ
3431 if (data)
3432 free_symfile_segment_data (data);
31d99776
DJ
3433
3434 if (do_sections)
3435 {
3436 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3437
3e43a32a
MS
3438 /* This is a temporary kludge to force data and bss to use the
3439 same offsets because that's what nlmconv does now. The real
3440 solution requires changes to the stub and remote.c that I
3441 don't have time to do right now. */
31d99776
DJ
3442
3443 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3444 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3445 }
c906108c
SS
3446
3447 objfile_relocate (symfile_objfile, offs);
3448}
3449
9a7071a8
JB
3450/* Send interrupt_sequence to remote target. */
3451static void
eeae04df 3452send_interrupt_sequence (void)
9a7071a8 3453{
5d93a237
TT
3454 struct remote_state *rs = get_remote_state ();
3455
9a7071a8 3456 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3457 remote_serial_write ("\x03", 1);
9a7071a8 3458 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3459 serial_send_break (rs->remote_desc);
9a7071a8
JB
3460 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3461 {
5d93a237 3462 serial_send_break (rs->remote_desc);
c33e31fd 3463 remote_serial_write ("g", 1);
9a7071a8
JB
3464 }
3465 else
3466 internal_error (__FILE__, __LINE__,
3467 _("Invalid value for interrupt_sequence_mode: %s."),
3468 interrupt_sequence_mode);
3469}
3470
3405876a
PA
3471
3472/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3473 and extract the PTID. Returns NULL_PTID if not found. */
3474
3475static ptid_t
3476stop_reply_extract_thread (char *stop_reply)
3477{
3478 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3479 {
3480 char *p;
3481
3482 /* Txx r:val ; r:val (...) */
3483 p = &stop_reply[3];
3484
3485 /* Look for "register" named "thread". */
3486 while (*p != '\0')
3487 {
3488 char *p1;
3489
3490 p1 = strchr (p, ':');
3491 if (p1 == NULL)
3492 return null_ptid;
3493
3494 if (strncmp (p, "thread", p1 - p) == 0)
3495 return read_ptid (++p1, &p);
3496
3497 p1 = strchr (p, ';');
3498 if (p1 == NULL)
3499 return null_ptid;
3500 p1++;
3501
3502 p = p1;
3503 }
3504 }
3505
3506 return null_ptid;
3507}
3508
b7ea362b
PA
3509/* Determine the remote side's current thread. If we have a stop
3510 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3511 "thread" register we can extract the current thread from. If not,
3512 ask the remote which is the current thread with qC. The former
3513 method avoids a roundtrip. */
3514
3515static ptid_t
3516get_current_thread (char *wait_status)
3517{
6a49a997 3518 ptid_t ptid = null_ptid;
b7ea362b
PA
3519
3520 /* Note we don't use remote_parse_stop_reply as that makes use of
3521 the target architecture, which we haven't yet fully determined at
3522 this point. */
3523 if (wait_status != NULL)
3524 ptid = stop_reply_extract_thread (wait_status);
3525 if (ptid_equal (ptid, null_ptid))
3526 ptid = remote_current_thread (inferior_ptid);
3527
3528 return ptid;
3529}
3530
49c62f2e
PA
3531/* Query the remote target for which is the current thread/process,
3532 add it to our tables, and update INFERIOR_PTID. The caller is
3533 responsible for setting the state such that the remote end is ready
3405876a
PA
3534 to return the current thread.
3535
3536 This function is called after handling the '?' or 'vRun' packets,
3537 whose response is a stop reply from which we can also try
3538 extracting the thread. If the target doesn't support the explicit
3539 qC query, we infer the current thread from that stop reply, passed
3540 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3541
3542static void
3405876a 3543add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3544{
3545 struct remote_state *rs = get_remote_state ();
3546 int fake_pid_p = 0;
6a49a997 3547 ptid_t ptid;
49c62f2e
PA
3548
3549 inferior_ptid = null_ptid;
3550
b7ea362b
PA
3551 /* Now, if we have thread information, update inferior_ptid. */
3552 ptid = get_current_thread (wait_status);
3405876a 3553
49c62f2e
PA
3554 if (!ptid_equal (ptid, null_ptid))
3555 {
3556 if (!remote_multi_process_p (rs))
3557 fake_pid_p = 1;
3558
3559 inferior_ptid = ptid;
3560 }
3561 else
3562 {
3563 /* Without this, some commands which require an active target
3564 (such as kill) won't work. This variable serves (at least)
3565 double duty as both the pid of the target process (if it has
3566 such), and as a flag indicating that a target is active. */
3567 inferior_ptid = magic_null_ptid;
3568 fake_pid_p = 1;
3569 }
3570
1b6e6f5c 3571 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3572
3573 /* Add the main thread. */
3574 add_thread_silent (inferior_ptid);
3575}
3576
221e1a37
PA
3577/* Process all initial stop replies the remote side sent in response
3578 to the ? packet. These indicate threads that were already stopped
3579 on initial connection. We mark these threads as stopped and print
3580 their current frame before giving the user the prompt. */
3581
3582static void
3583process_initial_stop_replies (void)
3584{
3585 int pending_stop_replies = stop_reply_queue_length ();
3586
3587 /* Consume the initial pending events. */
3588 while (pending_stop_replies-- > 0)
3589 {
3590 ptid_t waiton_ptid = minus_one_ptid;
3591 ptid_t event_ptid;
3592 struct target_waitstatus ws;
3593 int ignore_event = 0;
3594
3595 memset (&ws, 0, sizeof (ws));
3596 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3597 if (remote_debug)
3598 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3599
3600 switch (ws.kind)
3601 {
3602 case TARGET_WAITKIND_IGNORE:
3603 case TARGET_WAITKIND_NO_RESUMED:
3604 case TARGET_WAITKIND_SIGNALLED:
3605 case TARGET_WAITKIND_EXITED:
3606 /* We shouldn't see these, but if we do, just ignore. */
3607 if (remote_debug)
3608 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3609 ignore_event = 1;
3610 break;
3611
3612 case TARGET_WAITKIND_EXECD:
3613 xfree (ws.value.execd_pathname);
3614 break;
3615 default:
3616 break;
3617 }
3618
3619 if (ignore_event)
3620 continue;
3621
3622 switch_to_thread (event_ptid);
3623 set_executing (event_ptid, 0);
3624 set_running (event_ptid, 0);
3625
3626 stop_pc = get_frame_pc (get_current_frame ());
3627 set_current_sal_from_frame (get_current_frame ());
3628
3629 if (ws.kind == TARGET_WAITKIND_STOPPED)
3630 {
3631 enum gdb_signal sig = ws.value.sig;
3632
3633 /* Stubs traditionally report SIGTRAP as initial signal,
3634 instead of signal 0. Suppress it. */
3635 if (sig == GDB_SIGNAL_TRAP)
3636 sig = GDB_SIGNAL_0;
3637 inferior_thread ()->suspend.stop_signal = sig;
3638
3639 if (signal_print_state (sig))
3640 observer_notify_signal_received (sig);
3641 }
3642
3643 print_stop_event (&ws);
3644 observer_notify_normal_stop (NULL, 1);
3645 }
3646}
3647
9cbc821d 3648static void
04bd08de 3649remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3650{
c8d104ad
PA
3651 struct remote_state *rs = get_remote_state ();
3652 struct packet_config *noack_config;
2d717e4f 3653 char *wait_status = NULL;
8621d6a9 3654
23860348 3655 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3656 QUIT;
c906108c 3657
9a7071a8
JB
3658 if (interrupt_on_connect)
3659 send_interrupt_sequence ();
3660
57e12211 3661 /* Ack any packet which the remote side has already sent. */
5d93a237 3662 serial_write (rs->remote_desc, "+", 1);
57e12211 3663
1e51243a
PA
3664 /* Signal other parts that we're going through the initial setup,
3665 and so things may not be stable yet. */
3666 rs->starting_up = 1;
3667
c8d104ad
PA
3668 /* The first packet we send to the target is the optional "supported
3669 packets" request. If the target can answer this, it will tell us
3670 which later probes to skip. */
3671 remote_query_supported ();
3672
d914c394 3673 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3674 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3675 remote_set_permissions (target);
d914c394 3676
c8d104ad
PA
3677 /* Next, we possibly activate noack mode.
3678
3679 If the QStartNoAckMode packet configuration is set to AUTO,
3680 enable noack mode if the stub reported a wish for it with
3681 qSupported.
3682
3683 If set to TRUE, then enable noack mode even if the stub didn't
3684 report it in qSupported. If the stub doesn't reply OK, the
3685 session ends with an error.
3686
3687 If FALSE, then don't activate noack mode, regardless of what the
3688 stub claimed should be the default with qSupported. */
3689
3690 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3691 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3692 {
3693 putpkt ("QStartNoAckMode");
3694 getpkt (&rs->buf, &rs->buf_size, 0);
3695 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3696 rs->noack_mode = 1;
3697 }
3698
04bd08de 3699 if (extended_p)
5fe04517
PA
3700 {
3701 /* Tell the remote that we are using the extended protocol. */
3702 putpkt ("!");
3703 getpkt (&rs->buf, &rs->buf_size, 0);
3704 }
3705
9b224c5e
PA
3706 /* Let the target know which signals it is allowed to pass down to
3707 the program. */
3708 update_signals_program_target ();
3709
d962ef82
DJ
3710 /* Next, if the target can specify a description, read it. We do
3711 this before anything involving memory or registers. */
3712 target_find_description ();
3713
6c95b8df
PA
3714 /* Next, now that we know something about the target, update the
3715 address spaces in the program spaces. */
3716 update_address_spaces ();
3717
50c71eaf
PA
3718 /* On OSs where the list of libraries is global to all
3719 processes, we fetch them early. */
f5656ead 3720 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3721 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3722
74531fed
PA
3723 if (non_stop)
3724 {
4082afcc 3725 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3726 error (_("Non-stop mode requested, but remote "
3727 "does not support non-stop"));
74531fed
PA
3728
3729 putpkt ("QNonStop:1");
3730 getpkt (&rs->buf, &rs->buf_size, 0);
3731
3732 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3733 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3734
3735 /* Find about threads and processes the stub is already
3736 controlling. We default to adding them in the running state.
3737 The '?' query below will then tell us about which threads are
3738 stopped. */
e8032dde 3739 remote_update_thread_list (target);
74531fed 3740 }
4082afcc 3741 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3742 {
3743 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3744 Request it explicitly. */
74531fed
PA
3745 putpkt ("QNonStop:0");
3746 getpkt (&rs->buf, &rs->buf_size, 0);
3747
3748 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3749 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3750 }
3751
a0743c90
YQ
3752 /* Upload TSVs regardless of whether the target is running or not. The
3753 remote stub, such as GDBserver, may have some predefined or builtin
3754 TSVs, even if the target is not running. */
8bd200f1 3755 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3756 {
3757 struct uploaded_tsv *uploaded_tsvs = NULL;
3758
181e3713 3759 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3760 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3761 }
3762
2d717e4f
DJ
3763 /* Check whether the target is running now. */
3764 putpkt ("?");
3765 getpkt (&rs->buf, &rs->buf_size, 0);
3766
74531fed 3767 if (!non_stop)
2d717e4f 3768 {
e714e1bf
UW
3769 ptid_t ptid;
3770 int fake_pid_p = 0;
3771 struct inferior *inf;
3772
74531fed 3773 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3774 {
04bd08de 3775 if (!extended_p)
74531fed 3776 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3777
3778 /* We're connected, but not running. Drop out before we
3779 call start_remote. */
e278ad5b 3780 rs->starting_up = 0;
c35b1492 3781 return;
2d717e4f
DJ
3782 }
3783 else
74531fed 3784 {
74531fed
PA
3785 /* Save the reply for later. */
3786 wait_status = alloca (strlen (rs->buf) + 1);
3787 strcpy (wait_status, rs->buf);
3788 }
3789
b7ea362b 3790 /* Fetch thread list. */
e8032dde 3791 target_update_thread_list ();
b7ea362b 3792
74531fed
PA
3793 /* Let the stub know that we want it to return the thread. */
3794 set_continue_thread (minus_one_ptid);
3795
b7ea362b
PA
3796 if (thread_count () == 0)
3797 {
3798 /* Target has no concept of threads at all. GDB treats
3799 non-threaded target as single-threaded; add a main
3800 thread. */
3801 add_current_inferior_and_thread (wait_status);
3802 }
3803 else
3804 {
3805 /* We have thread information; select the thread the target
3806 says should be current. If we're reconnecting to a
3807 multi-threaded program, this will ideally be the thread
3808 that last reported an event before GDB disconnected. */
3809 inferior_ptid = get_current_thread (wait_status);
3810 if (ptid_equal (inferior_ptid, null_ptid))
3811 {
3812 /* Odd... The target was able to list threads, but not
3813 tell us which thread was current (no "thread"
3814 register in T stop reply?). Just pick the first
3815 thread in the thread list then. */
c9f35b34
KB
3816
3817 if (remote_debug)
3818 fprintf_unfiltered (gdb_stdlog,
3819 "warning: couldn't determine remote "
3820 "current thread; picking first in list.\n");
3821
b7ea362b
PA
3822 inferior_ptid = thread_list->ptid;
3823 }
3824 }
74531fed 3825
6e586cc5
YQ
3826 /* init_wait_for_inferior should be called before get_offsets in order
3827 to manage `inserted' flag in bp loc in a correct state.
3828 breakpoint_init_inferior, called from init_wait_for_inferior, set
3829 `inserted' flag to 0, while before breakpoint_re_set, called from
3830 start_remote, set `inserted' flag to 1. In the initialization of
3831 inferior, breakpoint_init_inferior should be called first, and then
3832 breakpoint_re_set can be called. If this order is broken, state of
3833 `inserted' flag is wrong, and cause some problems on breakpoint
3834 manipulation. */
3835 init_wait_for_inferior ();
3836
74531fed
PA
3837 get_offsets (); /* Get text, data & bss offsets. */
3838
d962ef82
DJ
3839 /* If we could not find a description using qXfer, and we know
3840 how to do it some other way, try again. This is not
3841 supported for non-stop; it could be, but it is tricky if
3842 there are no stopped threads when we connect. */
04bd08de 3843 if (remote_read_description_p (target)
f5656ead 3844 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3845 {
3846 target_clear_description ();
3847 target_find_description ();
3848 }
3849
74531fed
PA
3850 /* Use the previously fetched status. */
3851 gdb_assert (wait_status != NULL);
3852 strcpy (rs->buf, wait_status);
3853 rs->cached_wait_status = 1;
3854
3855 immediate_quit--;
04bd08de 3856 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3857 }
3858 else
3859 {
221e1a37
PA
3860 ptid_t current_ptid;
3861
68c97600
PA
3862 /* Clear WFI global state. Do this before finding about new
3863 threads and inferiors, and setting the current inferior.
3864 Otherwise we would clear the proceed status of the current
3865 inferior when we want its stop_soon state to be preserved
3866 (see notice_new_inferior). */
3867 init_wait_for_inferior ();
3868
74531fed
PA
3869 /* In non-stop, we will either get an "OK", meaning that there
3870 are no stopped threads at this time; or, a regular stop
3871 reply. In the latter case, there may be more than one thread
3872 stopped --- we pull them all out using the vStopped
3873 mechanism. */
3874 if (strcmp (rs->buf, "OK") != 0)
3875 {
722247f1 3876 struct notif_client *notif = &notif_client_stop;
2d717e4f 3877
722247f1
YQ
3878 /* remote_notif_get_pending_replies acks this one, and gets
3879 the rest out. */
f48ff2a7 3880 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3881 = remote_notif_parse (notif, rs->buf);
3882 remote_notif_get_pending_events (notif);
74531fed 3883 }
2d717e4f 3884
74531fed
PA
3885 if (thread_count () == 0)
3886 {
04bd08de 3887 if (!extended_p)
74531fed 3888 error (_("The target is not running (try extended-remote?)"));
82f73884 3889
c35b1492
PA
3890 /* We're connected, but not running. Drop out before we
3891 call start_remote. */
e278ad5b 3892 rs->starting_up = 0;
c35b1492
PA
3893 return;
3894 }
74531fed
PA
3895
3896 /* Let the stub know that we want it to return the thread. */
c0a2216e 3897
74531fed
PA
3898 /* Force the stub to choose a thread. */
3899 set_general_thread (null_ptid);
c906108c 3900
74531fed 3901 /* Query it. */
221e1a37 3902 current_ptid = remote_current_thread (minus_one_ptid);
74531fed
PA
3903 if (ptid_equal (inferior_ptid, minus_one_ptid))
3904 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3905
221e1a37 3906 inferior_ptid = current_ptid;
74531fed
PA
3907 get_offsets (); /* Get text, data & bss offsets. */
3908
3909 /* In non-stop mode, any cached wait status will be stored in
3910 the stop reply queue. */
3911 gdb_assert (wait_status == NULL);
f0223081 3912
2455069d 3913 /* Report all signals during attach/startup. */
94bedb42 3914 remote_pass_signals (target, 0, NULL);
221e1a37
PA
3915
3916 /* If there are already stopped threads, mark them stopped and
3917 report their stops before giving the prompt to the user. */
3918 process_initial_stop_replies ();
3919
3920 switch_to_thread (current_ptid);
3921
3922 if (target_can_async_p ())
3923 target_async (1);
74531fed 3924 }
c8d104ad 3925
c8d104ad
PA
3926 /* If we connected to a live target, do some additional setup. */
3927 if (target_has_execution)
3928 {
f4ccffad 3929 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3930 remote_check_symbols ();
c8d104ad 3931 }
50c71eaf 3932
d5551862
SS
3933 /* Possibly the target has been engaged in a trace run started
3934 previously; find out where things are at. */
8bd200f1 3935 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3936 {
00bf0b85 3937 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3938
00bf0b85
SS
3939 if (current_trace_status ()->running)
3940 printf_filtered (_("Trace is already running on the target.\n"));
3941
ab6617cc 3942 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3943
3944 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3945 }
3946
1e51243a
PA
3947 /* The thread and inferior lists are now synchronized with the
3948 target, our symbols have been relocated, and we're merged the
3949 target's tracepoints with ours. We're done with basic start
3950 up. */
3951 rs->starting_up = 0;
3952
a25a5a45
PA
3953 /* Maybe breakpoints are global and need to be inserted now. */
3954 if (breakpoints_should_be_inserted_now ())
50c71eaf 3955 insert_breakpoints ();
c906108c
SS
3956}
3957
3958/* Open a connection to a remote debugger.
3959 NAME is the filename used for communication. */
3960
3961static void
014f9477 3962remote_open (const char *name, int from_tty)
c906108c 3963{
75c99385 3964 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3965}
3966
c906108c
SS
3967/* Open a connection to a remote debugger using the extended
3968 remote gdb protocol. NAME is the filename used for communication. */
3969
3970static void
014f9477 3971extended_remote_open (const char *name, int from_tty)
c906108c 3972{
75c99385 3973 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3974}
3975
ca4f7f8b
PA
3976/* Reset all packets back to "unknown support". Called when opening a
3977 new connection to a remote target. */
c906108c 3978
d471ea57 3979static void
ca4f7f8b 3980reset_all_packet_configs_support (void)
d471ea57
AC
3981{
3982 int i;
a744cf53 3983
444abaca 3984 for (i = 0; i < PACKET_MAX; i++)
4082afcc 3985 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
3986}
3987
ca4f7f8b
PA
3988/* Initialize all packet configs. */
3989
3990static void
3991init_all_packet_configs (void)
3992{
3993 int i;
3994
3995 for (i = 0; i < PACKET_MAX; i++)
3996 {
3997 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3998 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3999 }
4000}
4001
23860348 4002/* Symbol look-up. */
dc8acb97
MS
4003
4004static void
36d25514 4005remote_check_symbols (void)
dc8acb97 4006{
d01949b6 4007 struct remote_state *rs = get_remote_state ();
dc8acb97 4008 char *msg, *reply, *tmp;
3b7344d5 4009 struct bound_minimal_symbol sym;
dc8acb97
MS
4010 int end;
4011
63154eca
PA
4012 /* The remote side has no concept of inferiors that aren't running
4013 yet, it only knows about running processes. If we're connected
4014 but our current inferior is not running, we should not invite the
4015 remote target to request symbol lookups related to its
4016 (unrelated) current process. */
4017 if (!target_has_execution)
4018 return;
4019
4082afcc 4020 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4021 return;
4022
63154eca
PA
4023 /* Make sure the remote is pointing at the right process. Note
4024 there's no way to select "no process". */
3c9c4b83
PA
4025 set_general_process ();
4026
6d820c5c
DJ
4027 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4028 because we need both at the same time. */
ea9c271d 4029 msg = alloca (get_remote_packet_size ());
6d820c5c 4030
23860348 4031 /* Invite target to request symbol lookups. */
dc8acb97
MS
4032
4033 putpkt ("qSymbol::");
6d820c5c
DJ
4034 getpkt (&rs->buf, &rs->buf_size, 0);
4035 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 4036 reply = rs->buf;
dc8acb97 4037
61012eef 4038 while (startswith (reply, "qSymbol:"))
dc8acb97 4039 {
77e371c0
TT
4040 struct bound_minimal_symbol sym;
4041
dc8acb97 4042 tmp = &reply[8];
cfd77fa1 4043 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4044 msg[end] = '\0';
4045 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4046 if (sym.minsym == NULL)
ea9c271d 4047 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4048 else
2bbe3cc1 4049 {
f5656ead 4050 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4051 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4052
4053 /* If this is a function address, return the start of code
4054 instead of any data function descriptor. */
f5656ead 4055 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4056 sym_addr,
4057 &current_target);
4058
4059 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4060 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4061 }
4062
dc8acb97 4063 putpkt (msg);
6d820c5c 4064 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4065 reply = rs->buf;
dc8acb97
MS
4066 }
4067}
4068
9db8d71f 4069static struct serial *
baa336ce 4070remote_serial_open (const char *name)
9db8d71f
DJ
4071{
4072 static int udp_warning = 0;
4073
4074 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4075 of in ser-tcp.c, because it is the remote protocol assuming that the
4076 serial connection is reliable and not the serial connection promising
4077 to be. */
61012eef 4078 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4079 {
3e43a32a
MS
4080 warning (_("The remote protocol may be unreliable over UDP.\n"
4081 "Some events may be lost, rendering further debugging "
4082 "impossible."));
9db8d71f
DJ
4083 udp_warning = 1;
4084 }
4085
4086 return serial_open (name);
4087}
4088
d914c394
SS
4089/* Inform the target of our permission settings. The permission flags
4090 work without this, but if the target knows the settings, it can do
4091 a couple things. First, it can add its own check, to catch cases
4092 that somehow manage to get by the permissions checks in target
4093 methods. Second, if the target is wired to disallow particular
4094 settings (for instance, a system in the field that is not set up to
4095 be able to stop at a breakpoint), it can object to any unavailable
4096 permissions. */
4097
4098void
c378d69d 4099remote_set_permissions (struct target_ops *self)
d914c394
SS
4100{
4101 struct remote_state *rs = get_remote_state ();
4102
bba74b36
YQ
4103 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4104 "WriteReg:%x;WriteMem:%x;"
4105 "InsertBreak:%x;InsertTrace:%x;"
4106 "InsertFastTrace:%x;Stop:%x",
4107 may_write_registers, may_write_memory,
4108 may_insert_breakpoints, may_insert_tracepoints,
4109 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4110 putpkt (rs->buf);
4111 getpkt (&rs->buf, &rs->buf_size, 0);
4112
4113 /* If the target didn't like the packet, warn the user. Do not try
4114 to undo the user's settings, that would just be maddening. */
4115 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4116 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4117}
4118
be2a5f71
DJ
4119/* This type describes each known response to the qSupported
4120 packet. */
4121struct protocol_feature
4122{
4123 /* The name of this protocol feature. */
4124 const char *name;
4125
4126 /* The default for this protocol feature. */
4127 enum packet_support default_support;
4128
4129 /* The function to call when this feature is reported, or after
4130 qSupported processing if the feature is not supported.
4131 The first argument points to this structure. The second
4132 argument indicates whether the packet requested support be
4133 enabled, disabled, or probed (or the default, if this function
4134 is being called at the end of processing and this feature was
4135 not reported). The third argument may be NULL; if not NULL, it
4136 is a NUL-terminated string taken from the packet following
4137 this feature's name and an equals sign. */
4138 void (*func) (const struct protocol_feature *, enum packet_support,
4139 const char *);
4140
4141 /* The corresponding packet for this feature. Only used if
4142 FUNC is remote_supported_packet. */
4143 int packet;
4144};
4145
be2a5f71
DJ
4146static void
4147remote_supported_packet (const struct protocol_feature *feature,
4148 enum packet_support support,
4149 const char *argument)
4150{
4151 if (argument)
4152 {
4153 warning (_("Remote qSupported response supplied an unexpected value for"
4154 " \"%s\"."), feature->name);
4155 return;
4156 }
4157
4082afcc 4158 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4159}
be2a5f71
DJ
4160
4161static void
4162remote_packet_size (const struct protocol_feature *feature,
4163 enum packet_support support, const char *value)
4164{
4165 struct remote_state *rs = get_remote_state ();
4166
4167 int packet_size;
4168 char *value_end;
4169
4170 if (support != PACKET_ENABLE)
4171 return;
4172
4173 if (value == NULL || *value == '\0')
4174 {
4175 warning (_("Remote target reported \"%s\" without a size."),
4176 feature->name);
4177 return;
4178 }
4179
4180 errno = 0;
4181 packet_size = strtol (value, &value_end, 16);
4182 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4183 {
4184 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4185 feature->name, value);
4186 return;
4187 }
4188
4189 if (packet_size > MAX_REMOTE_PACKET_SIZE)
4190 {
4191 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
4192 packet_size, MAX_REMOTE_PACKET_SIZE);
4193 packet_size = MAX_REMOTE_PACKET_SIZE;
4194 }
4195
4196 /* Record the new maximum packet size. */
4197 rs->explicit_packet_size = packet_size;
4198}
4199
dc473cfb 4200static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4201 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4202 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4203 PACKET_qXfer_auxv },
c78fa86a
GB
4204 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4205 PACKET_qXfer_exec_file },
23181151
DJ
4206 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4207 PACKET_qXfer_features },
cfa9d6d9
DJ
4208 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4209 PACKET_qXfer_libraries },
2268b414
JK
4210 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4211 PACKET_qXfer_libraries_svr4 },
ced63ec0 4212 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4213 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4214 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4215 PACKET_qXfer_memory_map },
4de6483e
UW
4216 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4217 PACKET_qXfer_spu_read },
4218 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4219 PACKET_qXfer_spu_write },
07e059b5
VP
4220 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4221 PACKET_qXfer_osdata },
dc146f7c
VP
4222 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4223 PACKET_qXfer_threads },
b3b9301e
PA
4224 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4225 PACKET_qXfer_traceframe_info },
89be2091
DJ
4226 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4227 PACKET_QPassSignals },
9b224c5e
PA
4228 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4229 PACKET_QProgramSignals },
a6f3e723
SL
4230 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4231 PACKET_QStartNoAckMode },
4082afcc
PA
4232 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4233 PACKET_multiprocess_feature },
4234 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4235 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4236 PACKET_qXfer_siginfo_read },
4237 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4238 PACKET_qXfer_siginfo_write },
4082afcc 4239 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4240 PACKET_ConditionalTracepoints },
4082afcc 4241 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4242 PACKET_ConditionalBreakpoints },
4082afcc 4243 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4244 PACKET_BreakpointCommands },
4082afcc 4245 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4246 PACKET_FastTracepoints },
4082afcc 4247 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4248 PACKET_StaticTracepoints },
4082afcc 4249 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4250 PACKET_InstallInTrace},
4082afcc
PA
4251 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4252 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4253 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4254 PACKET_bc },
4255 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4256 PACKET_bs },
409873ef
SS
4257 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4258 PACKET_TracepointSource },
d914c394
SS
4259 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4260 PACKET_QAllow },
4082afcc
PA
4261 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4262 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4263 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4264 PACKET_qXfer_fdpic },
169081d0
TG
4265 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4266 PACKET_qXfer_uib },
03583c20
UW
4267 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4268 PACKET_QDisableRandomization },
d1feda86 4269 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4270 { "QTBuffer:size", PACKET_DISABLE,
4271 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4272 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4273 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4274 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4275 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4276 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4277 PACKET_qXfer_btrace },
4278 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4279 PACKET_qXfer_btrace_conf },
4280 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4281 PACKET_Qbtrace_conf_bts_size },
4282 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4283 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4284 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4285 PACKET_fork_event_feature },
4286 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4287 PACKET_vfork_event_feature },
b20a6524
MM
4288 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4289 PACKET_Qbtrace_conf_pt_size }
be2a5f71
DJ
4290};
4291
c8d5aac9
L
4292static char *remote_support_xml;
4293
4294/* Register string appended to "xmlRegisters=" in qSupported query. */
4295
4296void
6e39997a 4297register_remote_support_xml (const char *xml)
c8d5aac9
L
4298{
4299#if defined(HAVE_LIBEXPAT)
4300 if (remote_support_xml == NULL)
c4f7c687 4301 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4302 else
4303 {
4304 char *copy = xstrdup (remote_support_xml + 13);
4305 char *p = strtok (copy, ",");
4306
4307 do
4308 {
4309 if (strcmp (p, xml) == 0)
4310 {
4311 /* already there */
4312 xfree (copy);
4313 return;
4314 }
4315 }
4316 while ((p = strtok (NULL, ",")) != NULL);
4317 xfree (copy);
4318
94b0dee1
PA
4319 remote_support_xml = reconcat (remote_support_xml,
4320 remote_support_xml, ",", xml,
4321 (char *) NULL);
c8d5aac9
L
4322 }
4323#endif
4324}
4325
4326static char *
4327remote_query_supported_append (char *msg, const char *append)
4328{
4329 if (msg)
94b0dee1 4330 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4331 else
4332 return xstrdup (append);
4333}
4334
be2a5f71
DJ
4335static void
4336remote_query_supported (void)
4337{
4338 struct remote_state *rs = get_remote_state ();
4339 char *next;
4340 int i;
4341 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4342
4343 /* The packet support flags are handled differently for this packet
4344 than for most others. We treat an error, a disabled packet, and
4345 an empty response identically: any features which must be reported
4346 to be used will be automatically disabled. An empty buffer
4347 accomplishes this, since that is also the representation for a list
4348 containing no features. */
4349
4350 rs->buf[0] = 0;
4082afcc 4351 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4352 {
c8d5aac9 4353 char *q = NULL;
94b0dee1 4354 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4355
73b8c1fd
PA
4356 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4357 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4358
f7e6eed5
PA
4359 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4360 q = remote_query_supported_append (q, "swbreak+");
4361 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4362 q = remote_query_supported_append (q, "hwbreak+");
4363
c8d5aac9
L
4364 if (remote_support_xml)
4365 q = remote_query_supported_append (q, remote_support_xml);
4366
dde08ee1
PA
4367 q = remote_query_supported_append (q, "qRelocInsn+");
4368
89245bc0
DB
4369 if (rs->extended)
4370 {
4371 if (packet_set_cmd_state (PACKET_fork_event_feature)
4372 != AUTO_BOOLEAN_FALSE)
4373 q = remote_query_supported_append (q, "fork-events+");
4374 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4375 != AUTO_BOOLEAN_FALSE)
4376 q = remote_query_supported_append (q, "vfork-events+");
4377 }
4378
dde08ee1
PA
4379 q = reconcat (q, "qSupported:", q, (char *) NULL);
4380 putpkt (q);
82f73884 4381
94b0dee1
PA
4382 do_cleanups (old_chain);
4383
be2a5f71
DJ
4384 getpkt (&rs->buf, &rs->buf_size, 0);
4385
4386 /* If an error occured, warn, but do not return - just reset the
4387 buffer to empty and go on to disable features. */
4388 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4389 == PACKET_ERROR)
4390 {
4391 warning (_("Remote failure reply: %s"), rs->buf);
4392 rs->buf[0] = 0;
4393 }
4394 }
4395
4396 memset (seen, 0, sizeof (seen));
4397
4398 next = rs->buf;
4399 while (*next)
4400 {
4401 enum packet_support is_supported;
4402 char *p, *end, *name_end, *value;
4403
4404 /* First separate out this item from the rest of the packet. If
4405 there's another item after this, we overwrite the separator
4406 (terminated strings are much easier to work with). */
4407 p = next;
4408 end = strchr (p, ';');
4409 if (end == NULL)
4410 {
4411 end = p + strlen (p);
4412 next = end;
4413 }
4414 else
4415 {
89be2091
DJ
4416 *end = '\0';
4417 next = end + 1;
4418
be2a5f71
DJ
4419 if (end == p)
4420 {
4421 warning (_("empty item in \"qSupported\" response"));
4422 continue;
4423 }
be2a5f71
DJ
4424 }
4425
4426 name_end = strchr (p, '=');
4427 if (name_end)
4428 {
4429 /* This is a name=value entry. */
4430 is_supported = PACKET_ENABLE;
4431 value = name_end + 1;
4432 *name_end = '\0';
4433 }
4434 else
4435 {
4436 value = NULL;
4437 switch (end[-1])
4438 {
4439 case '+':
4440 is_supported = PACKET_ENABLE;
4441 break;
4442
4443 case '-':
4444 is_supported = PACKET_DISABLE;
4445 break;
4446
4447 case '?':
4448 is_supported = PACKET_SUPPORT_UNKNOWN;
4449 break;
4450
4451 default:
3e43a32a
MS
4452 warning (_("unrecognized item \"%s\" "
4453 "in \"qSupported\" response"), p);
be2a5f71
DJ
4454 continue;
4455 }
4456 end[-1] = '\0';
4457 }
4458
4459 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4460 if (strcmp (remote_protocol_features[i].name, p) == 0)
4461 {
4462 const struct protocol_feature *feature;
4463
4464 seen[i] = 1;
4465 feature = &remote_protocol_features[i];
4466 feature->func (feature, is_supported, value);
4467 break;
4468 }
4469 }
4470
4471 /* If we increased the packet size, make sure to increase the global
4472 buffer size also. We delay this until after parsing the entire
4473 qSupported packet, because this is the same buffer we were
4474 parsing. */
4475 if (rs->buf_size < rs->explicit_packet_size)
4476 {
4477 rs->buf_size = rs->explicit_packet_size;
4478 rs->buf = xrealloc (rs->buf, rs->buf_size);
4479 }
4480
4481 /* Handle the defaults for unmentioned features. */
4482 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4483 if (!seen[i])
4484 {
4485 const struct protocol_feature *feature;
4486
4487 feature = &remote_protocol_features[i];
4488 feature->func (feature, feature->default_support, NULL);
4489 }
4490}
4491
78a095c3
JK
4492/* Remove any of the remote.c targets from target stack. Upper targets depend
4493 on it so remove them first. */
4494
4495static void
4496remote_unpush_target (void)
4497{
4498 pop_all_targets_above (process_stratum - 1);
4499}
be2a5f71 4500
c906108c 4501static void
014f9477 4502remote_open_1 (const char *name, int from_tty,
3e43a32a 4503 struct target_ops *target, int extended_p)
c906108c 4504{
d01949b6 4505 struct remote_state *rs = get_remote_state ();
a6f3e723 4506
c906108c 4507 if (name == 0)
8a3fe4f8 4508 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4509 "serial device is attached to the remote system\n"
8a3fe4f8 4510 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4511
23860348 4512 /* See FIXME above. */
c6ebd6cf 4513 if (!target_async_permitted)
92d1e331 4514 wait_forever_enabled_p = 1;
6426a772 4515
2d717e4f 4516 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4517 Ask this question first, before target_preopen has a chance to kill
4518 anything. */
5d93a237 4519 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4520 {
78a095c3
JK
4521 if (from_tty
4522 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4523 error (_("Still connected."));
4524 }
4525
78a095c3 4526 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4527 target_preopen (from_tty);
4528
89be2091 4529 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4530 xfree (rs->last_pass_packet);
4531 rs->last_pass_packet = NULL;
89be2091 4532
9b224c5e
PA
4533 /* Make sure we send the program signals list the next time we
4534 resume. */
5e4a05c4
TT
4535 xfree (rs->last_program_signals_packet);
4536 rs->last_program_signals_packet = NULL;
9b224c5e 4537
ad9a8f3f 4538 remote_fileio_reset ();
1dd41f16
NS
4539 reopen_exec_file ();
4540 reread_symbols ();
4541
5d93a237
TT
4542 rs->remote_desc = remote_serial_open (name);
4543 if (!rs->remote_desc)
c906108c
SS
4544 perror_with_name (name);
4545
4546 if (baud_rate != -1)
4547 {
5d93a237 4548 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4549 {
9b74d5d3
KB
4550 /* The requested speed could not be set. Error out to
4551 top level after closing remote_desc. Take care to
4552 set remote_desc to NULL to avoid closing remote_desc
4553 more than once. */
5d93a237
TT
4554 serial_close (rs->remote_desc);
4555 rs->remote_desc = NULL;
c906108c
SS
4556 perror_with_name (name);
4557 }
4558 }
4559
236af5e3 4560 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4561 serial_raw (rs->remote_desc);
c906108c
SS
4562
4563 /* If there is something sitting in the buffer we might take it as a
4564 response to a command, which would be bad. */
5d93a237 4565 serial_flush_input (rs->remote_desc);
c906108c
SS
4566
4567 if (from_tty)
4568 {
4569 puts_filtered ("Remote debugging using ");
4570 puts_filtered (name);
4571 puts_filtered ("\n");
4572 }
23860348 4573 push_target (target); /* Switch to using remote target now. */
c906108c 4574
74531fed
PA
4575 /* Register extra event sources in the event loop. */
4576 remote_async_inferior_event_token
4577 = create_async_event_handler (remote_async_inferior_event_handler,
4578 NULL);
5965e028 4579 rs->notif_state = remote_notif_state_allocate ();
74531fed 4580
be2a5f71
DJ
4581 /* Reset the target state; these things will be queried either by
4582 remote_query_supported or as they are needed. */
ca4f7f8b 4583 reset_all_packet_configs_support ();
74531fed 4584 rs->cached_wait_status = 0;
be2a5f71 4585 rs->explicit_packet_size = 0;
a6f3e723 4586 rs->noack_mode = 0;
82f73884 4587 rs->extended = extended_p;
e24a49d8 4588 rs->waiting_for_stop_reply = 0;
3a29589a 4589 rs->ctrlc_pending_p = 0;
802188a7 4590
47f8a51d
TT
4591 rs->general_thread = not_sent_ptid;
4592 rs->continue_thread = not_sent_ptid;
262e1174 4593 rs->remote_traceframe_number = -1;
c906108c 4594
9d1f7ab2 4595 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4596 rs->use_threadinfo_query = 1;
4597 rs->use_threadextra_query = 1;
9d1f7ab2 4598
80152258
PA
4599 readahead_cache_invalidate ();
4600
c6ebd6cf 4601 if (target_async_permitted)
92d1e331 4602 {
23860348 4603 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4604 remote_async_terminal_ours_p = 1;
4605
4606 /* FIXME: cagney/1999-09-23: During the initial connection it is
4607 assumed that the target is already ready and able to respond to
0df8b418 4608 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4609 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4610 around this. Eventually a mechanism that allows
92d1e331 4611 wait_for_inferior() to expect/get timeouts will be
23860348 4612 implemented. */
92d1e331
DJ
4613 wait_forever_enabled_p = 0;
4614 }
4615
23860348 4616 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4617 no_shared_libraries (NULL, 0);
f78f6cf1 4618
74531fed
PA
4619 /* Start afresh. */
4620 init_thread_list ();
4621
36918e70 4622 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4623 target (we'd otherwise be in an inconsistent state) and then
4624 propogate the error on up the exception chain. This ensures that
4625 the caller doesn't stumble along blindly assuming that the
4626 function succeeded. The CLI doesn't have this problem but other
4627 UI's, such as MI do.
36918e70
AC
4628
4629 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4630 this function should return an error indication letting the
ce2826aa 4631 caller restore the previous state. Unfortunately the command
36918e70
AC
4632 ``target remote'' is directly wired to this function making that
4633 impossible. On a positive note, the CLI side of this problem has
4634 been fixed - the function set_cmd_context() makes it possible for
4635 all the ``target ....'' commands to share a common callback
4636 function. See cli-dump.c. */
109c3e39 4637 {
2d717e4f 4638
492d29ea 4639 TRY
04bd08de
TT
4640 {
4641 remote_start_remote (from_tty, target, extended_p);
4642 }
492d29ea 4643 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4644 {
c8d104ad
PA
4645 /* Pop the partially set up target - unless something else did
4646 already before throwing the exception. */
5d93a237 4647 if (rs->remote_desc != NULL)
78a095c3 4648 remote_unpush_target ();
c6ebd6cf 4649 if (target_async_permitted)
109c3e39
AC
4650 wait_forever_enabled_p = 1;
4651 throw_exception (ex);
4652 }
492d29ea 4653 END_CATCH
109c3e39 4654 }
c906108c 4655
f4abbc16
MM
4656 remote_btrace_reset ();
4657
c6ebd6cf 4658 if (target_async_permitted)
92d1e331 4659 wait_forever_enabled_p = 1;
43ff13b4
JM
4660}
4661
de0d863e
DB
4662/* Detach the specified process. */
4663
4664static void
4665remote_detach_pid (int pid)
4666{
4667 struct remote_state *rs = get_remote_state ();
4668
4669 if (remote_multi_process_p (rs))
4670 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4671 else
4672 strcpy (rs->buf, "D");
4673
4674 putpkt (rs->buf);
4675 getpkt (&rs->buf, &rs->buf_size, 0);
4676
4677 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4678 ;
4679 else if (rs->buf[0] == '\0')
4680 error (_("Remote doesn't know how to detach"));
4681 else
4682 error (_("Can't detach process."));
4683}
4684
4685/* This detaches a program to which we previously attached, using
4686 inferior_ptid to identify the process. After this is done, GDB
4687 can be used to debug some other program. We better not have left
4688 any breakpoints in the target program or it'll die when it hits
4689 one. */
c906108c
SS
4690
4691static void
de0d863e 4692remote_detach_1 (const char *args, int from_tty)
c906108c 4693{
82f73884 4694 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4695 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4696 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4697 int is_fork_parent;
c906108c
SS
4698
4699 if (args)
8a3fe4f8 4700 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4701
2d717e4f
DJ
4702 if (!target_has_execution)
4703 error (_("No process to detach from."));
4704
7cee1e54
PA
4705 if (from_tty)
4706 {
4707 char *exec_file = get_exec_file (0);
4708 if (exec_file == NULL)
4709 exec_file = "";
4710 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4711 target_pid_to_str (pid_to_ptid (pid)));
4712 gdb_flush (gdb_stdout);
4713 }
4714
c906108c 4715 /* Tell the remote target to detach. */
de0d863e 4716 remote_detach_pid (pid);
82f73884 4717
de0d863e 4718 if (from_tty && !rs->extended)
7cee1e54 4719 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4720
de0d863e
DB
4721 /* Check to see if we are detaching a fork parent. Note that if we
4722 are detaching a fork child, tp == NULL. */
4723 is_fork_parent = (tp != NULL
4724 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4725
4726 /* If doing detach-on-fork, we don't mourn, because that will delete
4727 breakpoints that should be available for the followed inferior. */
4728 if (!is_fork_parent)
4729 target_mourn_inferior ();
4730 else
4731 {
4732 inferior_ptid = null_ptid;
4733 detach_inferior (pid);
4734 }
2d717e4f
DJ
4735}
4736
4737static void
52554a0e 4738remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4739{
de0d863e 4740 remote_detach_1 (args, from_tty);
2d717e4f
DJ
4741}
4742
4743static void
52554a0e 4744extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4745{
de0d863e
DB
4746 remote_detach_1 (args, from_tty);
4747}
4748
4749/* Target follow-fork function for remote targets. On entry, and
4750 at return, the current inferior is the fork parent.
4751
4752 Note that although this is currently only used for extended-remote,
4753 it is named remote_follow_fork in anticipation of using it for the
4754 remote target as well. */
4755
4756static int
4757remote_follow_fork (struct target_ops *ops, int follow_child,
4758 int detach_fork)
4759{
4760 struct remote_state *rs = get_remote_state ();
c269dbdb 4761 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 4762
c269dbdb
DB
4763 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4764 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
4765 {
4766 /* When following the parent and detaching the child, we detach
4767 the child here. For the case of following the child and
4768 detaching the parent, the detach is done in the target-
4769 independent follow fork code in infrun.c. We can't use
4770 target_detach when detaching an unfollowed child because
4771 the client side doesn't know anything about the child. */
4772 if (detach_fork && !follow_child)
4773 {
4774 /* Detach the fork child. */
4775 ptid_t child_ptid;
4776 pid_t child_pid;
4777
4778 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4779 child_pid = ptid_get_pid (child_ptid);
4780
4781 remote_detach_pid (child_pid);
4782 detach_inferior (child_pid);
4783 }
4784 }
4785 return 0;
c906108c
SS
4786}
4787
6ad8ae5c
DJ
4788/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4789
43ff13b4 4790static void
fee354ee 4791remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4792{
43ff13b4 4793 if (args)
2d717e4f 4794 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4795
2d717e4f 4796 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 4797 won't do it. So call remote_mourn directly instead of
2d717e4f 4798 target_mourn_inferior. */
20f796c9 4799 remote_mourn (target);
2d717e4f 4800
43ff13b4
JM
4801 if (from_tty)
4802 puts_filtered ("Ending remote debugging.\n");
4803}
4804
2d717e4f
DJ
4805/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4806 be chatty about it. */
4807
4808static void
20f796c9
GB
4809extended_remote_attach (struct target_ops *target, const char *args,
4810 int from_tty)
2d717e4f
DJ
4811{
4812 struct remote_state *rs = get_remote_state ();
be86555c 4813 int pid;
96ef3384 4814 char *wait_status = NULL;
2d717e4f 4815
74164c56 4816 pid = parse_pid_to_attach (args);
2d717e4f 4817
74164c56
JK
4818 /* Remote PID can be freely equal to getpid, do not check it here the same
4819 way as in other targets. */
2d717e4f 4820
4082afcc 4821 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4822 error (_("This target does not support attaching to a process"));
4823
7cee1e54
PA
4824 if (from_tty)
4825 {
4826 char *exec_file = get_exec_file (0);
4827
4828 if (exec_file)
4829 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4830 target_pid_to_str (pid_to_ptid (pid)));
4831 else
4832 printf_unfiltered (_("Attaching to %s\n"),
4833 target_pid_to_str (pid_to_ptid (pid)));
4834
4835 gdb_flush (gdb_stdout);
4836 }
4837
bba74b36 4838 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4839 putpkt (rs->buf);
4840 getpkt (&rs->buf, &rs->buf_size, 0);
4841
4082afcc
PA
4842 switch (packet_ok (rs->buf,
4843 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4844 {
4082afcc 4845 case PACKET_OK:
74531fed
PA
4846 if (!non_stop)
4847 {
4848 /* Save the reply for later. */
4849 wait_status = alloca (strlen (rs->buf) + 1);
4850 strcpy (wait_status, rs->buf);
4851 }
4852 else if (strcmp (rs->buf, "OK") != 0)
4853 error (_("Attaching to %s failed with: %s"),
4854 target_pid_to_str (pid_to_ptid (pid)),
4855 rs->buf);
4082afcc
PA
4856 break;
4857 case PACKET_UNKNOWN:
4858 error (_("This target does not support attaching to a process"));
4859 default:
4860 error (_("Attaching to %s failed"),
4861 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4862 }
2d717e4f 4863
1b6e6f5c 4864 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 4865
2d717e4f 4866 inferior_ptid = pid_to_ptid (pid);
79d7f229 4867
bad34192
PA
4868 if (non_stop)
4869 {
4870 struct thread_info *thread;
79d7f229 4871
bad34192 4872 /* Get list of threads. */
e8032dde 4873 remote_update_thread_list (target);
82f73884 4874
bad34192
PA
4875 thread = first_thread_of_process (pid);
4876 if (thread)
4877 inferior_ptid = thread->ptid;
4878 else
4879 inferior_ptid = pid_to_ptid (pid);
4880
4881 /* Invalidate our notion of the remote current thread. */
47f8a51d 4882 record_currthread (rs, minus_one_ptid);
bad34192 4883 }
74531fed 4884 else
bad34192
PA
4885 {
4886 /* Now, if we have thread information, update inferior_ptid. */
4887 inferior_ptid = remote_current_thread (inferior_ptid);
4888
4889 /* Add the main thread to the thread list. */
4890 add_thread_silent (inferior_ptid);
4891 }
c0a2216e 4892
96ef3384
UW
4893 /* Next, if the target can specify a description, read it. We do
4894 this before anything involving memory or registers. */
4895 target_find_description ();
4896
74531fed
PA
4897 if (!non_stop)
4898 {
4899 /* Use the previously fetched status. */
4900 gdb_assert (wait_status != NULL);
4901
4902 if (target_can_async_p ())
4903 {
722247f1
YQ
4904 struct notif_event *reply
4905 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4906
722247f1 4907 push_stop_reply ((struct stop_reply *) reply);
74531fed 4908
6a3753b3 4909 target_async (1);
74531fed
PA
4910 }
4911 else
4912 {
4913 gdb_assert (wait_status != NULL);
4914 strcpy (rs->buf, wait_status);
4915 rs->cached_wait_status = 1;
4916 }
4917 }
4918 else
4919 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4920}
4921
b9c1d481
AS
4922/* Implementation of the to_post_attach method. */
4923
4924static void
4925extended_remote_post_attach (struct target_ops *ops, int pid)
4926{
4927 /* In certain cases GDB might not have had the chance to start
4928 symbol lookup up until now. This could happen if the debugged
4929 binary is not using shared libraries, the vsyscall page is not
4930 present (on Linux) and the binary itself hadn't changed since the
4931 debugging process was started. */
4932 if (symfile_objfile != NULL)
4933 remote_check_symbols();
4934}
4935
c906108c 4936\f
506fb367
DJ
4937/* Check for the availability of vCont. This function should also check
4938 the response. */
c906108c
SS
4939
4940static void
6d820c5c 4941remote_vcont_probe (struct remote_state *rs)
c906108c 4942{
2e9f7625 4943 char *buf;
6d820c5c 4944
2e9f7625
DJ
4945 strcpy (rs->buf, "vCont?");
4946 putpkt (rs->buf);
6d820c5c 4947 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4948 buf = rs->buf;
c906108c 4949
506fb367 4950 /* Make sure that the features we assume are supported. */
61012eef 4951 if (startswith (buf, "vCont"))
506fb367
DJ
4952 {
4953 char *p = &buf[5];
4954 int support_s, support_S, support_c, support_C;
4955
4956 support_s = 0;
4957 support_S = 0;
4958 support_c = 0;
4959 support_C = 0;
d458bd84 4960 rs->supports_vCont.t = 0;
c1e36e3e 4961 rs->supports_vCont.r = 0;
506fb367
DJ
4962 while (p && *p == ';')
4963 {
4964 p++;
4965 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4966 support_s = 1;
4967 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4968 support_S = 1;
4969 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4970 support_c = 1;
4971 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4972 support_C = 1;
74531fed 4973 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4974 rs->supports_vCont.t = 1;
c1e36e3e
PA
4975 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4976 rs->supports_vCont.r = 1;
506fb367
DJ
4977
4978 p = strchr (p, ';');
4979 }
c906108c 4980
506fb367
DJ
4981 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4982 BUF will make packet_ok disable the packet. */
4983 if (!support_s || !support_S || !support_c || !support_C)
4984 buf[0] = 0;
4985 }
c906108c 4986
444abaca 4987 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4988}
c906108c 4989
0d8f58ca
PA
4990/* Helper function for building "vCont" resumptions. Write a
4991 resumption to P. ENDP points to one-passed-the-end of the buffer
4992 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4993 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4994 resumed thread should be single-stepped and/or signalled. If PTID
4995 equals minus_one_ptid, then all threads are resumed; if PTID
4996 represents a process, then all threads of the process are resumed;
4997 the thread to be stepped and/or signalled is given in the global
4998 INFERIOR_PTID. */
4999
5000static char *
5001append_resumption (char *p, char *endp,
2ea28649 5002 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5003{
5004 struct remote_state *rs = get_remote_state ();
5005
a493e3e2 5006 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5007 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5008 else if (step
5009 /* GDB is willing to range step. */
5010 && use_range_stepping
5011 /* Target supports range stepping. */
5012 && rs->supports_vCont.r
5013 /* We don't currently support range stepping multiple
5014 threads with a wildcard (though the protocol allows it,
5015 so stubs shouldn't make an active effort to forbid
5016 it). */
5017 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5018 {
5019 struct thread_info *tp;
5020
5021 if (ptid_equal (ptid, minus_one_ptid))
5022 {
5023 /* If we don't know about the target thread's tid, then
5024 we're resuming magic_null_ptid (see caller). */
5025 tp = find_thread_ptid (magic_null_ptid);
5026 }
5027 else
5028 tp = find_thread_ptid (ptid);
5029 gdb_assert (tp != NULL);
5030
5031 if (tp->control.may_range_step)
5032 {
5033 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5034
5035 p += xsnprintf (p, endp - p, ";r%s,%s",
5036 phex_nz (tp->control.step_range_start,
5037 addr_size),
5038 phex_nz (tp->control.step_range_end,
5039 addr_size));
5040 }
5041 else
5042 p += xsnprintf (p, endp - p, ";s");
5043 }
0d8f58ca
PA
5044 else if (step)
5045 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5046 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5047 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5048 else
5049 p += xsnprintf (p, endp - p, ";c");
5050
5051 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5052 {
5053 ptid_t nptid;
5054
5055 /* All (-1) threads of process. */
ba348170 5056 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5057
5058 p += xsnprintf (p, endp - p, ":");
5059 p = write_ptid (p, endp, nptid);
5060 }
5061 else if (!ptid_equal (ptid, minus_one_ptid))
5062 {
5063 p += xsnprintf (p, endp - p, ":");
5064 p = write_ptid (p, endp, ptid);
5065 }
5066
5067 return p;
5068}
5069
e5ef252a
PA
5070/* Append a vCont continue-with-signal action for threads that have a
5071 non-zero stop signal. */
5072
5073static char *
5074append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5075{
5076 struct thread_info *thread;
5077
034f788c 5078 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5079 if (ptid_match (thread->ptid, ptid)
5080 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5081 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5082 {
5083 p = append_resumption (p, endp, thread->ptid,
5084 0, thread->suspend.stop_signal);
5085 thread->suspend.stop_signal = GDB_SIGNAL_0;
5086 }
5087
5088 return p;
5089}
5090
506fb367
DJ
5091/* Resume the remote inferior by using a "vCont" packet. The thread
5092 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5093 resumed thread should be single-stepped and/or signalled. If PTID
5094 equals minus_one_ptid, then all threads are resumed; the thread to
5095 be stepped and/or signalled is given in the global INFERIOR_PTID.
5096 This function returns non-zero iff it resumes the inferior.
44eaed12 5097
506fb367
DJ
5098 This function issues a strict subset of all possible vCont commands at the
5099 moment. */
44eaed12 5100
506fb367 5101static int
2ea28649 5102remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5103{
5104 struct remote_state *rs = get_remote_state ();
82f73884
PA
5105 char *p;
5106 char *endp;
44eaed12 5107
4082afcc 5108 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5109 remote_vcont_probe (rs);
44eaed12 5110
4082afcc 5111 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5112 return 0;
44eaed12 5113
82f73884
PA
5114 p = rs->buf;
5115 endp = rs->buf + get_remote_packet_size ();
5116
506fb367
DJ
5117 /* If we could generate a wider range of packets, we'd have to worry
5118 about overflowing BUF. Should there be a generic
5119 "multi-part-packet" packet? */
5120
0d8f58ca
PA
5121 p += xsnprintf (p, endp - p, "vCont");
5122
79d7f229 5123 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5124 {
79d7f229
PA
5125 /* MAGIC_NULL_PTID means that we don't have any active threads,
5126 so we don't have any TID numbers the inferior will
5127 understand. Make sure to only send forms that do not specify
5128 a TID. */
a9cbf802 5129 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5130 }
0d8f58ca 5131 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5132 {
0d8f58ca
PA
5133 /* Resume all threads (of all processes, or of a single
5134 process), with preference for INFERIOR_PTID. This assumes
5135 inferior_ptid belongs to the set of all threads we are about
5136 to resume. */
a493e3e2 5137 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5138 {
0d8f58ca
PA
5139 /* Step inferior_ptid, with or without signal. */
5140 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5141 }
0d8f58ca 5142
e5ef252a
PA
5143 /* Also pass down any pending signaled resumption for other
5144 threads not the current. */
5145 p = append_pending_thread_resumptions (p, endp, ptid);
5146
0d8f58ca 5147 /* And continue others without a signal. */
a493e3e2 5148 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5149 }
5150 else
506fb367
DJ
5151 {
5152 /* Scheduler locking; resume only PTID. */
a9cbf802 5153 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5154 }
c906108c 5155
82f73884
PA
5156 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5157 putpkt (rs->buf);
506fb367 5158
74531fed
PA
5159 if (non_stop)
5160 {
5161 /* In non-stop, the stub replies to vCont with "OK". The stop
5162 reply will be reported asynchronously by means of a `%Stop'
5163 notification. */
5164 getpkt (&rs->buf, &rs->buf_size, 0);
5165 if (strcmp (rs->buf, "OK") != 0)
5166 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5167 }
5168
506fb367 5169 return 1;
c906108c 5170}
43ff13b4 5171
506fb367
DJ
5172/* Tell the remote machine to resume. */
5173
43ff13b4 5174static void
28439f5e 5175remote_resume (struct target_ops *ops,
2ea28649 5176 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5177{
d01949b6 5178 struct remote_state *rs = get_remote_state ();
2e9f7625 5179 char *buf;
43ff13b4 5180
722247f1
YQ
5181 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5182 (explained in remote-notif.c:handle_notification) so
5183 remote_notif_process is not called. We need find a place where
5184 it is safe to start a 'vNotif' sequence. It is good to do it
5185 before resuming inferior, because inferior was stopped and no RSP
5186 traffic at that moment. */
5187 if (!non_stop)
5965e028 5188 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5189
b73be471 5190 rs->last_sent_signal = siggnal;
280ceea3 5191 rs->last_sent_step = step;
43ff13b4 5192
506fb367 5193 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5194 /* No reverse support (yet) for vCont. */
5195 if (execution_direction != EXEC_REVERSE)
5196 if (remote_vcont_resume (ptid, step, siggnal))
5197 goto done;
506fb367 5198
79d7f229
PA
5199 /* All other supported resume packets do use Hc, so set the continue
5200 thread. */
5201 if (ptid_equal (ptid, minus_one_ptid))
5202 set_continue_thread (any_thread_ptid);
506fb367 5203 else
79d7f229 5204 set_continue_thread (ptid);
506fb367 5205
2e9f7625 5206 buf = rs->buf;
b2175913
MS
5207 if (execution_direction == EXEC_REVERSE)
5208 {
5209 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5210 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5211 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5212 siggnal);
40ab02ce 5213
4082afcc 5214 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5215 error (_("Remote reverse-step not supported."));
4082afcc 5216 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5217 error (_("Remote reverse-continue not supported."));
40ab02ce 5218
b2175913
MS
5219 strcpy (buf, step ? "bs" : "bc");
5220 }
a493e3e2 5221 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5222 {
5223 buf[0] = step ? 'S' : 'C';
c5aa993b 5224 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5225 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5226 buf[3] = '\0';
5227 }
5228 else
c5aa993b 5229 strcpy (buf, step ? "s" : "c");
506fb367 5230
44eaed12 5231 putpkt (buf);
43ff13b4 5232
75c99385 5233 done:
2acceee2 5234 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5235 with the event loop. NOTE: this is the one place where all the
5236 execution commands end up. We could alternatively do this in each
23860348 5237 of the execution commands in infcmd.c. */
2acceee2
JM
5238 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5239 into infcmd.c in order to allow inferior function calls to work
23860348 5240 NOT asynchronously. */
362646f5 5241 if (target_can_async_p ())
6a3753b3 5242 target_async (1);
e24a49d8
PA
5243
5244 /* We've just told the target to resume. The remote server will
5245 wait for the inferior to stop, and then send a stop reply. In
5246 the mean time, we can't start another command/query ourselves
74531fed
PA
5247 because the stub wouldn't be ready to process it. This applies
5248 only to the base all-stop protocol, however. In non-stop (which
5249 only supports vCont), the stub replies with an "OK", and is
5250 immediate able to process further serial input. */
5251 if (!non_stop)
5252 rs->waiting_for_stop_reply = 1;
43ff13b4 5253}
c906108c 5254\f
43ff13b4
JM
5255
5256/* Set up the signal handler for SIGINT, while the target is
23860348 5257 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5258static void
934b9bac 5259async_initialize_sigint_signal_handler (void)
43ff13b4 5260{
934b9bac 5261 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5262}
5263
23860348 5264/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5265static void
934b9bac 5266async_handle_remote_sigint (int sig)
43ff13b4 5267{
934b9bac 5268 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5269 /* Note we need to go through gdb_call_async_signal_handler in order
5270 to wake up the event loop on Windows. */
5271 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5272}
5273
5274/* Signal handler for SIGINT, installed after SIGINT has already been
5275 sent once. It will take effect the second time that the user sends
23860348 5276 a ^C. */
43ff13b4 5277static void
934b9bac 5278async_handle_remote_sigint_twice (int sig)
43ff13b4 5279{
934b9bac 5280 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5281 /* See note in async_handle_remote_sigint. */
5282 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5283}
5284
abc56d60
PA
5285/* Implementation of to_check_pending_interrupt. */
5286
5287static void
5288remote_check_pending_interrupt (struct target_ops *self)
5289{
5290 struct async_signal_handler *token = async_sigint_remote_twice_token;
5291
5292 if (async_signal_handler_is_marked (token))
5293 {
5294 clear_async_signal_handler (token);
5295 call_async_signal_handler (token);
5296 }
5297}
5298
6426a772 5299/* Perform the real interruption of the target execution, in response
23860348 5300 to a ^C. */
c5aa993b 5301static void
fba45db2 5302async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5303{
5304 if (remote_debug)
248fd3bf 5305 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5306
94cc34af 5307 target_stop (inferior_ptid);
43ff13b4
JM
5308}
5309
0df8b418 5310/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5311 up on the target alltogether. */
47e1ce27 5312static void
fba45db2 5313async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5314{
2df3850c 5315 if (remote_debug)
248fd3bf 5316 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5317
5318 interrupt_query ();
43ff13b4
JM
5319}
5320
5321/* Reinstall the usual SIGINT handlers, after the target has
23860348 5322 stopped. */
6426a772 5323static void
934b9bac 5324async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5325{
5326 signal (SIGINT, handle_sigint);
43ff13b4
JM
5327}
5328
c906108c
SS
5329/* Send ^C to target to halt it. Target will respond, and send us a
5330 packet. */
507f3c78 5331static void (*ofunc) (int);
c906108c 5332
bfedc46a
PA
5333/* The command line interface's interrupt routine. This function is installed
5334 as a signal handler for SIGINT. The first time a user requests an
5335 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5336 response from the target (it didn't stop when the user requested it),
23860348 5337 we ask the user if he'd like to detach from the target. */
bfedc46a 5338
c906108c 5339static void
934b9bac 5340sync_remote_interrupt (int signo)
c906108c 5341{
23860348 5342 /* If this doesn't work, try more severe steps. */
934b9bac 5343 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5344
934b9bac 5345 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5346}
5347
5348/* The user typed ^C twice. */
5349
5350static void
934b9bac 5351sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5352{
5353 signal (signo, ofunc);
934b9bac
JK
5354 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5355 signal (signo, sync_remote_interrupt);
c906108c 5356}
7a292a7a 5357
74531fed
PA
5358/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5359 thread, all threads of a remote process, or all threads of all
5360 processes. */
5361
5362static void
5363remote_stop_ns (ptid_t ptid)
5364{
5365 struct remote_state *rs = get_remote_state ();
5366 char *p = rs->buf;
5367 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5368
4082afcc 5369 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5370 remote_vcont_probe (rs);
5371
d458bd84 5372 if (!rs->supports_vCont.t)
74531fed
PA
5373 error (_("Remote server does not support stopping threads"));
5374
f91d3df5
PA
5375 if (ptid_equal (ptid, minus_one_ptid)
5376 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5377 p += xsnprintf (p, endp - p, "vCont;t");
5378 else
5379 {
5380 ptid_t nptid;
5381
74531fed
PA
5382 p += xsnprintf (p, endp - p, "vCont;t:");
5383
5384 if (ptid_is_pid (ptid))
5385 /* All (-1) threads of process. */
ba348170 5386 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5387 else
5388 {
5389 /* Small optimization: if we already have a stop reply for
5390 this thread, no use in telling the stub we want this
5391 stopped. */
5392 if (peek_stop_reply (ptid))
5393 return;
5394
5395 nptid = ptid;
5396 }
5397
a9cbf802 5398 write_ptid (p, endp, nptid);
74531fed
PA
5399 }
5400
5401 /* In non-stop, we get an immediate OK reply. The stop reply will
5402 come in asynchronously by notification. */
5403 putpkt (rs->buf);
5404 getpkt (&rs->buf, &rs->buf_size, 0);
5405 if (strcmp (rs->buf, "OK") != 0)
5406 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5407}
5408
bfedc46a
PA
5409/* All-stop version of target_interrupt. Sends a break or a ^C to
5410 interrupt the remote target. It is undefined which thread of which
5411 process reports the interrupt. */
74531fed
PA
5412
5413static void
bfedc46a 5414remote_interrupt_as (ptid_t ptid)
74531fed
PA
5415{
5416 struct remote_state *rs = get_remote_state ();
5417
3a29589a
DJ
5418 rs->ctrlc_pending_p = 1;
5419
74531fed
PA
5420 /* If the inferior is stopped already, but the core didn't know
5421 about it yet, just ignore the request. The cached wait status
5422 will be collected in remote_wait. */
5423 if (rs->cached_wait_status)
5424 return;
5425
9a7071a8
JB
5426 /* Send interrupt_sequence to remote target. */
5427 send_interrupt_sequence ();
74531fed
PA
5428}
5429
bfedc46a 5430/* Implement the to_stop function for the remote targets. */
74531fed 5431
c906108c 5432static void
1eab8a48 5433remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5434{
7a292a7a 5435 if (remote_debug)
0f71a2f6 5436 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5437
74531fed
PA
5438 if (non_stop)
5439 remote_stop_ns (ptid);
c906108c 5440 else
bfedc46a
PA
5441 {
5442 /* We don't currently have a way to transparently pause the
5443 remote target in all-stop mode. Interrupt it instead. */
5444 remote_interrupt_as (ptid);
5445 }
5446}
5447
5448/* Implement the to_interrupt function for the remote targets. */
5449
5450static void
5451remote_interrupt (struct target_ops *self, ptid_t ptid)
5452{
5453 if (remote_debug)
5454 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5455
5456 if (non_stop)
5457 {
5458 /* We don't currently have a way to ^C the remote target in
5459 non-stop mode. Stop it (with no signal) instead. */
5460 remote_stop_ns (ptid);
5461 }
5462 else
5463 remote_interrupt_as (ptid);
c906108c
SS
5464}
5465
5466/* Ask the user what to do when an interrupt is received. */
5467
5468static void
fba45db2 5469interrupt_query (void)
c906108c 5470{
abc56d60
PA
5471 struct remote_state *rs = get_remote_state ();
5472 struct cleanup *old_chain;
5473
5474 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5475 target_terminal_ours ();
5476
abc56d60 5477 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5478 {
abc56d60
PA
5479 if (query (_("The target is not responding to interrupt requests.\n"
5480 "Stop debugging it? ")))
74531fed 5481 {
78a095c3 5482 remote_unpush_target ();
abc56d60 5483 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5484 }
5485 }
abc56d60
PA
5486 else
5487 {
5488 if (query (_("Interrupted while waiting for the program.\n"
5489 "Give up waiting? ")))
5490 quit ();
5491 }
c906108c 5492
abc56d60 5493 do_cleanups (old_chain);
c906108c
SS
5494}
5495
6426a772
JM
5496/* Enable/disable target terminal ownership. Most targets can use
5497 terminal groups to control terminal ownership. Remote targets are
5498 different in that explicit transfer of ownership to/from GDB/target
23860348 5499 is required. */
6426a772
JM
5500
5501static void
d2f640d4 5502remote_terminal_inferior (struct target_ops *self)
6426a772 5503{
c6ebd6cf 5504 if (!target_async_permitted)
75c99385
PA
5505 /* Nothing to do. */
5506 return;
5507
d9d2d8b6
PA
5508 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5509 idempotent. The event-loop GDB talking to an asynchronous target
5510 with a synchronous command calls this function from both
5511 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5512 transfer the terminal to the target when it shouldn't this guard
5513 can go away. */
6426a772
JM
5514 if (!remote_async_terminal_ours_p)
5515 return;
5516 delete_file_handler (input_fd);
5517 remote_async_terminal_ours_p = 0;
934b9bac 5518 async_initialize_sigint_signal_handler ();
6426a772
JM
5519 /* NOTE: At this point we could also register our selves as the
5520 recipient of all input. Any characters typed could then be
23860348 5521 passed on down to the target. */
6426a772
JM
5522}
5523
5524static void
e3594fd1 5525remote_terminal_ours (struct target_ops *self)
6426a772 5526{
c6ebd6cf 5527 if (!target_async_permitted)
75c99385
PA
5528 /* Nothing to do. */
5529 return;
5530
5531 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5532 if (remote_async_terminal_ours_p)
5533 return;
934b9bac 5534 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5535 add_file_handler (input_fd, stdin_event_handler, 0);
5536 remote_async_terminal_ours_p = 1;
5537}
5538
176a6961 5539static void
917317f4 5540remote_console_output (char *msg)
c906108c
SS
5541{
5542 char *p;
5543
c5aa993b 5544 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5545 {
5546 char tb[2];
5547 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5548
c906108c
SS
5549 tb[0] = c;
5550 tb[1] = 0;
43ff13b4 5551 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5552 }
00db5b94
PA
5553 gdb_flush (gdb_stdtarg);
5554}
74531fed
PA
5555
5556typedef struct cached_reg
5557{
5558 int num;
5559 gdb_byte data[MAX_REGISTER_SIZE];
5560} cached_reg_t;
5561
5562DEF_VEC_O(cached_reg_t);
5563
722247f1 5564typedef struct stop_reply
74531fed 5565{
722247f1 5566 struct notif_event base;
74531fed 5567
722247f1 5568 /* The identifier of the thread about this event */
74531fed
PA
5569 ptid_t ptid;
5570
340e3c99 5571 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5572 connection, represented by a remote_state object, is closed,
5573 all the associated stop_reply events should be released. */
5574 struct remote_state *rs;
5575
74531fed
PA
5576 struct target_waitstatus ws;
5577
15148d6a
PA
5578 /* Expedited registers. This makes remote debugging a bit more
5579 efficient for those targets that provide critical registers as
5580 part of their normal status mechanism (as another roundtrip to
5581 fetch them is avoided). */
74531fed
PA
5582 VEC(cached_reg_t) *regcache;
5583
f7e6eed5
PA
5584 enum target_stop_reason stop_reason;
5585
74531fed
PA
5586 CORE_ADDR watch_data_address;
5587
dc146f7c 5588 int core;
722247f1 5589} *stop_reply_p;
a744cf53 5590
722247f1
YQ
5591DECLARE_QUEUE_P (stop_reply_p);
5592DEFINE_QUEUE_P (stop_reply_p);
5593/* The list of already fetched and acknowledged stop events. This
5594 queue is used for notification Stop, and other notifications
5595 don't need queue for their events, because the notification events
5596 of Stop can't be consumed immediately, so that events should be
5597 queued first, and be consumed by remote_wait_{ns,as} one per
5598 time. Other notifications can consume their events immediately,
5599 so queue is not needed for them. */
5600static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5601
5602static void
5603stop_reply_xfree (struct stop_reply *r)
5604{
f48ff2a7 5605 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5606}
5607
221e1a37
PA
5608/* Return the length of the stop reply queue. */
5609
5610static int
5611stop_reply_queue_length (void)
5612{
5613 return QUEUE_length (stop_reply_p, stop_reply_queue);
5614}
5615
722247f1
YQ
5616static void
5617remote_notif_stop_parse (struct notif_client *self, char *buf,
5618 struct notif_event *event)
5619{
5620 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5621}
5622
5623static void
5624remote_notif_stop_ack (struct notif_client *self, char *buf,
5625 struct notif_event *event)
5626{
5627 struct stop_reply *stop_reply = (struct stop_reply *) event;
5628
5629 /* acknowledge */
5630 putpkt ((char *) self->ack_command);
5631
5632 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5633 /* We got an unknown stop reply. */
5634 error (_("Unknown stop reply"));
5635
5636 push_stop_reply (stop_reply);
5637}
5638
5639static int
5640remote_notif_stop_can_get_pending_events (struct notif_client *self)
5641{
5642 /* We can't get pending events in remote_notif_process for
5643 notification stop, and we have to do this in remote_wait_ns
5644 instead. If we fetch all queued events from stub, remote stub
5645 may exit and we have no chance to process them back in
5646 remote_wait_ns. */
5647 mark_async_event_handler (remote_async_inferior_event_token);
5648 return 0;
5649}
5650
5651static void
5652stop_reply_dtr (struct notif_event *event)
5653{
5654 struct stop_reply *r = (struct stop_reply *) event;
5655
5656 VEC_free (cached_reg_t, r->regcache);
5657}
5658
5659static struct notif_event *
5660remote_notif_stop_alloc_reply (void)
5661{
8d749320
SM
5662 /* We cast to a pointer to the "base class". */
5663 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5664
5665 r->dtr = stop_reply_dtr;
5666
5667 return r;
5668}
5669
5670/* A client of notification Stop. */
5671
5672struct notif_client notif_client_stop =
5673{
5674 "Stop",
5675 "vStopped",
5676 remote_notif_stop_parse,
5677 remote_notif_stop_ack,
5678 remote_notif_stop_can_get_pending_events,
5679 remote_notif_stop_alloc_reply,
f48ff2a7 5680 REMOTE_NOTIF_STOP,
722247f1
YQ
5681};
5682
5683/* A parameter to pass data in and out. */
5684
5685struct queue_iter_param
5686{
5687 void *input;
5688 struct stop_reply *output;
5689};
5690
cbb8991c
DB
5691/* Determine if THREAD is a pending fork parent thread. ARG contains
5692 the pid of the process that owns the threads we want to check, or
5693 -1 if we want to check all threads. */
5694
5695static int
5696is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5697 ptid_t thread_ptid)
5698{
5699 if (ws->kind == TARGET_WAITKIND_FORKED
5700 || ws->kind == TARGET_WAITKIND_VFORKED)
5701 {
5702 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5703 return 1;
5704 }
5705
5706 return 0;
5707}
5708
5709/* Check whether EVENT is a fork event, and if it is, remove the
5710 fork child from the context list passed in DATA. */
5711
5712static int
5713remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5714 QUEUE_ITER (stop_reply_p) *iter,
5715 stop_reply_p event,
5716 void *data)
5717{
5718 struct queue_iter_param *param = data;
5719 struct threads_listing_context *context = param->input;
5720
5721 if (event->ws.kind == TARGET_WAITKIND_FORKED
5722 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5723 {
5724 threads_listing_context_remove (&event->ws, context);
5725 }
5726
5727 return 1;
5728}
5729
5730/* If CONTEXT contains any fork child threads that have not been
5731 reported yet, remove them from the CONTEXT list. If such a
5732 thread exists it is because we are stopped at a fork catchpoint
5733 and have not yet called follow_fork, which will set up the
5734 host-side data structures for the new process. */
5735
5736static void
5737remove_new_fork_children (struct threads_listing_context *context)
5738{
5739 struct thread_info * thread;
5740 int pid = -1;
5741 struct notif_client *notif = &notif_client_stop;
5742 struct queue_iter_param param;
5743
5744 /* For any threads stopped at a fork event, remove the corresponding
5745 fork child threads from the CONTEXT list. */
5746 ALL_NON_EXITED_THREADS (thread)
5747 {
5748 struct target_waitstatus *ws = &thread->pending_follow;
5749
5750 if (is_pending_fork_parent (ws, pid, thread->ptid))
5751 {
5752 threads_listing_context_remove (ws, context);
5753 }
5754 }
5755
5756 /* Check for any pending fork events (not reported or processed yet)
5757 in process PID and remove those fork child threads from the
5758 CONTEXT list as well. */
5759 remote_notif_get_pending_events (notif);
5760 param.input = context;
5761 param.output = NULL;
5762 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5763 remove_child_of_pending_fork, &param);
5764}
5765
f48ff2a7
YQ
5766/* Remove stop replies in the queue if its pid is equal to the given
5767 inferior's pid. */
722247f1
YQ
5768
5769static int
f48ff2a7
YQ
5770remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5771 QUEUE_ITER (stop_reply_p) *iter,
5772 stop_reply_p event,
5773 void *data)
722247f1
YQ
5774{
5775 struct queue_iter_param *param = data;
5776 struct inferior *inf = param->input;
5777
f48ff2a7 5778 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5779 {
5780 stop_reply_xfree (event);
5781 QUEUE_remove_elem (stop_reply_p, q, iter);
5782 }
5783
5784 return 1;
5785}
5786
f48ff2a7 5787/* Discard all pending stop replies of inferior INF. */
c906108c 5788
74531fed 5789static void
5f4cf0bb 5790discard_pending_stop_replies (struct inferior *inf)
c906108c 5791{
722247f1
YQ
5792 int i;
5793 struct queue_iter_param param;
f48ff2a7
YQ
5794 struct stop_reply *reply;
5795 struct remote_state *rs = get_remote_state ();
5796 struct remote_notif_state *rns = rs->notif_state;
5797
5798 /* This function can be notified when an inferior exists. When the
5799 target is not remote, the notification state is NULL. */
5800 if (rs->remote_desc == NULL)
5801 return;
5802
5803 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5804
74531fed 5805 /* Discard the in-flight notification. */
f48ff2a7 5806 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5807 {
722247f1 5808 stop_reply_xfree (reply);
f48ff2a7 5809 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5810 }
c906108c 5811
722247f1
YQ
5812 param.input = inf;
5813 param.output = NULL;
74531fed
PA
5814 /* Discard the stop replies we have already pulled with
5815 vStopped. */
722247f1 5816 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5817 remove_stop_reply_for_inferior, &param);
5818}
5819
bcc75809
YQ
5820/* If its remote state is equal to the given remote state,
5821 remove EVENT from the stop reply queue. */
5822
5823static int
5824remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5825 QUEUE_ITER (stop_reply_p) *iter,
5826 stop_reply_p event,
5827 void *data)
5828{
5829 struct queue_iter_param *param = data;
5830 struct remote_state *rs = param->input;
5831
5832 if (event->rs == rs)
5833 {
5834 stop_reply_xfree (event);
5835 QUEUE_remove_elem (stop_reply_p, q, iter);
5836 }
5837
5838 return 1;
5839}
5840
5841/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5842
5843static void
bcc75809 5844discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5845{
5846 struct queue_iter_param param;
5847
bcc75809 5848 param.input = rs;
f48ff2a7
YQ
5849 param.output = NULL;
5850 /* Discard the stop replies we have already pulled with
5851 vStopped. */
5852 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5853 remove_stop_reply_of_remote_state, &param);
722247f1 5854}
74531fed 5855
722247f1
YQ
5856/* A parameter to pass data in and out. */
5857
5858static int
5859remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5860 QUEUE_ITER (stop_reply_p) *iter,
5861 stop_reply_p event,
5862 void *data)
5863{
5864 struct queue_iter_param *param = data;
5865 ptid_t *ptid = param->input;
5866
5867 if (ptid_match (event->ptid, *ptid))
5868 {
5869 param->output = event;
5870 QUEUE_remove_elem (stop_reply_p, q, iter);
5871 return 0;
c8e38a49 5872 }
722247f1
YQ
5873
5874 return 1;
74531fed 5875}
43ff13b4 5876
722247f1
YQ
5877/* Remove the first reply in 'stop_reply_queue' which matches
5878 PTID. */
2e9f7625 5879
722247f1
YQ
5880static struct stop_reply *
5881remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5882{
722247f1
YQ
5883 struct queue_iter_param param;
5884
5885 param.input = &ptid;
5886 param.output = NULL;
5887
5888 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5889 remote_notif_remove_once_on_match, &param);
5890 if (notif_debug)
5891 fprintf_unfiltered (gdb_stdlog,
5892 "notif: discard queued event: 'Stop' in %s\n",
5893 target_pid_to_str (ptid));
a744cf53 5894
722247f1 5895 return param.output;
74531fed 5896}
75c99385 5897
74531fed
PA
5898/* Look for a queued stop reply belonging to PTID. If one is found,
5899 remove it from the queue, and return it. Returns NULL if none is
5900 found. If there are still queued events left to process, tell the
5901 event loop to get back to target_wait soon. */
e24a49d8 5902
74531fed
PA
5903static struct stop_reply *
5904queued_stop_reply (ptid_t ptid)
5905{
722247f1 5906 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5907
722247f1 5908 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5909 /* There's still at least an event left. */
5910 mark_async_event_handler (remote_async_inferior_event_token);
5911
722247f1 5912 return r;
74531fed
PA
5913}
5914
5915/* Push a fully parsed stop reply in the stop reply queue. Since we
5916 know that we now have at least one queued event left to pass to the
5917 core side, tell the event loop to get back to target_wait soon. */
5918
5919static void
5920push_stop_reply (struct stop_reply *new_event)
5921{
722247f1 5922 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5923
722247f1
YQ
5924 if (notif_debug)
5925 fprintf_unfiltered (gdb_stdlog,
5926 "notif: push 'Stop' %s to queue %d\n",
5927 target_pid_to_str (new_event->ptid),
5928 QUEUE_length (stop_reply_p,
5929 stop_reply_queue));
74531fed
PA
5930
5931 mark_async_event_handler (remote_async_inferior_event_token);
5932}
5933
722247f1
YQ
5934static int
5935stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5936 QUEUE_ITER (stop_reply_p) *iter,
5937 struct stop_reply *event,
5938 void *data)
5939{
5940 ptid_t *ptid = data;
5941
5942 return !(ptid_equal (*ptid, event->ptid)
5943 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5944}
5945
74531fed
PA
5946/* Returns true if we have a stop reply for PTID. */
5947
5948static int
5949peek_stop_reply (ptid_t ptid)
5950{
722247f1
YQ
5951 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5952 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5953}
5954
1f10ba14
PA
5955/* Skip PACKET until the next semi-colon (or end of string). */
5956
5957static char *
5958skip_to_semicolon (char *p)
5959{
5960 while (*p != '\0' && *p != ';')
5961 p++;
5962 return p;
5963}
5964
26d56a93
SL
5965/* Helper for remote_parse_stop_reply. Return nonzero if the substring
5966 starting with P and ending with PEND matches PREFIX. */
5967
5968static int
5969strprefix (const char *p, const char *pend, const char *prefix)
5970{
5971 for ( ; p < pend; p++, prefix++)
5972 if (*p != *prefix)
5973 return 0;
5974 return *prefix == '\0';
5975}
5976
74531fed
PA
5977/* Parse the stop reply in BUF. Either the function succeeds, and the
5978 result is stored in EVENT, or throws an error. */
5979
5980static void
5981remote_parse_stop_reply (char *buf, struct stop_reply *event)
5982{
5983 struct remote_arch_state *rsa = get_remote_arch_state ();
5984 ULONGEST addr;
5985 char *p;
5986
5987 event->ptid = null_ptid;
bcc75809 5988 event->rs = get_remote_state ();
74531fed
PA
5989 event->ws.kind = TARGET_WAITKIND_IGNORE;
5990 event->ws.value.integer = 0;
f7e6eed5 5991 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 5992 event->regcache = NULL;
dc146f7c 5993 event->core = -1;
74531fed
PA
5994
5995 switch (buf[0])
5996 {
5997 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5998 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5999 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6000 ss = signal number
6001 n... = register number
6002 r... = register contents
6003 */
6004
6005 p = &buf[3]; /* after Txx */
6006 while (*p)
6007 {
6008 char *p1;
cea39f65 6009 int fieldsize;
43ff13b4 6010
1f10ba14
PA
6011 p1 = strchr (p, ':');
6012 if (p1 == NULL)
6013 error (_("Malformed packet(a) (missing colon): %s\n\
6014Packet: '%s'\n"),
6015 p, buf);
6016 if (p == p1)
6017 error (_("Malformed packet(a) (missing register number): %s\n\
6018Packet: '%s'\n"),
6019 p, buf);
3c3bea1c 6020
1f10ba14
PA
6021 /* Some "registers" are actually extended stop information.
6022 Note if you're adding a new entry here: GDB 7.9 and
6023 earlier assume that all register "numbers" that start
6024 with an hex digit are real register numbers. Make sure
6025 the server only sends such a packet if it knows the
6026 client understands it. */
c8e38a49 6027
26d56a93 6028 if (strprefix (p, p1, "thread"))
1f10ba14 6029 event->ptid = read_ptid (++p1, &p);
26d56a93
SL
6030 else if (strprefix (p, p1, "watch")
6031 || strprefix (p, p1, "rwatch")
6032 || strprefix (p, p1, "awatch"))
cea39f65 6033 {
f7e6eed5 6034 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6035 p = unpack_varlen_hex (++p1, &addr);
6036 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6037 }
26d56a93 6038 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6039 {
6040 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6041
6042 /* Make sure the stub doesn't forget to indicate support
6043 with qSupported. */
6044 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6045 error (_("Unexpected swbreak stop reason"));
6046
6047 /* The value part is documented as "must be empty",
6048 though we ignore it, in case we ever decide to make
6049 use of it in a backward compatible way. */
6050 p = skip_to_semicolon (p1 + 1);
6051 }
26d56a93 6052 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6053 {
6054 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6055
6056 /* Make sure the stub doesn't forget to indicate support
6057 with qSupported. */
6058 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6059 error (_("Unexpected hwbreak stop reason"));
6060
6061 /* See above. */
6062 p = skip_to_semicolon (p1 + 1);
6063 }
26d56a93 6064 else if (strprefix (p, p1, "library"))
cea39f65 6065 {
1f10ba14
PA
6066 event->ws.kind = TARGET_WAITKIND_LOADED;
6067 p = skip_to_semicolon (p1 + 1);
6068 }
26d56a93 6069 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6070 {
6071 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6072 /* p1 will indicate "begin" or "end", but it makes
6073 no difference for now, so ignore it. */
6074 p = skip_to_semicolon (p1 + 1);
6075 }
26d56a93 6076 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6077 {
6078 ULONGEST c;
a744cf53 6079
1f10ba14
PA
6080 p = unpack_varlen_hex (++p1, &c);
6081 event->core = c;
cea39f65 6082 }
26d56a93 6083 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6084 {
6085 event->ws.value.related_pid = read_ptid (++p1, &p);
6086 event->ws.kind = TARGET_WAITKIND_FORKED;
6087 }
26d56a93 6088 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6089 {
6090 event->ws.value.related_pid = read_ptid (++p1, &p);
6091 event->ws.kind = TARGET_WAITKIND_VFORKED;
6092 }
26d56a93 6093 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6094 {
6095 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6096 p = skip_to_semicolon (p1 + 1);
6097 }
cea39f65
MS
6098 else
6099 {
1f10ba14
PA
6100 ULONGEST pnum;
6101 char *p_temp;
6102
6103 /* Maybe a real ``P'' register number. */
6104 p_temp = unpack_varlen_hex (p, &pnum);
6105 /* If the first invalid character is the colon, we got a
6106 register number. Otherwise, it's an unknown stop
6107 reason. */
6108 if (p_temp == p1)
6109 {
6110 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6111 cached_reg_t cached_reg;
43ff13b4 6112
1f10ba14
PA
6113 if (reg == NULL)
6114 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6115Packet: '%s'\n"),
1f10ba14 6116 hex_string (pnum), p, buf);
c8e38a49 6117
1f10ba14 6118 cached_reg.num = reg->regnum;
4100683b 6119
1f10ba14
PA
6120 p = p1 + 1;
6121 fieldsize = hex2bin (p, cached_reg.data,
6122 register_size (target_gdbarch (),
6123 reg->regnum));
6124 p += 2 * fieldsize;
6125 if (fieldsize < register_size (target_gdbarch (),
6126 reg->regnum))
6127 warning (_("Remote reply is too short: %s"), buf);
74531fed 6128
1f10ba14
PA
6129 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6130 }
6131 else
6132 {
6133 /* Not a number. Silently skip unknown optional
6134 info. */
6135 p = skip_to_semicolon (p1 + 1);
6136 }
cea39f65 6137 }
c8e38a49 6138
cea39f65
MS
6139 if (*p != ';')
6140 error (_("Remote register badly formatted: %s\nhere: %s"),
6141 buf, p);
6142 ++p;
6143 }
5b5596ff
PA
6144
6145 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6146 break;
6147
c8e38a49
PA
6148 /* fall through */
6149 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6150 {
6151 int sig;
6152
6153 event->ws.kind = TARGET_WAITKIND_STOPPED;
6154 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6155 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6156 event->ws.value.sig = (enum gdb_signal) sig;
6157 else
6158 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6159 }
c8e38a49
PA
6160 break;
6161 case 'W': /* Target exited. */
6162 case 'X':
6163 {
6164 char *p;
6165 int pid;
6166 ULONGEST value;
82f73884 6167
c8e38a49
PA
6168 /* GDB used to accept only 2 hex chars here. Stubs should
6169 only send more if they detect GDB supports multi-process
6170 support. */
6171 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6172
c8e38a49
PA
6173 if (buf[0] == 'W')
6174 {
6175 /* The remote process exited. */
74531fed
PA
6176 event->ws.kind = TARGET_WAITKIND_EXITED;
6177 event->ws.value.integer = value;
c8e38a49
PA
6178 }
6179 else
6180 {
6181 /* The remote process exited with a signal. */
74531fed 6182 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6183 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6184 event->ws.value.sig = (enum gdb_signal) value;
6185 else
6186 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6187 }
82f73884 6188
c8e38a49
PA
6189 /* If no process is specified, assume inferior_ptid. */
6190 pid = ptid_get_pid (inferior_ptid);
6191 if (*p == '\0')
6192 ;
6193 else if (*p == ';')
6194 {
6195 p++;
6196
0b24eb2d 6197 if (*p == '\0')
82f73884 6198 ;
61012eef 6199 else if (startswith (p, "process:"))
82f73884 6200 {
c8e38a49 6201 ULONGEST upid;
a744cf53 6202
c8e38a49
PA
6203 p += sizeof ("process:") - 1;
6204 unpack_varlen_hex (p, &upid);
6205 pid = upid;
82f73884
PA
6206 }
6207 else
6208 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6209 }
c8e38a49
PA
6210 else
6211 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6212 event->ptid = pid_to_ptid (pid);
6213 }
6214 break;
6215 }
6216
6217 if (non_stop && ptid_equal (event->ptid, null_ptid))
6218 error (_("No process or thread specified in stop reply: %s"), buf);
6219}
6220
722247f1
YQ
6221/* When the stub wants to tell GDB about a new notification reply, it
6222 sends a notification (%Stop, for example). Those can come it at
6223 any time, hence, we have to make sure that any pending
6224 putpkt/getpkt sequence we're making is finished, before querying
6225 the stub for more events with the corresponding ack command
6226 (vStopped, for example). E.g., if we started a vStopped sequence
6227 immediately upon receiving the notification, something like this
6228 could happen:
74531fed
PA
6229
6230 1.1) --> Hg 1
6231 1.2) <-- OK
6232 1.3) --> g
6233 1.4) <-- %Stop
6234 1.5) --> vStopped
6235 1.6) <-- (registers reply to step #1.3)
6236
6237 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6238 query.
6239
796cb314 6240 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6241 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6242 doing whatever we were doing:
6243
6244 2.1) --> Hg 1
6245 2.2) <-- OK
6246 2.3) --> g
6247 2.4) <-- %Stop
6248 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6249 2.5) <-- (registers reply to step #2.3)
6250
6251 Eventualy after step #2.5, we return to the event loop, which
6252 notices there's an event on the
6253 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6254 associated callback --- the function below. At this point, we're
6255 always safe to start a vStopped sequence. :
6256
6257 2.6) --> vStopped
6258 2.7) <-- T05 thread:2
6259 2.8) --> vStopped
6260 2.9) --> OK
6261*/
6262
722247f1
YQ
6263void
6264remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6265{
6266 struct remote_state *rs = get_remote_state ();
74531fed 6267
f48ff2a7 6268 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6269 {
722247f1
YQ
6270 if (notif_debug)
6271 fprintf_unfiltered (gdb_stdlog,
6272 "notif: process: '%s' ack pending event\n",
6273 nc->name);
74531fed 6274
722247f1 6275 /* acknowledge */
f48ff2a7
YQ
6276 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6277 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6278
6279 while (1)
6280 {
6281 getpkt (&rs->buf, &rs->buf_size, 0);
6282 if (strcmp (rs->buf, "OK") == 0)
6283 break;
6284 else
722247f1 6285 remote_notif_ack (nc, rs->buf);
74531fed
PA
6286 }
6287 }
722247f1
YQ
6288 else
6289 {
6290 if (notif_debug)
6291 fprintf_unfiltered (gdb_stdlog,
6292 "notif: process: '%s' no pending reply\n",
6293 nc->name);
6294 }
74531fed
PA
6295}
6296
74531fed
PA
6297/* Called when it is decided that STOP_REPLY holds the info of the
6298 event that is to be returned to the core. This function always
6299 destroys STOP_REPLY. */
6300
6301static ptid_t
6302process_stop_reply (struct stop_reply *stop_reply,
6303 struct target_waitstatus *status)
6304{
6305 ptid_t ptid;
6306
6307 *status = stop_reply->ws;
6308 ptid = stop_reply->ptid;
6309
6310 /* If no thread/process was reported by the stub, assume the current
6311 inferior. */
6312 if (ptid_equal (ptid, null_ptid))
6313 ptid = inferior_ptid;
6314
5f3563ea
PA
6315 if (status->kind != TARGET_WAITKIND_EXITED
6316 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 6317 {
ee154bee
TT
6318 struct remote_state *rs = get_remote_state ();
6319
5f3563ea
PA
6320 /* Expedited registers. */
6321 if (stop_reply->regcache)
6322 {
217f1f79 6323 struct regcache *regcache
f5656ead 6324 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6325 cached_reg_t *reg;
6326 int ix;
6327
6328 for (ix = 0;
6329 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6330 ix++)
217f1f79 6331 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6332 VEC_free (cached_reg_t, stop_reply->regcache);
6333 }
74531fed 6334
f7e6eed5 6335 rs->stop_reason = stop_reply->stop_reason;
ee154bee 6336 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
6337
6338 remote_notice_new_inferior (ptid, 0);
dc146f7c 6339 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
6340 }
6341
74531fed
PA
6342 stop_reply_xfree (stop_reply);
6343 return ptid;
6344}
6345
6346/* The non-stop mode version of target_wait. */
6347
6348static ptid_t
47608cb1 6349remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6350{
6351 struct remote_state *rs = get_remote_state ();
74531fed
PA
6352 struct stop_reply *stop_reply;
6353 int ret;
fee9eda9 6354 int is_notif = 0;
74531fed
PA
6355
6356 /* If in non-stop mode, get out of getpkt even if a
6357 notification is received. */
6358
6359 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6360 0 /* forever */, &is_notif);
74531fed
PA
6361 while (1)
6362 {
fee9eda9 6363 if (ret != -1 && !is_notif)
74531fed
PA
6364 switch (rs->buf[0])
6365 {
6366 case 'E': /* Error of some sort. */
6367 /* We're out of sync with the target now. Did it continue
6368 or not? We can't tell which thread it was in non-stop,
6369 so just ignore this. */
6370 warning (_("Remote failure reply: %s"), rs->buf);
6371 break;
6372 case 'O': /* Console output. */
6373 remote_console_output (rs->buf + 1);
6374 break;
6375 default:
6376 warning (_("Invalid remote reply: %s"), rs->buf);
6377 break;
6378 }
6379
6380 /* Acknowledge a pending stop reply that may have arrived in the
6381 mean time. */
f48ff2a7 6382 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6383 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6384
6385 /* If indeed we noticed a stop reply, we're done. */
6386 stop_reply = queued_stop_reply (ptid);
6387 if (stop_reply != NULL)
6388 return process_stop_reply (stop_reply, status);
6389
47608cb1 6390 /* Still no event. If we're just polling for an event, then
74531fed 6391 return to the event loop. */
47608cb1 6392 if (options & TARGET_WNOHANG)
74531fed
PA
6393 {
6394 status->kind = TARGET_WAITKIND_IGNORE;
6395 return minus_one_ptid;
6396 }
6397
47608cb1 6398 /* Otherwise do a blocking wait. */
74531fed 6399 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6400 1 /* forever */, &is_notif);
74531fed
PA
6401 }
6402}
6403
6404/* Wait until the remote machine stops, then return, storing status in
6405 STATUS just as `wait' would. */
6406
6407static ptid_t
47608cb1 6408remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6409{
6410 struct remote_state *rs = get_remote_state ();
74531fed 6411 ptid_t event_ptid = null_ptid;
cea39f65 6412 char *buf;
74531fed
PA
6413 struct stop_reply *stop_reply;
6414
47608cb1
PA
6415 again:
6416
74531fed
PA
6417 status->kind = TARGET_WAITKIND_IGNORE;
6418 status->value.integer = 0;
6419
6420 stop_reply = queued_stop_reply (ptid);
6421 if (stop_reply != NULL)
6422 return process_stop_reply (stop_reply, status);
6423
6424 if (rs->cached_wait_status)
6425 /* Use the cached wait status, but only once. */
6426 rs->cached_wait_status = 0;
6427 else
6428 {
6429 int ret;
722247f1 6430 int is_notif;
567420d1
PA
6431 int forever = ((options & TARGET_WNOHANG) == 0
6432 && wait_forever_enabled_p);
6433
6434 if (!rs->waiting_for_stop_reply)
6435 {
6436 status->kind = TARGET_WAITKIND_NO_RESUMED;
6437 return minus_one_ptid;
6438 }
74531fed
PA
6439
6440 if (!target_is_async_p ())
6441 {
934b9bac 6442 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6443 /* If the user hit C-c before this packet, or between packets,
6444 pretend that it was hit right here. */
522002f9 6445 if (check_quit_flag ())
74531fed 6446 {
522002f9 6447 clear_quit_flag ();
934b9bac 6448 sync_remote_interrupt (SIGINT);
74531fed
PA
6449 }
6450 }
6451
6452 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6453 _never_ wait for ever -> test on target_is_async_p().
6454 However, before we do that we need to ensure that the caller
6455 knows how to take the target into/out of async mode. */
722247f1 6456 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6457 forever, &is_notif);
722247f1 6458
5e1b953b
SDJ
6459 if (!target_is_async_p ())
6460 signal (SIGINT, ofunc);
6461
722247f1
YQ
6462 /* GDB gets a notification. Return to core as this event is
6463 not interesting. */
6464 if (ret != -1 && is_notif)
6465 return minus_one_ptid;
567420d1
PA
6466
6467 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6468 return minus_one_ptid;
74531fed
PA
6469 }
6470
6471 buf = rs->buf;
6472
f7e6eed5 6473 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
6474
6475 /* We got something. */
6476 rs->waiting_for_stop_reply = 0;
6477
3a29589a
DJ
6478 /* Assume that the target has acknowledged Ctrl-C unless we receive
6479 an 'F' or 'O' packet. */
6480 if (buf[0] != 'F' && buf[0] != 'O')
6481 rs->ctrlc_pending_p = 0;
6482
74531fed
PA
6483 switch (buf[0])
6484 {
6485 case 'E': /* Error of some sort. */
6486 /* We're out of sync with the target now. Did it continue or
6487 not? Not is more likely, so report a stop. */
6488 warning (_("Remote failure reply: %s"), buf);
6489 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6490 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6491 break;
6492 case 'F': /* File-I/O request. */
3a29589a
DJ
6493 remote_fileio_request (buf, rs->ctrlc_pending_p);
6494 rs->ctrlc_pending_p = 0;
74531fed
PA
6495 break;
6496 case 'T': case 'S': case 'X': case 'W':
6497 {
722247f1
YQ
6498 struct stop_reply *stop_reply
6499 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6500 rs->buf);
74531fed 6501
74531fed 6502 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6503 break;
6504 }
6505 case 'O': /* Console output. */
6506 remote_console_output (buf + 1);
e24a49d8 6507
c8e38a49
PA
6508 /* The target didn't really stop; keep waiting. */
6509 rs->waiting_for_stop_reply = 1;
e24a49d8 6510
c8e38a49
PA
6511 break;
6512 case '\0':
b73be471 6513 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6514 {
6515 /* Zero length reply means that we tried 'S' or 'C' and the
6516 remote system doesn't support it. */
6517 target_terminal_ours_for_output ();
6518 printf_filtered
6519 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6520 gdb_signal_to_name (rs->last_sent_signal));
6521 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6522 target_terminal_inferior ();
6523
280ceea3 6524 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6525 putpkt ((char *) buf);
6526
6527 /* We just told the target to resume, so a stop reply is in
6528 order. */
e24a49d8 6529 rs->waiting_for_stop_reply = 1;
c8e38a49 6530 break;
43ff13b4 6531 }
c8e38a49
PA
6532 /* else fallthrough */
6533 default:
6534 warning (_("Invalid remote reply: %s"), buf);
6535 /* Keep waiting. */
6536 rs->waiting_for_stop_reply = 1;
6537 break;
43ff13b4 6538 }
c8e38a49 6539
c8e38a49 6540 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6541 {
6542 /* Nothing interesting happened. If we're doing a non-blocking
6543 poll, we're done. Otherwise, go back to waiting. */
6544 if (options & TARGET_WNOHANG)
6545 return minus_one_ptid;
6546 else
6547 goto again;
6548 }
74531fed
PA
6549 else if (status->kind != TARGET_WAITKIND_EXITED
6550 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6551 {
6552 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6553 record_currthread (rs, event_ptid);
82f73884
PA
6554 else
6555 event_ptid = inferior_ptid;
43ff13b4 6556 }
74531fed
PA
6557 else
6558 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6559 record_currthread (rs, minus_one_ptid);
79d7f229 6560
82f73884 6561 return event_ptid;
43ff13b4
JM
6562}
6563
74531fed
PA
6564/* Wait until the remote machine stops, then return, storing status in
6565 STATUS just as `wait' would. */
6566
c8e38a49 6567static ptid_t
117de6a9 6568remote_wait (struct target_ops *ops,
47608cb1 6569 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6570{
6571 ptid_t event_ptid;
6572
74531fed 6573 if (non_stop)
47608cb1 6574 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6575 else
47608cb1 6576 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6577
d9d41e78 6578 if (target_is_async_p ())
c8e38a49 6579 {
74531fed
PA
6580 /* If there are are events left in the queue tell the event loop
6581 to return here. */
722247f1 6582 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6583 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6584 }
c8e38a49
PA
6585
6586 return event_ptid;
6587}
6588
74ca34ce 6589/* Fetch a single register using a 'p' packet. */
c906108c 6590
b96ec7ac 6591static int
56be3814 6592fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6593{
6594 struct remote_state *rs = get_remote_state ();
2e9f7625 6595 char *buf, *p;
b96ec7ac
AC
6596 char regp[MAX_REGISTER_SIZE];
6597 int i;
6598
4082afcc 6599 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6600 return 0;
6601
6602 if (reg->pnum == -1)
6603 return 0;
6604
2e9f7625 6605 p = rs->buf;
fcad0fa4 6606 *p++ = 'p';
74ca34ce 6607 p += hexnumstr (p, reg->pnum);
fcad0fa4 6608 *p++ = '\0';
1f4437a4
MS
6609 putpkt (rs->buf);
6610 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6611
2e9f7625
DJ
6612 buf = rs->buf;
6613
74ca34ce
DJ
6614 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6615 {
6616 case PACKET_OK:
6617 break;
6618 case PACKET_UNKNOWN:
6619 return 0;
6620 case PACKET_ERROR:
27a9c0bf
MS
6621 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6622 gdbarch_register_name (get_regcache_arch (regcache),
6623 reg->regnum),
6624 buf);
74ca34ce 6625 }
3f9a994c
JB
6626
6627 /* If this register is unfetchable, tell the regcache. */
6628 if (buf[0] == 'x')
8480adf2 6629 {
56be3814 6630 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6631 return 1;
b96ec7ac 6632 }
b96ec7ac 6633
3f9a994c
JB
6634 /* Otherwise, parse and supply the value. */
6635 p = buf;
6636 i = 0;
6637 while (p[0] != 0)
6638 {
6639 if (p[1] == 0)
74ca34ce 6640 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6641
6642 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6643 p += 2;
6644 }
56be3814 6645 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6646 return 1;
b96ec7ac
AC
6647}
6648
74ca34ce
DJ
6649/* Fetch the registers included in the target's 'g' packet. */
6650
29709017
DJ
6651static int
6652send_g_packet (void)
c906108c 6653{
d01949b6 6654 struct remote_state *rs = get_remote_state ();
cea39f65 6655 int buf_len;
c906108c 6656
bba74b36 6657 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6658 remote_send (&rs->buf, &rs->buf_size);
c906108c 6659
29709017
DJ
6660 /* We can get out of synch in various cases. If the first character
6661 in the buffer is not a hex character, assume that has happened
6662 and try to fetch another packet to read. */
6663 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6664 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6665 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6666 && rs->buf[0] != 'x') /* New: unavailable register value. */
6667 {
6668 if (remote_debug)
6669 fprintf_unfiltered (gdb_stdlog,
6670 "Bad register packet; fetching a new packet\n");
6671 getpkt (&rs->buf, &rs->buf_size, 0);
6672 }
6673
74ca34ce
DJ
6674 buf_len = strlen (rs->buf);
6675
6676 /* Sanity check the received packet. */
6677 if (buf_len % 2 != 0)
6678 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6679
6680 return buf_len / 2;
6681}
6682
6683static void
56be3814 6684process_g_packet (struct regcache *regcache)
29709017 6685{
4a22f64d 6686 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6687 struct remote_state *rs = get_remote_state ();
6688 struct remote_arch_state *rsa = get_remote_arch_state ();
6689 int i, buf_len;
6690 char *p;
6691 char *regs;
6692
6693 buf_len = strlen (rs->buf);
6694
6695 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6696 if (buf_len > 2 * rsa->sizeof_g_packet)
6697 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6698
6699 /* Save the size of the packet sent to us by the target. It is used
6700 as a heuristic when determining the max size of packets that the
6701 target can safely receive. */
6702 if (rsa->actual_register_packet_size == 0)
6703 rsa->actual_register_packet_size = buf_len;
6704
6705 /* If this is smaller than we guessed the 'g' packet would be,
6706 update our records. A 'g' reply that doesn't include a register's
6707 value implies either that the register is not available, or that
6708 the 'p' packet must be used. */
6709 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6710 {
74ca34ce
DJ
6711 rsa->sizeof_g_packet = buf_len / 2;
6712
4a22f64d 6713 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6714 {
74ca34ce
DJ
6715 if (rsa->regs[i].pnum == -1)
6716 continue;
6717
6718 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6719 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6720 else
74ca34ce 6721 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6722 }
74ca34ce 6723 }
b323314b 6724
74ca34ce 6725 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6726
6727 /* Unimplemented registers read as all bits zero. */
ea9c271d 6728 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6729
c906108c
SS
6730 /* Reply describes registers byte by byte, each byte encoded as two
6731 hex characters. Suck them all up, then supply them to the
6732 register cacheing/storage mechanism. */
6733
74ca34ce 6734 p = rs->buf;
ea9c271d 6735 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6736 {
74ca34ce
DJ
6737 if (p[0] == 0 || p[1] == 0)
6738 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6739 internal_error (__FILE__, __LINE__,
9b20d036 6740 _("unexpected end of 'g' packet reply"));
74ca34ce 6741
c906108c 6742 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6743 regs[i] = 0; /* 'x' */
c906108c
SS
6744 else
6745 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6746 p += 2;
6747 }
6748
a744cf53
MS
6749 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6750 {
6751 struct packet_reg *r = &rsa->regs[i];
6752
6753 if (r->in_g_packet)
6754 {
6755 if (r->offset * 2 >= strlen (rs->buf))
6756 /* This shouldn't happen - we adjusted in_g_packet above. */
6757 internal_error (__FILE__, __LINE__,
9b20d036 6758 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6759 else if (rs->buf[r->offset * 2] == 'x')
6760 {
6761 gdb_assert (r->offset * 2 < strlen (rs->buf));
6762 /* The register isn't available, mark it as such (at
6763 the same time setting the value to zero). */
6764 regcache_raw_supply (regcache, r->regnum, NULL);
6765 }
6766 else
6767 regcache_raw_supply (regcache, r->regnum,
6768 regs + r->offset);
6769 }
6770 }
c906108c
SS
6771}
6772
29709017 6773static void
56be3814 6774fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6775{
6776 send_g_packet ();
56be3814 6777 process_g_packet (regcache);
29709017
DJ
6778}
6779
e6e4e701
PA
6780/* Make the remote selected traceframe match GDB's selected
6781 traceframe. */
6782
6783static void
6784set_remote_traceframe (void)
6785{
6786 int newnum;
262e1174 6787 struct remote_state *rs = get_remote_state ();
e6e4e701 6788
262e1174 6789 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6790 return;
6791
6792 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6793 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6794
6795 newnum = target_trace_find (tfind_number,
6796 get_traceframe_number (), 0, 0, NULL);
6797
6798 /* Should not happen. If it does, all bets are off. */
6799 if (newnum != get_traceframe_number ())
6800 warning (_("could not set remote traceframe"));
6801}
6802
74ca34ce 6803static void
28439f5e
PA
6804remote_fetch_registers (struct target_ops *ops,
6805 struct regcache *regcache, int regnum)
74ca34ce 6806{
74ca34ce
DJ
6807 struct remote_arch_state *rsa = get_remote_arch_state ();
6808 int i;
6809
e6e4e701 6810 set_remote_traceframe ();
79d7f229 6811 set_general_thread (inferior_ptid);
74ca34ce
DJ
6812
6813 if (regnum >= 0)
6814 {
6815 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6816
74ca34ce
DJ
6817 gdb_assert (reg != NULL);
6818
6819 /* If this register might be in the 'g' packet, try that first -
6820 we are likely to read more than one register. If this is the
6821 first 'g' packet, we might be overly optimistic about its
6822 contents, so fall back to 'p'. */
6823 if (reg->in_g_packet)
6824 {
56be3814 6825 fetch_registers_using_g (regcache);
74ca34ce
DJ
6826 if (reg->in_g_packet)
6827 return;
6828 }
6829
56be3814 6830 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6831 return;
6832
6833 /* This register is not available. */
56be3814 6834 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6835
6836 return;
6837 }
6838
56be3814 6839 fetch_registers_using_g (regcache);
74ca34ce 6840
4a22f64d 6841 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6842 if (!rsa->regs[i].in_g_packet)
56be3814 6843 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6844 {
6845 /* This register is not available. */
56be3814 6846 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6847 }
6848}
6849
c906108c
SS
6850/* Prepare to store registers. Since we may send them all (using a
6851 'G' request), we have to read out the ones we don't want to change
6852 first. */
6853
c5aa993b 6854static void
f32dbf8c 6855remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6856{
ea9c271d 6857 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6858 int i;
cfd77fa1 6859 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6860
c906108c 6861 /* Make sure the entire registers array is valid. */
4082afcc 6862 switch (packet_support (PACKET_P))
5a2468f5
JM
6863 {
6864 case PACKET_DISABLE:
6865 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6866 /* Make sure all the necessary registers are cached. */
4a22f64d 6867 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6868 if (rsa->regs[i].in_g_packet)
316f2060 6869 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6870 break;
6871 case PACKET_ENABLE:
6872 break;
6873 }
6874}
6875
ad10f812 6876/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6877 packet was not recognized. */
5a2468f5
JM
6878
6879static int
1f4437a4
MS
6880store_register_using_P (const struct regcache *regcache,
6881 struct packet_reg *reg)
5a2468f5 6882{
4a22f64d 6883 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6884 struct remote_state *rs = get_remote_state ();
5a2468f5 6885 /* Try storing a single register. */
6d820c5c 6886 char *buf = rs->buf;
cfd77fa1 6887 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6888 char *p;
5a2468f5 6889
4082afcc 6890 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6891 return 0;
6892
6893 if (reg->pnum == -1)
6894 return 0;
6895
ea9c271d 6896 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6897 p = buf + strlen (buf);
56be3814 6898 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6899 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6900 putpkt (rs->buf);
6901 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6902
74ca34ce
DJ
6903 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6904 {
6905 case PACKET_OK:
6906 return 1;
6907 case PACKET_ERROR:
27a9c0bf
MS
6908 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6909 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6910 case PACKET_UNKNOWN:
6911 return 0;
6912 default:
6913 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6914 }
c906108c
SS
6915}
6916
23860348
MS
6917/* Store register REGNUM, or all registers if REGNUM == -1, from the
6918 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6919
6920static void
56be3814 6921store_registers_using_G (const struct regcache *regcache)
c906108c 6922{
d01949b6 6923 struct remote_state *rs = get_remote_state ();
ea9c271d 6924 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6925 gdb_byte *regs;
c906108c
SS
6926 char *p;
6927
193cb69f
AC
6928 /* Extract all the registers in the regcache copying them into a
6929 local buffer. */
6930 {
b323314b 6931 int i;
a744cf53 6932
ea9c271d
DJ
6933 regs = alloca (rsa->sizeof_g_packet);
6934 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6935 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6936 {
ea9c271d 6937 struct packet_reg *r = &rsa->regs[i];
a744cf53 6938
b323314b 6939 if (r->in_g_packet)
56be3814 6940 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6941 }
6942 }
c906108c
SS
6943
6944 /* Command describes registers byte by byte,
6945 each byte encoded as two hex characters. */
6d820c5c 6946 p = rs->buf;
193cb69f 6947 *p++ = 'G';
74ca34ce
DJ
6948 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6949 updated. */
6950 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6951 putpkt (rs->buf);
6952 getpkt (&rs->buf, &rs->buf_size, 0);
6953 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6954 error (_("Could not write registers; remote failure reply '%s'"),
6955 rs->buf);
c906108c 6956}
74ca34ce
DJ
6957
6958/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6959 of the register cache buffer. FIXME: ignores errors. */
6960
6961static void
28439f5e
PA
6962remote_store_registers (struct target_ops *ops,
6963 struct regcache *regcache, int regnum)
74ca34ce 6964{
74ca34ce
DJ
6965 struct remote_arch_state *rsa = get_remote_arch_state ();
6966 int i;
6967
e6e4e701 6968 set_remote_traceframe ();
79d7f229 6969 set_general_thread (inferior_ptid);
74ca34ce
DJ
6970
6971 if (regnum >= 0)
6972 {
6973 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6974
74ca34ce
DJ
6975 gdb_assert (reg != NULL);
6976
6977 /* Always prefer to store registers using the 'P' packet if
6978 possible; we often change only a small number of registers.
6979 Sometimes we change a larger number; we'd need help from a
6980 higher layer to know to use 'G'. */
56be3814 6981 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6982 return;
6983
6984 /* For now, don't complain if we have no way to write the
6985 register. GDB loses track of unavailable registers too
6986 easily. Some day, this may be an error. We don't have
0df8b418 6987 any way to read the register, either... */
74ca34ce
DJ
6988 if (!reg->in_g_packet)
6989 return;
6990
56be3814 6991 store_registers_using_G (regcache);
74ca34ce
DJ
6992 return;
6993 }
6994
56be3814 6995 store_registers_using_G (regcache);
74ca34ce 6996
4a22f64d 6997 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6998 if (!rsa->regs[i].in_g_packet)
56be3814 6999 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7000 /* See above for why we do not issue an error here. */
7001 continue;
7002}
c906108c
SS
7003\f
7004
7005/* Return the number of hex digits in num. */
7006
7007static int
fba45db2 7008hexnumlen (ULONGEST num)
c906108c
SS
7009{
7010 int i;
7011
7012 for (i = 0; num != 0; i++)
7013 num >>= 4;
7014
7015 return max (i, 1);
7016}
7017
2df3850c 7018/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7019
7020static int
fba45db2 7021hexnumstr (char *buf, ULONGEST num)
c906108c 7022{
c906108c 7023 int len = hexnumlen (num);
a744cf53 7024
2df3850c
JM
7025 return hexnumnstr (buf, num, len);
7026}
7027
c906108c 7028
2df3850c 7029/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7030
2df3850c 7031static int
fba45db2 7032hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7033{
7034 int i;
7035
7036 buf[width] = '\0';
7037
7038 for (i = width - 1; i >= 0; i--)
c906108c 7039 {
c5aa993b 7040 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7041 num >>= 4;
7042 }
7043
2df3850c 7044 return width;
c906108c
SS
7045}
7046
23860348 7047/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7048
7049static CORE_ADDR
fba45db2 7050remote_address_masked (CORE_ADDR addr)
c906108c 7051{
883b9c6c 7052 unsigned int address_size = remote_address_size;
a744cf53 7053
911c95a5
UW
7054 /* If "remoteaddresssize" was not set, default to target address size. */
7055 if (!address_size)
f5656ead 7056 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7057
7058 if (address_size > 0
7059 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7060 {
7061 /* Only create a mask when that mask can safely be constructed
23860348 7062 in a ULONGEST variable. */
c906108c 7063 ULONGEST mask = 1;
a744cf53 7064
911c95a5 7065 mask = (mask << address_size) - 1;
c906108c
SS
7066 addr &= mask;
7067 }
7068 return addr;
7069}
7070
7071/* Determine whether the remote target supports binary downloading.
7072 This is accomplished by sending a no-op memory write of zero length
7073 to the target at the specified address. It does not suffice to send
23860348
MS
7074 the whole packet, since many stubs strip the eighth bit and
7075 subsequently compute a wrong checksum, which causes real havoc with
7076 remote_write_bytes.
7a292a7a 7077
96baa820 7078 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7079 clean. In cases like this, the user should clear "remote
23860348 7080 X-packet". */
96baa820 7081
c906108c 7082static void
fba45db2 7083check_binary_download (CORE_ADDR addr)
c906108c 7084{
d01949b6 7085 struct remote_state *rs = get_remote_state ();
24b06219 7086
4082afcc 7087 switch (packet_support (PACKET_X))
c906108c 7088 {
96baa820
JM
7089 case PACKET_DISABLE:
7090 break;
7091 case PACKET_ENABLE:
7092 break;
7093 case PACKET_SUPPORT_UNKNOWN:
7094 {
96baa820 7095 char *p;
802188a7 7096
2e9f7625 7097 p = rs->buf;
96baa820
JM
7098 *p++ = 'X';
7099 p += hexnumstr (p, (ULONGEST) addr);
7100 *p++ = ',';
7101 p += hexnumstr (p, (ULONGEST) 0);
7102 *p++ = ':';
7103 *p = '\0';
802188a7 7104
2e9f7625 7105 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7106 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7107
2e9f7625 7108 if (rs->buf[0] == '\0')
96baa820
JM
7109 {
7110 if (remote_debug)
7111 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7112 "binary downloading NOT "
7113 "supported by target\n");
444abaca 7114 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7115 }
7116 else
7117 {
7118 if (remote_debug)
7119 fprintf_unfiltered (gdb_stdlog,
64b9b334 7120 "binary downloading supported by target\n");
444abaca 7121 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7122 }
7123 break;
7124 }
c906108c
SS
7125 }
7126}
7127
124e13d9
SM
7128/* Helper function to resize the payload in order to try to get a good
7129 alignment. We try to write an amount of data such that the next write will
7130 start on an address aligned on REMOTE_ALIGN_WRITES. */
7131
7132static int
7133align_for_efficient_write (int todo, CORE_ADDR memaddr)
7134{
7135 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7136}
7137
c906108c
SS
7138/* Write memory data directly to the remote machine.
7139 This does not inform the data cache; the data cache uses this.
a76d924d 7140 HEADER is the starting part of the packet.
c906108c
SS
7141 MEMADDR is the address in the remote memory space.
7142 MYADDR is the address of the buffer in our space.
124e13d9
SM
7143 LEN_UNITS is the number of addressable units to write.
7144 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7145 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7146 should send data as binary ('X'), or hex-encoded ('M').
7147
7148 The function creates packet of the form
7149 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7150
124e13d9 7151 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7152
7153 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7154 are omitted.
7155
9b409511 7156 Return the transferred status, error or OK (an
124e13d9
SM
7157 'enum target_xfer_status' value). Save the number of addressable units
7158 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7159
7160 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7161 exchange between gdb and the stub could look like (?? in place of the
7162 checksum):
7163
7164 -> $m1000,4#??
7165 <- aaaabbbbccccdddd
7166
7167 -> $M1000,3:eeeeffffeeee#??
7168 <- OK
7169
7170 -> $m1000,4#??
7171 <- eeeeffffeeeedddd */
c906108c 7172
9b409511 7173static enum target_xfer_status
a76d924d 7174remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7175 const gdb_byte *myaddr, ULONGEST len_units,
7176 int unit_size, ULONGEST *xfered_len_units,
7177 char packet_format, int use_length)
c906108c 7178{
6d820c5c 7179 struct remote_state *rs = get_remote_state ();
cfd77fa1 7180 char *p;
a76d924d
DJ
7181 char *plen = NULL;
7182 int plenlen = 0;
124e13d9
SM
7183 int todo_units;
7184 int units_written;
7185 int payload_capacity_bytes;
7186 int payload_length_bytes;
a76d924d
DJ
7187
7188 if (packet_format != 'X' && packet_format != 'M')
7189 internal_error (__FILE__, __LINE__,
9b20d036 7190 _("remote_write_bytes_aux: bad packet format"));
c906108c 7191
124e13d9 7192 if (len_units == 0)
9b409511 7193 return TARGET_XFER_EOF;
b2182ed2 7194
124e13d9 7195 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7196
6d820c5c
DJ
7197 /* The packet buffer will be large enough for the payload;
7198 get_memory_packet_size ensures this. */
a76d924d 7199 rs->buf[0] = '\0';
c906108c 7200
a257b5bb 7201 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7202 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7203
124e13d9 7204 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7205 if (!use_length)
0df8b418 7206 /* The comma won't be used. */
124e13d9
SM
7207 payload_capacity_bytes += 1;
7208 payload_capacity_bytes -= strlen (header);
7209 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7210
a76d924d 7211 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7212
a76d924d
DJ
7213 strcat (rs->buf, header);
7214 p = rs->buf + strlen (header);
7215
7216 /* Compute a best guess of the number of bytes actually transfered. */
7217 if (packet_format == 'X')
c906108c 7218 {
23860348 7219 /* Best guess at number of bytes that will fit. */
124e13d9 7220 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7221 if (use_length)
124e13d9
SM
7222 payload_capacity_bytes -= hexnumlen (todo_units);
7223 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7224 }
7225 else
7226 {
124e13d9
SM
7227 /* Number of bytes that will fit. */
7228 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7229 if (use_length)
124e13d9
SM
7230 payload_capacity_bytes -= hexnumlen (todo_units);
7231 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7232 }
a76d924d 7233
124e13d9 7234 if (todo_units <= 0)
3de11b2e 7235 internal_error (__FILE__, __LINE__,
405f8e94 7236 _("minimum packet size too small to write data"));
802188a7 7237
6765f3e5
DJ
7238 /* If we already need another packet, then try to align the end
7239 of this packet to a useful boundary. */
124e13d9
SM
7240 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7241 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7242
a257b5bb 7243 /* Append "<memaddr>". */
917317f4
JM
7244 memaddr = remote_address_masked (memaddr);
7245 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7246
a76d924d
DJ
7247 if (use_length)
7248 {
7249 /* Append ",". */
7250 *p++ = ',';
802188a7 7251
124e13d9
SM
7252 /* Append the length and retain its location and size. It may need to be
7253 adjusted once the packet body has been created. */
a76d924d 7254 plen = p;
124e13d9 7255 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7256 p += plenlen;
7257 }
a257b5bb
AC
7258
7259 /* Append ":". */
917317f4
JM
7260 *p++ = ':';
7261 *p = '\0';
802188a7 7262
a257b5bb 7263 /* Append the packet body. */
a76d924d 7264 if (packet_format == 'X')
917317f4 7265 {
917317f4
JM
7266 /* Binary mode. Send target system values byte by byte, in
7267 increasing byte addresses. Only escape certain critical
7268 characters. */
124e13d9
SM
7269 payload_length_bytes =
7270 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7271 &units_written, payload_capacity_bytes);
6765f3e5 7272
124e13d9 7273 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7274 a second try to keep the end of the packet aligned. Don't do
7275 this if the packet is tiny. */
124e13d9 7276 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7277 {
124e13d9
SM
7278 int new_todo_units;
7279
7280 new_todo_units = align_for_efficient_write (units_written, memaddr);
7281
7282 if (new_todo_units != units_written)
7283 payload_length_bytes =
7284 remote_escape_output (myaddr, new_todo_units, unit_size,
7285 (gdb_byte *) p, &units_written,
7286 payload_capacity_bytes);
6765f3e5
DJ
7287 }
7288
124e13d9
SM
7289 p += payload_length_bytes;
7290 if (use_length && units_written < todo_units)
c906108c 7291 {
802188a7 7292 /* Escape chars have filled up the buffer prematurely,
124e13d9 7293 and we have actually sent fewer units than planned.
917317f4
JM
7294 Fix-up the length field of the packet. Use the same
7295 number of characters as before. */
124e13d9
SM
7296 plen += hexnumnstr (plen, (ULONGEST) units_written,
7297 plenlen);
917317f4 7298 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7299 }
a76d924d
DJ
7300 }
7301 else
7302 {
917317f4
JM
7303 /* Normal mode: Send target system values byte by byte, in
7304 increasing byte addresses. Each byte is encoded as a two hex
7305 value. */
124e13d9
SM
7306 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7307 units_written = todo_units;
c906108c 7308 }
802188a7 7309
2e9f7625 7310 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7311 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7312
2e9f7625 7313 if (rs->buf[0] == 'E')
00d84524 7314 return TARGET_XFER_E_IO;
802188a7 7315
124e13d9
SM
7316 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7317 send fewer units than we'd planned. */
7318 *xfered_len_units = (ULONGEST) units_written;
9b409511 7319 return TARGET_XFER_OK;
c906108c
SS
7320}
7321
a76d924d
DJ
7322/* Write memory data directly to the remote machine.
7323 This does not inform the data cache; the data cache uses this.
7324 MEMADDR is the address in the remote memory space.
7325 MYADDR is the address of the buffer in our space.
7326 LEN is the number of bytes.
7327
9b409511
YQ
7328 Return the transferred status, error or OK (an
7329 'enum target_xfer_status' value). Save the number of bytes
7330 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7331
9b409511
YQ
7332static enum target_xfer_status
7333remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7334 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7335{
7336 char *packet_format = 0;
7337
7338 /* Check whether the target supports binary download. */
7339 check_binary_download (memaddr);
7340
4082afcc 7341 switch (packet_support (PACKET_X))
a76d924d
DJ
7342 {
7343 case PACKET_ENABLE:
7344 packet_format = "X";
7345 break;
7346 case PACKET_DISABLE:
7347 packet_format = "M";
7348 break;
7349 case PACKET_SUPPORT_UNKNOWN:
7350 internal_error (__FILE__, __LINE__,
7351 _("remote_write_bytes: bad internal state"));
7352 default:
7353 internal_error (__FILE__, __LINE__, _("bad switch"));
7354 }
7355
7356 return remote_write_bytes_aux (packet_format,
124e13d9 7357 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7358 packet_format[0], 1);
a76d924d
DJ
7359}
7360
9217e74e
YQ
7361/* Read memory data directly from the remote machine.
7362 This does not use the data cache; the data cache uses this.
7363 MEMADDR is the address in the remote memory space.
7364 MYADDR is the address of the buffer in our space.
124e13d9
SM
7365 LEN_UNITS is the number of addressable memory units to read..
7366 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7367
7368 Return the transferred status, error or OK (an
7369 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7370 transferred in *XFERED_LEN_UNITS.
7371
7372 See the comment of remote_write_bytes_aux for an example of
7373 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7374
7375static enum target_xfer_status
124e13d9
SM
7376remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7377 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7378{
7379 struct remote_state *rs = get_remote_state ();
124e13d9 7380 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7381 char *p;
124e13d9
SM
7382 int todo_units;
7383 int decoded_bytes;
9217e74e 7384
124e13d9 7385 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7386 /* The packet buffer will be large enough for the payload;
7387 get_memory_packet_size ensures this. */
7388
124e13d9
SM
7389 /* Number of units that will fit. */
7390 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7391
7392 /* Construct "m"<memaddr>","<len>". */
7393 memaddr = remote_address_masked (memaddr);
7394 p = rs->buf;
7395 *p++ = 'm';
7396 p += hexnumstr (p, (ULONGEST) memaddr);
7397 *p++ = ',';
124e13d9 7398 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7399 *p = '\0';
7400 putpkt (rs->buf);
7401 getpkt (&rs->buf, &rs->buf_size, 0);
7402 if (rs->buf[0] == 'E'
7403 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7404 && rs->buf[3] == '\0')
7405 return TARGET_XFER_E_IO;
7406 /* Reply describes memory byte by byte, each byte encoded as two hex
7407 characters. */
7408 p = rs->buf;
124e13d9 7409 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7410 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7411 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7412 return TARGET_XFER_OK;
7413}
7414
b55fbac4
YQ
7415/* Using the set of read-only target sections of remote, read live
7416 read-only memory.
8acf9577
YQ
7417
7418 For interface/parameters/return description see target.h,
7419 to_xfer_partial. */
7420
7421static enum target_xfer_status
b55fbac4
YQ
7422remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7423 ULONGEST memaddr, ULONGEST len,
124e13d9 7424 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7425{
7426 struct target_section *secp;
7427 struct target_section_table *table;
7428
7429 secp = target_section_by_addr (ops, memaddr);
7430 if (secp != NULL
7431 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7432 secp->the_bfd_section)
7433 & SEC_READONLY))
7434 {
7435 struct target_section *p;
7436 ULONGEST memend = memaddr + len;
7437
7438 table = target_get_section_table (ops);
7439
7440 for (p = table->sections; p < table->sections_end; p++)
7441 {
7442 if (memaddr >= p->addr)
7443 {
7444 if (memend <= p->endaddr)
7445 {
7446 /* Entire transfer is within this section. */
124e13d9 7447 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7448 xfered_len);
8acf9577
YQ
7449 }
7450 else if (memaddr >= p->endaddr)
7451 {
7452 /* This section ends before the transfer starts. */
7453 continue;
7454 }
7455 else
7456 {
7457 /* This section overlaps the transfer. Just do half. */
7458 len = p->endaddr - memaddr;
124e13d9 7459 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7460 xfered_len);
8acf9577
YQ
7461 }
7462 }
7463 }
7464 }
7465
7466 return TARGET_XFER_EOF;
7467}
7468
9217e74e
YQ
7469/* Similar to remote_read_bytes_1, but it reads from the remote stub
7470 first if the requested memory is unavailable in traceframe.
7471 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7472
9b409511 7473static enum target_xfer_status
8acf9577 7474remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7475 gdb_byte *myaddr, ULONGEST len, int unit_size,
7476 ULONGEST *xfered_len)
c906108c 7477{
6b6aa828 7478 if (len == 0)
96c4f946 7479 return TARGET_XFER_EOF;
b2182ed2 7480
8acf9577
YQ
7481 if (get_traceframe_number () != -1)
7482 {
7483 VEC(mem_range_s) *available;
7484
7485 /* If we fail to get the set of available memory, then the
7486 target does not support querying traceframe info, and so we
7487 attempt reading from the traceframe anyway (assuming the
7488 target implements the old QTro packet then). */
7489 if (traceframe_available_memory (&available, memaddr, len))
7490 {
7491 struct cleanup *old_chain;
7492
7493 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7494
7495 if (VEC_empty (mem_range_s, available)
7496 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7497 {
7498 enum target_xfer_status res;
7499
7500 /* Don't read into the traceframe's available
7501 memory. */
7502 if (!VEC_empty (mem_range_s, available))
7503 {
7504 LONGEST oldlen = len;
7505
7506 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7507 gdb_assert (len <= oldlen);
7508 }
7509
7510 do_cleanups (old_chain);
7511
7512 /* This goes through the topmost target again. */
b55fbac4 7513 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7514 len, unit_size, xfered_len);
8acf9577
YQ
7515 if (res == TARGET_XFER_OK)
7516 return TARGET_XFER_OK;
7517 else
7518 {
7519 /* No use trying further, we know some memory starting
7520 at MEMADDR isn't available. */
7521 *xfered_len = len;
7522 return TARGET_XFER_UNAVAILABLE;
7523 }
7524 }
7525
7526 /* Don't try to read more than how much is available, in
7527 case the target implements the deprecated QTro packet to
7528 cater for older GDBs (the target's knowledge of read-only
7529 sections may be outdated by now). */
7530 len = VEC_index (mem_range_s, available, 0)->length;
7531
7532 do_cleanups (old_chain);
7533 }
7534 }
7535
124e13d9 7536 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7537}
74531fed 7538
c906108c 7539\f
c906108c 7540
a76d924d
DJ
7541/* Sends a packet with content determined by the printf format string
7542 FORMAT and the remaining arguments, then gets the reply. Returns
7543 whether the packet was a success, a failure, or unknown. */
7544
77b64a49
PA
7545static enum packet_result remote_send_printf (const char *format, ...)
7546 ATTRIBUTE_PRINTF (1, 2);
7547
2c0b251b 7548static enum packet_result
a76d924d
DJ
7549remote_send_printf (const char *format, ...)
7550{
7551 struct remote_state *rs = get_remote_state ();
7552 int max_size = get_remote_packet_size ();
a76d924d 7553 va_list ap;
a744cf53 7554
a76d924d
DJ
7555 va_start (ap, format);
7556
7557 rs->buf[0] = '\0';
7558 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7559 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7560
7561 if (putpkt (rs->buf) < 0)
7562 error (_("Communication problem with target."));
7563
7564 rs->buf[0] = '\0';
7565 getpkt (&rs->buf, &rs->buf_size, 0);
7566
7567 return packet_check_result (rs->buf);
7568}
7569
7570static void
7571restore_remote_timeout (void *p)
7572{
7573 int value = *(int *)p;
a744cf53 7574
a76d924d
DJ
7575 remote_timeout = value;
7576}
7577
7578/* Flash writing can take quite some time. We'll set
7579 effectively infinite timeout for flash operations.
7580 In future, we'll need to decide on a better approach. */
7581static const int remote_flash_timeout = 1000;
7582
7583static void
7584remote_flash_erase (struct target_ops *ops,
7585 ULONGEST address, LONGEST length)
7586{
f5656ead 7587 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7588 int saved_remote_timeout = remote_timeout;
7589 enum packet_result ret;
a76d924d
DJ
7590 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7591 &saved_remote_timeout);
a744cf53 7592
a76d924d
DJ
7593 remote_timeout = remote_flash_timeout;
7594
7595 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7596 phex (address, addr_size),
a76d924d
DJ
7597 phex (length, 4));
7598 switch (ret)
7599 {
7600 case PACKET_UNKNOWN:
7601 error (_("Remote target does not support flash erase"));
7602 case PACKET_ERROR:
7603 error (_("Error erasing flash with vFlashErase packet"));
7604 default:
7605 break;
7606 }
7607
7608 do_cleanups (back_to);
7609}
7610
9b409511
YQ
7611static enum target_xfer_status
7612remote_flash_write (struct target_ops *ops, ULONGEST address,
7613 ULONGEST length, ULONGEST *xfered_len,
7614 const gdb_byte *data)
a76d924d
DJ
7615{
7616 int saved_remote_timeout = remote_timeout;
9b409511 7617 enum target_xfer_status ret;
a76d924d 7618 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7619 &saved_remote_timeout);
a76d924d
DJ
7620
7621 remote_timeout = remote_flash_timeout;
124e13d9 7622 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 7623 xfered_len,'X', 0);
a76d924d
DJ
7624 do_cleanups (back_to);
7625
7626 return ret;
7627}
7628
7629static void
7630remote_flash_done (struct target_ops *ops)
7631{
7632 int saved_remote_timeout = remote_timeout;
7633 int ret;
7634 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7635 &saved_remote_timeout);
7636
7637 remote_timeout = remote_flash_timeout;
7638 ret = remote_send_printf ("vFlashDone");
7639 do_cleanups (back_to);
7640
7641 switch (ret)
7642 {
7643 case PACKET_UNKNOWN:
7644 error (_("Remote target does not support vFlashDone"));
7645 case PACKET_ERROR:
7646 error (_("Error finishing flash operation"));
7647 default:
7648 break;
7649 }
7650}
7651
c906108c 7652static void
fba45db2 7653remote_files_info (struct target_ops *ignore)
c906108c
SS
7654{
7655 puts_filtered ("Debugging a target over a serial line.\n");
7656}
7657\f
7658/* Stuff for dealing with the packets which are part of this protocol.
7659 See comment at top of file for details. */
7660
1927e618
PA
7661/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7662 error to higher layers. Called when a serial error is detected.
7663 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7664 the system error message for errno at function entry and final dot
7665 for output compatibility with throw_perror_with_name. */
1927e618
PA
7666
7667static void
7668unpush_and_perror (const char *string)
7669{
d6cb50a2 7670 int saved_errno = errno;
1927e618
PA
7671
7672 remote_unpush_target ();
d6cb50a2
JK
7673 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7674 safe_strerror (saved_errno));
1927e618
PA
7675}
7676
0876f84a 7677/* Read a single character from the remote end. */
c906108c
SS
7678
7679static int
fba45db2 7680readchar (int timeout)
c906108c
SS
7681{
7682 int ch;
5d93a237 7683 struct remote_state *rs = get_remote_state ();
c906108c 7684
5d93a237 7685 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7686
2acceee2 7687 if (ch >= 0)
0876f84a 7688 return ch;
2acceee2
JM
7689
7690 switch ((enum serial_rc) ch)
c906108c
SS
7691 {
7692 case SERIAL_EOF:
78a095c3 7693 remote_unpush_target ();
598d3636 7694 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7695 /* no return */
c906108c 7696 case SERIAL_ERROR:
1927e618
PA
7697 unpush_and_perror (_("Remote communication error. "
7698 "Target disconnected."));
2acceee2 7699 /* no return */
c906108c 7700 case SERIAL_TIMEOUT:
2acceee2 7701 break;
c906108c 7702 }
2acceee2 7703 return ch;
c906108c
SS
7704}
7705
c33e31fd
PA
7706/* Wrapper for serial_write that closes the target and throws if
7707 writing fails. */
7708
7709static void
7710remote_serial_write (const char *str, int len)
7711{
5d93a237
TT
7712 struct remote_state *rs = get_remote_state ();
7713
7714 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7715 {
1927e618
PA
7716 unpush_and_perror (_("Remote communication error. "
7717 "Target disconnected."));
c33e31fd
PA
7718 }
7719}
7720
6d820c5c
DJ
7721/* Send the command in *BUF to the remote machine, and read the reply
7722 into *BUF. Report an error if we get an error reply. Resize
7723 *BUF using xrealloc if necessary to hold the result, and update
7724 *SIZEOF_BUF. */
c906108c
SS
7725
7726static void
6d820c5c
DJ
7727remote_send (char **buf,
7728 long *sizeof_buf)
c906108c 7729{
6d820c5c 7730 putpkt (*buf);
c2d11a7d 7731 getpkt (buf, sizeof_buf, 0);
c906108c 7732
6d820c5c
DJ
7733 if ((*buf)[0] == 'E')
7734 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7735}
7736
6e5abd65
PA
7737/* Return a pointer to an xmalloc'ed string representing an escaped
7738 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7739 etc. The caller is responsible for releasing the returned
7740 memory. */
7741
7742static char *
7743escape_buffer (const char *buf, int n)
7744{
7745 struct cleanup *old_chain;
7746 struct ui_file *stb;
7747 char *str;
6e5abd65
PA
7748
7749 stb = mem_fileopen ();
7750 old_chain = make_cleanup_ui_file_delete (stb);
7751
6ef284bd 7752 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7753 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7754 do_cleanups (old_chain);
7755 return str;
7756}
7757
c906108c
SS
7758/* Display a null-terminated packet on stdout, for debugging, using C
7759 string notation. */
7760
7761static void
baa336ce 7762print_packet (const char *buf)
c906108c
SS
7763{
7764 puts_filtered ("\"");
43e526b9 7765 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7766 puts_filtered ("\"");
7767}
7768
7769int
baa336ce 7770putpkt (const char *buf)
c906108c
SS
7771{
7772 return putpkt_binary (buf, strlen (buf));
7773}
7774
7775/* Send a packet to the remote machine, with error checking. The data
23860348 7776 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7777 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7778 and for a possible /0 if we are debugging (remote_debug) and want
7779 to print the sent packet as a string. */
c906108c
SS
7780
7781static int
baa336ce 7782putpkt_binary (const char *buf, int cnt)
c906108c 7783{
2d717e4f 7784 struct remote_state *rs = get_remote_state ();
c906108c
SS
7785 int i;
7786 unsigned char csum = 0;
11cf8741 7787 char *buf2 = alloca (cnt + 6);
085dd6e6 7788
c906108c
SS
7789 int ch;
7790 int tcount = 0;
7791 char *p;
dd61ec5c 7792 char *message;
c906108c 7793
e24a49d8
PA
7794 /* Catch cases like trying to read memory or listing threads while
7795 we're waiting for a stop reply. The remote server wouldn't be
7796 ready to handle this request, so we'd hang and timeout. We don't
7797 have to worry about this in synchronous mode, because in that
7798 case it's not possible to issue a command while the target is
74531fed
PA
7799 running. This is not a problem in non-stop mode, because in that
7800 case, the stub is always ready to process serial input. */
d9d41e78 7801 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7802 {
7803 error (_("Cannot execute this command while the target is running.\n"
7804 "Use the \"interrupt\" command to stop the target\n"
7805 "and then try again."));
7806 }
e24a49d8 7807
2d717e4f
DJ
7808 /* We're sending out a new packet. Make sure we don't look at a
7809 stale cached response. */
7810 rs->cached_wait_status = 0;
7811
c906108c
SS
7812 /* Copy the packet into buffer BUF2, encapsulating it
7813 and giving it a checksum. */
7814
c906108c
SS
7815 p = buf2;
7816 *p++ = '$';
7817
7818 for (i = 0; i < cnt; i++)
7819 {
7820 csum += buf[i];
7821 *p++ = buf[i];
7822 }
7823 *p++ = '#';
7824 *p++ = tohex ((csum >> 4) & 0xf);
7825 *p++ = tohex (csum & 0xf);
7826
7827 /* Send it over and over until we get a positive ack. */
7828
7829 while (1)
7830 {
7831 int started_error_output = 0;
7832
7833 if (remote_debug)
7834 {
6e5abd65
PA
7835 struct cleanup *old_chain;
7836 char *str;
7837
c906108c 7838 *p = '\0';
6e5abd65
PA
7839 str = escape_buffer (buf2, p - buf2);
7840 old_chain = make_cleanup (xfree, str);
7841 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7842 gdb_flush (gdb_stdlog);
6e5abd65 7843 do_cleanups (old_chain);
c906108c 7844 }
c33e31fd 7845 remote_serial_write (buf2, p - buf2);
c906108c 7846
a6f3e723
SL
7847 /* If this is a no acks version of the remote protocol, send the
7848 packet and move on. */
7849 if (rs->noack_mode)
7850 break;
7851
74531fed
PA
7852 /* Read until either a timeout occurs (-2) or '+' is read.
7853 Handle any notification that arrives in the mean time. */
c906108c
SS
7854 while (1)
7855 {
7856 ch = readchar (remote_timeout);
7857
c5aa993b 7858 if (remote_debug)
c906108c
SS
7859 {
7860 switch (ch)
7861 {
7862 case '+':
1216fa2c 7863 case '-':
c906108c
SS
7864 case SERIAL_TIMEOUT:
7865 case '$':
74531fed 7866 case '%':
c906108c
SS
7867 if (started_error_output)
7868 {
7869 putchar_unfiltered ('\n');
7870 started_error_output = 0;
7871 }
7872 }
7873 }
7874
7875 switch (ch)
7876 {
7877 case '+':
7878 if (remote_debug)
0f71a2f6 7879 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7880 return 1;
1216fa2c
AC
7881 case '-':
7882 if (remote_debug)
7883 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7884 /* FALLTHROUGH */
c906108c 7885 case SERIAL_TIMEOUT:
c5aa993b 7886 tcount++;
c906108c
SS
7887 if (tcount > 3)
7888 return 0;
23860348 7889 break; /* Retransmit buffer. */
c906108c
SS
7890 case '$':
7891 {
40e3f985 7892 if (remote_debug)
2bc416ba 7893 fprintf_unfiltered (gdb_stdlog,
23860348 7894 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7895 /* It's probably an old response sent because an ACK
7896 was lost. Gobble up the packet and ack it so it
7897 doesn't get retransmitted when we resend this
7898 packet. */
6d820c5c 7899 skip_frame ();
c33e31fd 7900 remote_serial_write ("+", 1);
23860348 7901 continue; /* Now, go look for +. */
c906108c 7902 }
74531fed
PA
7903
7904 case '%':
7905 {
7906 int val;
7907
7908 /* If we got a notification, handle it, and go back to looking
7909 for an ack. */
7910 /* We've found the start of a notification. Now
7911 collect the data. */
7912 val = read_frame (&rs->buf, &rs->buf_size);
7913 if (val >= 0)
7914 {
7915 if (remote_debug)
7916 {
6e5abd65
PA
7917 struct cleanup *old_chain;
7918 char *str;
7919
7920 str = escape_buffer (rs->buf, val);
7921 old_chain = make_cleanup (xfree, str);
7922 fprintf_unfiltered (gdb_stdlog,
7923 " Notification received: %s\n",
7924 str);
7925 do_cleanups (old_chain);
74531fed 7926 }
5965e028 7927 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7928 /* We're in sync now, rewait for the ack. */
7929 tcount = 0;
7930 }
7931 else
7932 {
7933 if (remote_debug)
7934 {
7935 if (!started_error_output)
7936 {
7937 started_error_output = 1;
7938 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7939 }
7940 fputc_unfiltered (ch & 0177, gdb_stdlog);
7941 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7942 }
7943 }
7944 continue;
7945 }
7946 /* fall-through */
c906108c
SS
7947 default:
7948 if (remote_debug)
7949 {
7950 if (!started_error_output)
7951 {
7952 started_error_output = 1;
0f71a2f6 7953 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7954 }
0f71a2f6 7955 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7956 }
7957 continue;
7958 }
23860348 7959 break; /* Here to retransmit. */
c906108c
SS
7960 }
7961
7962#if 0
7963 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7964 able to get out next time we call QUIT, without anything as
7965 violent as interrupt_query. If we want to provide a way out of
7966 here without getting to the next QUIT, it should be based on
7967 hitting ^C twice as in remote_wait. */
c906108c
SS
7968 if (quit_flag)
7969 {
7970 quit_flag = 0;
7971 interrupt_query ();
7972 }
7973#endif
7974 }
a6f3e723 7975 return 0;
c906108c
SS
7976}
7977
6d820c5c
DJ
7978/* Come here after finding the start of a frame when we expected an
7979 ack. Do our best to discard the rest of this packet. */
7980
7981static void
7982skip_frame (void)
7983{
7984 int c;
7985
7986 while (1)
7987 {
7988 c = readchar (remote_timeout);
7989 switch (c)
7990 {
7991 case SERIAL_TIMEOUT:
7992 /* Nothing we can do. */
7993 return;
7994 case '#':
7995 /* Discard the two bytes of checksum and stop. */
7996 c = readchar (remote_timeout);
7997 if (c >= 0)
7998 c = readchar (remote_timeout);
7999
8000 return;
8001 case '*': /* Run length encoding. */
8002 /* Discard the repeat count. */
8003 c = readchar (remote_timeout);
8004 if (c < 0)
8005 return;
8006 break;
8007 default:
8008 /* A regular character. */
8009 break;
8010 }
8011 }
8012}
8013
c906108c 8014/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8015 into *BUF, verifying the checksum, length, and handling run-length
8016 compression. NUL terminate the buffer. If there is not enough room,
8017 expand *BUF using xrealloc.
c906108c 8018
c2d11a7d
JM
8019 Returns -1 on error, number of characters in buffer (ignoring the
8020 trailing NULL) on success. (could be extended to return one of the
23860348 8021 SERIAL status indications). */
c2d11a7d
JM
8022
8023static long
6d820c5c
DJ
8024read_frame (char **buf_p,
8025 long *sizeof_buf)
c906108c
SS
8026{
8027 unsigned char csum;
c2d11a7d 8028 long bc;
c906108c 8029 int c;
6d820c5c 8030 char *buf = *buf_p;
a6f3e723 8031 struct remote_state *rs = get_remote_state ();
c906108c
SS
8032
8033 csum = 0;
c2d11a7d 8034 bc = 0;
c906108c
SS
8035
8036 while (1)
8037 {
8038 c = readchar (remote_timeout);
c906108c
SS
8039 switch (c)
8040 {
8041 case SERIAL_TIMEOUT:
8042 if (remote_debug)
0f71a2f6 8043 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8044 return -1;
c906108c
SS
8045 case '$':
8046 if (remote_debug)
0f71a2f6
JM
8047 fputs_filtered ("Saw new packet start in middle of old one\n",
8048 gdb_stdlog);
23860348 8049 return -1; /* Start a new packet, count retries. */
c906108c
SS
8050 case '#':
8051 {
8052 unsigned char pktcsum;
e1b09194
AC
8053 int check_0 = 0;
8054 int check_1 = 0;
c906108c 8055
c2d11a7d 8056 buf[bc] = '\0';
c906108c 8057
e1b09194
AC
8058 check_0 = readchar (remote_timeout);
8059 if (check_0 >= 0)
8060 check_1 = readchar (remote_timeout);
802188a7 8061
e1b09194
AC
8062 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8063 {
8064 if (remote_debug)
2bc416ba 8065 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8066 gdb_stdlog);
e1b09194
AC
8067 return -1;
8068 }
8069 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8070 {
8071 if (remote_debug)
2bc416ba 8072 fputs_filtered ("Communication error in checksum\n",
23860348 8073 gdb_stdlog);
40e3f985
FN
8074 return -1;
8075 }
c906108c 8076
a6f3e723
SL
8077 /* Don't recompute the checksum; with no ack packets we
8078 don't have any way to indicate a packet retransmission
8079 is necessary. */
8080 if (rs->noack_mode)
8081 return bc;
8082
e1b09194 8083 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8084 if (csum == pktcsum)
c2d11a7d 8085 return bc;
c906108c 8086
c5aa993b 8087 if (remote_debug)
c906108c 8088 {
6e5abd65
PA
8089 struct cleanup *old_chain;
8090 char *str;
8091
8092 str = escape_buffer (buf, bc);
8093 old_chain = make_cleanup (xfree, str);
8094 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8095 "Bad checksum, sentsum=0x%x, "
8096 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8097 pktcsum, csum, str);
8098 do_cleanups (old_chain);
c906108c 8099 }
c2d11a7d 8100 /* Number of characters in buffer ignoring trailing
23860348 8101 NULL. */
c2d11a7d 8102 return -1;
c906108c 8103 }
23860348 8104 case '*': /* Run length encoding. */
c2c6d25f
JM
8105 {
8106 int repeat;
c906108c 8107
a744cf53 8108 csum += c;
b4501125
AC
8109 c = readchar (remote_timeout);
8110 csum += c;
23860348 8111 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8112
23860348 8113 /* The character before ``*'' is repeated. */
c2d11a7d 8114
6d820c5c 8115 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8116 {
6d820c5c
DJ
8117 if (bc + repeat - 1 >= *sizeof_buf - 1)
8118 {
8119 /* Make some more room in the buffer. */
8120 *sizeof_buf += repeat;
8121 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8122 buf = *buf_p;
8123 }
8124
c2d11a7d
JM
8125 memset (&buf[bc], buf[bc - 1], repeat);
8126 bc += repeat;
c2c6d25f
JM
8127 continue;
8128 }
8129
c2d11a7d 8130 buf[bc] = '\0';
6d820c5c 8131 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8132 return -1;
c2c6d25f 8133 }
c906108c 8134 default:
6d820c5c 8135 if (bc >= *sizeof_buf - 1)
c906108c 8136 {
6d820c5c
DJ
8137 /* Make some more room in the buffer. */
8138 *sizeof_buf *= 2;
8139 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8140 buf = *buf_p;
c906108c
SS
8141 }
8142
6d820c5c
DJ
8143 buf[bc++] = c;
8144 csum += c;
8145 continue;
c906108c
SS
8146 }
8147 }
8148}
8149
8150/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8151 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8152 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8153 rather than timing out; this is used (in synchronous mode) to wait
8154 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8155/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8156 don't have to change all the calls to getpkt to deal with the
8157 return value, because at the moment I don't know what the right
23860348 8158 thing to do it for those. */
c906108c 8159void
6d820c5c
DJ
8160getpkt (char **buf,
8161 long *sizeof_buf,
c2d11a7d 8162 int forever)
d9fcf2fb
JM
8163{
8164 int timed_out;
8165
8166 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8167}
8168
8169
8170/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8171 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8172 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8173 rather than timing out; this is used (in synchronous mode) to wait
8174 for a target that is is executing user code to stop. If FOREVER ==
8175 0, this function is allowed to time out gracefully and return an
74531fed
PA
8176 indication of this to the caller. Otherwise return the number of
8177 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8178 enough reason to return to the caller. *IS_NOTIF is an output
8179 boolean that indicates whether *BUF holds a notification or not
8180 (a regular packet). */
74531fed 8181
3172dc30 8182static int
74531fed 8183getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8184 int expecting_notif, int *is_notif)
c906108c 8185{
2d717e4f 8186 struct remote_state *rs = get_remote_state ();
c906108c
SS
8187 int c;
8188 int tries;
8189 int timeout;
df4b58fe 8190 int val = -1;
c906108c 8191
2d717e4f
DJ
8192 /* We're reading a new response. Make sure we don't look at a
8193 previously cached response. */
8194 rs->cached_wait_status = 0;
8195
6d820c5c 8196 strcpy (*buf, "timeout");
c906108c
SS
8197
8198 if (forever)
74531fed
PA
8199 timeout = watchdog > 0 ? watchdog : -1;
8200 else if (expecting_notif)
8201 timeout = 0; /* There should already be a char in the buffer. If
8202 not, bail out. */
c906108c
SS
8203 else
8204 timeout = remote_timeout;
8205
8206#define MAX_TRIES 3
8207
74531fed
PA
8208 /* Process any number of notifications, and then return when
8209 we get a packet. */
8210 for (;;)
c906108c 8211 {
d9c43928 8212 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8213 times. */
8214 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8215 {
74531fed
PA
8216 /* This can loop forever if the remote side sends us
8217 characters continuously, but if it pauses, we'll get
8218 SERIAL_TIMEOUT from readchar because of timeout. Then
8219 we'll count that as a retry.
8220
8221 Note that even when forever is set, we will only wait
8222 forever prior to the start of a packet. After that, we
8223 expect characters to arrive at a brisk pace. They should
8224 show up within remote_timeout intervals. */
8225 do
8226 c = readchar (timeout);
8227 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8228
8229 if (c == SERIAL_TIMEOUT)
8230 {
74531fed
PA
8231 if (expecting_notif)
8232 return -1; /* Don't complain, it's normal to not get
8233 anything in this case. */
8234
23860348 8235 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8236 {
2acceee2 8237 QUIT;
78a095c3 8238 remote_unpush_target ();
598d3636
JK
8239 throw_error (TARGET_CLOSE_ERROR,
8240 _("Watchdog timeout has expired. "
8241 "Target detached."));
c906108c 8242 }
c906108c 8243 if (remote_debug)
0f71a2f6 8244 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8245 }
74531fed
PA
8246 else
8247 {
8248 /* We've found the start of a packet or notification.
8249 Now collect the data. */
8250 val = read_frame (buf, sizeof_buf);
8251 if (val >= 0)
8252 break;
8253 }
8254
c33e31fd 8255 remote_serial_write ("-", 1);
c906108c 8256 }
c906108c 8257
74531fed
PA
8258 if (tries > MAX_TRIES)
8259 {
8260 /* We have tried hard enough, and just can't receive the
8261 packet/notification. Give up. */
8262 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8263
74531fed
PA
8264 /* Skip the ack char if we're in no-ack mode. */
8265 if (!rs->noack_mode)
c33e31fd 8266 remote_serial_write ("+", 1);
74531fed
PA
8267 return -1;
8268 }
c906108c 8269
74531fed
PA
8270 /* If we got an ordinary packet, return that to our caller. */
8271 if (c == '$')
c906108c
SS
8272 {
8273 if (remote_debug)
43e526b9 8274 {
6e5abd65
PA
8275 struct cleanup *old_chain;
8276 char *str;
8277
8278 str = escape_buffer (*buf, val);
8279 old_chain = make_cleanup (xfree, str);
8280 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8281 do_cleanups (old_chain);
43e526b9 8282 }
a6f3e723
SL
8283
8284 /* Skip the ack char if we're in no-ack mode. */
8285 if (!rs->noack_mode)
c33e31fd 8286 remote_serial_write ("+", 1);
fee9eda9
YQ
8287 if (is_notif != NULL)
8288 *is_notif = 0;
0876f84a 8289 return val;
c906108c
SS
8290 }
8291
74531fed
PA
8292 /* If we got a notification, handle it, and go back to looking
8293 for a packet. */
8294 else
8295 {
8296 gdb_assert (c == '%');
8297
8298 if (remote_debug)
8299 {
6e5abd65
PA
8300 struct cleanup *old_chain;
8301 char *str;
8302
8303 str = escape_buffer (*buf, val);
8304 old_chain = make_cleanup (xfree, str);
8305 fprintf_unfiltered (gdb_stdlog,
8306 " Notification received: %s\n",
8307 str);
8308 do_cleanups (old_chain);
74531fed 8309 }
fee9eda9
YQ
8310 if (is_notif != NULL)
8311 *is_notif = 1;
c906108c 8312
5965e028 8313 handle_notification (rs->notif_state, *buf);
c906108c 8314
74531fed 8315 /* Notifications require no acknowledgement. */
a6f3e723 8316
74531fed 8317 if (expecting_notif)
fee9eda9 8318 return val;
74531fed
PA
8319 }
8320 }
8321}
8322
8323static int
8324getpkt_sane (char **buf, long *sizeof_buf, int forever)
8325{
fee9eda9 8326 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8327}
8328
8329static int
fee9eda9
YQ
8330getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8331 int *is_notif)
74531fed 8332{
fee9eda9
YQ
8333 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8334 is_notif);
c906108c 8335}
74531fed 8336
cbb8991c
DB
8337/* Check whether EVENT is a fork event for the process specified
8338 by the pid passed in DATA, and if it is, kill the fork child. */
8339
8340static int
8341kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8342 QUEUE_ITER (stop_reply_p) *iter,
8343 stop_reply_p event,
8344 void *data)
8345{
8346 struct queue_iter_param *param = data;
8347 int parent_pid = *(int *) param->input;
8348
8349 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8350 {
8351 struct remote_state *rs = get_remote_state ();
8352 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8353 int res;
8354
8355 res = remote_vkill (child_pid, rs);
8356 if (res != 0)
8357 error (_("Can't kill fork child process %d"), child_pid);
8358 }
8359
8360 return 1;
8361}
8362
8363/* Kill any new fork children of process PID that haven't been
8364 processed by follow_fork. */
8365
8366static void
8367kill_new_fork_children (int pid, struct remote_state *rs)
8368{
8369 struct thread_info *thread;
8370 struct notif_client *notif = &notif_client_stop;
8371 struct queue_iter_param param;
8372
8373 /* Kill the fork child threads of any threads in process PID
8374 that are stopped at a fork event. */
8375 ALL_NON_EXITED_THREADS (thread)
8376 {
8377 struct target_waitstatus *ws = &thread->pending_follow;
8378
8379 if (is_pending_fork_parent (ws, pid, thread->ptid))
8380 {
8381 struct remote_state *rs = get_remote_state ();
8382 int child_pid = ptid_get_pid (ws->value.related_pid);
8383 int res;
8384
8385 res = remote_vkill (child_pid, rs);
8386 if (res != 0)
8387 error (_("Can't kill fork child process %d"), child_pid);
8388 }
8389 }
8390
8391 /* Check for any pending fork events (not reported or processed yet)
8392 in process PID and kill those fork child threads as well. */
8393 remote_notif_get_pending_events (notif);
8394 param.input = &pid;
8395 param.output = NULL;
8396 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8397 kill_child_of_pending_fork, &param);
8398}
8399
c906108c
SS
8400\f
8401static void
7d85a9c0 8402remote_kill (struct target_ops *ops)
43ff13b4 8403{
0fdf84ca
PA
8404
8405 /* Catch errors so the user can quit from gdb even when we
23860348 8406 aren't on speaking terms with the remote system. */
492d29ea 8407 TRY
0fdf84ca
PA
8408 {
8409 putpkt ("k");
8410 }
492d29ea 8411 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8412 {
8413 if (ex.error == TARGET_CLOSE_ERROR)
8414 {
8415 /* If we got an (EOF) error that caused the target
8416 to go away, then we're done, that's what we wanted.
8417 "k" is susceptible to cause a premature EOF, given
8418 that the remote server isn't actually required to
8419 reply to "k", and it can happen that it doesn't
8420 even get to reply ACK to the "k". */
8421 return;
8422 }
8423
8424 /* Otherwise, something went wrong. We didn't actually kill
8425 the target. Just propagate the exception, and let the
8426 user or higher layers decide what to do. */
8427 throw_exception (ex);
8428 }
492d29ea 8429 END_CATCH
43ff13b4 8430
0fdf84ca
PA
8431 /* We've killed the remote end, we get to mourn it. Since this is
8432 target remote, single-process, mourning the inferior also
8433 unpushes remote_ops. */
43ff13b4
JM
8434 target_mourn_inferior ();
8435}
8436
82f73884
PA
8437static int
8438remote_vkill (int pid, struct remote_state *rs)
8439{
4082afcc 8440 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8441 return -1;
8442
8443 /* Tell the remote target to detach. */
bba74b36 8444 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8445 putpkt (rs->buf);
8446 getpkt (&rs->buf, &rs->buf_size, 0);
8447
4082afcc
PA
8448 switch (packet_ok (rs->buf,
8449 &remote_protocol_packets[PACKET_vKill]))
8450 {
8451 case PACKET_OK:
8452 return 0;
8453 case PACKET_ERROR:
8454 return 1;
8455 case PACKET_UNKNOWN:
8456 return -1;
8457 default:
8458 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8459 }
82f73884
PA
8460}
8461
8462static void
7d85a9c0 8463extended_remote_kill (struct target_ops *ops)
82f73884
PA
8464{
8465 int res;
8466 int pid = ptid_get_pid (inferior_ptid);
8467 struct remote_state *rs = get_remote_state ();
8468
cbb8991c
DB
8469 /* If we're stopped while forking and we haven't followed yet, kill the
8470 child task. We need to do this before killing the parent task
8471 because if this is a vfork then the parent will be sleeping. */
8472 kill_new_fork_children (pid, rs);
8473
82f73884 8474 res = remote_vkill (pid, rs);
901f9912 8475 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8476 {
8477 /* Don't try 'k' on a multi-process aware stub -- it has no way
8478 to specify the pid. */
8479
8480 putpkt ("k");
8481#if 0
8482 getpkt (&rs->buf, &rs->buf_size, 0);
8483 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8484 res = 1;
8485#else
8486 /* Don't wait for it to die. I'm not really sure it matters whether
8487 we do or not. For the existing stubs, kill is a noop. */
8488 res = 0;
8489#endif
8490 }
8491
8492 if (res != 0)
8493 error (_("Can't kill process"));
8494
82f73884
PA
8495 target_mourn_inferior ();
8496}
8497
c906108c 8498static void
20f796c9 8499remote_mourn (struct target_ops *target)
c906108c
SS
8500{
8501 unpush_target (target);
ce5ce7ed 8502
8a2492ee
PA
8503 /* remote_close takes care of doing most of the clean up. */
8504 generic_mourn_inferior ();
c906108c
SS
8505}
8506
2d717e4f 8507static void
20f796c9 8508extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8509{
8510 struct remote_state *rs = get_remote_state ();
c906108c 8511
e24a49d8
PA
8512 /* In case we got here due to an error, but we're going to stay
8513 connected. */
8514 rs->waiting_for_stop_reply = 0;
8515
dc1981d7
PA
8516 /* If the current general thread belonged to the process we just
8517 detached from or has exited, the remote side current general
8518 thread becomes undefined. Considering a case like this:
8519
8520 - We just got here due to a detach.
8521 - The process that we're detaching from happens to immediately
8522 report a global breakpoint being hit in non-stop mode, in the
8523 same thread we had selected before.
8524 - GDB attaches to this process again.
8525 - This event happens to be the next event we handle.
8526
8527 GDB would consider that the current general thread didn't need to
8528 be set on the stub side (with Hg), since for all it knew,
8529 GENERAL_THREAD hadn't changed.
8530
8531 Notice that although in all-stop mode, the remote server always
8532 sets the current thread to the thread reporting the stop event,
8533 that doesn't happen in non-stop mode; in non-stop, the stub *must
8534 not* change the current thread when reporting a breakpoint hit,
8535 due to the decoupling of event reporting and event handling.
8536
8537 To keep things simple, we always invalidate our notion of the
8538 current thread. */
47f8a51d 8539 record_currthread (rs, minus_one_ptid);
dc1981d7 8540
2d717e4f
DJ
8541 /* Unlike "target remote", we do not want to unpush the target; then
8542 the next time the user says "run", we won't be connected. */
8543
48aa3c27
PA
8544 /* Call common code to mark the inferior as not running. */
8545 generic_mourn_inferior ();
8546
d729566a 8547 if (!have_inferiors ())
2d717e4f 8548 {
82f73884
PA
8549 if (!remote_multi_process_p (rs))
8550 {
8551 /* Check whether the target is running now - some remote stubs
8552 automatically restart after kill. */
8553 putpkt ("?");
8554 getpkt (&rs->buf, &rs->buf_size, 0);
8555
8556 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8557 {
3e43a32a
MS
8558 /* Assume that the target has been restarted. Set
8559 inferior_ptid so that bits of core GDB realizes
8560 there's something here, e.g., so that the user can
8561 say "kill" again. */
82f73884
PA
8562 inferior_ptid = magic_null_ptid;
8563 }
82f73884 8564 }
2d717e4f
DJ
8565 }
8566}
c906108c 8567
03583c20 8568static int
2bfc0540 8569extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8570{
4082afcc 8571 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8572}
8573
8574static void
8575extended_remote_disable_randomization (int val)
8576{
8577 struct remote_state *rs = get_remote_state ();
8578 char *reply;
8579
bba74b36
YQ
8580 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8581 val);
03583c20
UW
8582 putpkt (rs->buf);
8583 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8584 if (*reply == '\0')
8585 error (_("Target does not support QDisableRandomization."));
8586 if (strcmp (reply, "OK") != 0)
8587 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8588}
8589
2d717e4f
DJ
8590static int
8591extended_remote_run (char *args)
8592{
8593 struct remote_state *rs = get_remote_state ();
2d717e4f 8594 int len;
c906108c 8595
2d717e4f
DJ
8596 /* If the user has disabled vRun support, or we have detected that
8597 support is not available, do not try it. */
4082afcc 8598 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8599 return -1;
424163ea 8600
2d717e4f
DJ
8601 strcpy (rs->buf, "vRun;");
8602 len = strlen (rs->buf);
c906108c 8603
2d717e4f
DJ
8604 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8605 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8606 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8607 strlen (remote_exec_file));
2d717e4f 8608
d1a41061 8609 gdb_assert (args != NULL);
2d717e4f
DJ
8610 if (*args)
8611 {
8612 struct cleanup *back_to;
8613 int i;
8614 char **argv;
8615
d1a41061 8616 argv = gdb_buildargv (args);
6e366df1 8617 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8618 for (i = 0; argv[i] != NULL; i++)
8619 {
8620 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8621 error (_("Argument list too long for run packet"));
8622 rs->buf[len++] = ';';
9f1b45b0
TT
8623 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8624 strlen (argv[i]));
2d717e4f
DJ
8625 }
8626 do_cleanups (back_to);
8627 }
8628
8629 rs->buf[len++] = '\0';
8630
8631 putpkt (rs->buf);
8632 getpkt (&rs->buf, &rs->buf_size, 0);
8633
4082afcc 8634 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8635 {
4082afcc 8636 case PACKET_OK:
3405876a 8637 /* We have a wait response. All is well. */
2d717e4f 8638 return 0;
4082afcc
PA
8639 case PACKET_UNKNOWN:
8640 return -1;
8641 case PACKET_ERROR:
2d717e4f
DJ
8642 if (remote_exec_file[0] == '\0')
8643 error (_("Running the default executable on the remote target failed; "
8644 "try \"set remote exec-file\"?"));
8645 else
8646 error (_("Running \"%s\" on the remote target failed"),
8647 remote_exec_file);
4082afcc
PA
8648 default:
8649 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8650 }
c906108c
SS
8651}
8652
2d717e4f
DJ
8653/* In the extended protocol we want to be able to do things like
8654 "run" and have them basically work as expected. So we need
8655 a special create_inferior function. We support changing the
8656 executable file and the command line arguments, but not the
8657 environment. */
8658
43ff13b4 8659static void
77a19445
TT
8660extended_remote_create_inferior (struct target_ops *ops,
8661 char *exec_file, char *args,
8662 char **env, int from_tty)
43ff13b4 8663{
3405876a
PA
8664 int run_worked;
8665 char *stop_reply;
8666 struct remote_state *rs = get_remote_state ();
8667
43ff13b4 8668 /* If running asynchronously, register the target file descriptor
23860348 8669 with the event loop. */
75c99385 8670 if (target_can_async_p ())
6a3753b3 8671 target_async (1);
43ff13b4 8672
03583c20 8673 /* Disable address space randomization if requested (and supported). */
2bfc0540 8674 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8675 extended_remote_disable_randomization (disable_randomization);
8676
43ff13b4 8677 /* Now restart the remote server. */
3405876a
PA
8678 run_worked = extended_remote_run (args) != -1;
8679 if (!run_worked)
2d717e4f
DJ
8680 {
8681 /* vRun was not supported. Fail if we need it to do what the
8682 user requested. */
8683 if (remote_exec_file[0])
8684 error (_("Remote target does not support \"set remote exec-file\""));
8685 if (args[0])
8686 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8687
2d717e4f
DJ
8688 /* Fall back to "R". */
8689 extended_remote_restart ();
8690 }
424163ea 8691
6c95b8df
PA
8692 if (!have_inferiors ())
8693 {
8694 /* Clean up from the last time we ran, before we mark the target
8695 running again. This will mark breakpoints uninserted, and
8696 get_offsets may insert breakpoints. */
8697 init_thread_list ();
8698 init_wait_for_inferior ();
8699 }
45280a52 8700
3405876a
PA
8701 /* vRun's success return is a stop reply. */
8702 stop_reply = run_worked ? rs->buf : NULL;
8703 add_current_inferior_and_thread (stop_reply);
c0a2216e 8704
2d717e4f
DJ
8705 /* Get updated offsets, if the stub uses qOffsets. */
8706 get_offsets ();
2d717e4f 8707}
c906108c 8708\f
c5aa993b 8709
b775012e
LM
8710/* Given a location's target info BP_TGT and the packet buffer BUF, output
8711 the list of conditions (in agent expression bytecode format), if any, the
8712 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8713 started from BUF and ended at BUF_END. */
b775012e
LM
8714
8715static int
8716remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8717 struct bp_target_info *bp_tgt, char *buf,
8718 char *buf_end)
b775012e
LM
8719{
8720 struct agent_expr *aexpr = NULL;
8721 int i, ix;
8722 char *pkt;
8723 char *buf_start = buf;
8724
8725 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8726 return 0;
8727
8728 buf += strlen (buf);
bba74b36 8729 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8730 buf++;
8731
8732 /* Send conditions to the target and free the vector. */
8733 for (ix = 0;
8734 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8735 ix++)
8736 {
bba74b36 8737 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8738 buf += strlen (buf);
8739 for (i = 0; i < aexpr->len; ++i)
8740 buf = pack_hex_byte (buf, aexpr->buf[i]);
8741 *buf = '\0';
8742 }
b775012e
LM
8743 return 0;
8744}
8745
d3ce09f5
SS
8746static void
8747remote_add_target_side_commands (struct gdbarch *gdbarch,
8748 struct bp_target_info *bp_tgt, char *buf)
8749{
8750 struct agent_expr *aexpr = NULL;
8751 int i, ix;
8752
8753 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8754 return;
8755
8756 buf += strlen (buf);
8757
8758 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8759 buf += strlen (buf);
8760
8761 /* Concatenate all the agent expressions that are commands into the
8762 cmds parameter. */
8763 for (ix = 0;
8764 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8765 ix++)
8766 {
8767 sprintf (buf, "X%x,", aexpr->len);
8768 buf += strlen (buf);
8769 for (i = 0; i < aexpr->len; ++i)
8770 buf = pack_hex_byte (buf, aexpr->buf[i]);
8771 *buf = '\0';
8772 }
d3ce09f5
SS
8773}
8774
8181d85f
DJ
8775/* Insert a breakpoint. On targets that have software breakpoint
8776 support, we ask the remote target to do the work; on targets
8777 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8778
8779static int
3db08215
MM
8780remote_insert_breakpoint (struct target_ops *ops,
8781 struct gdbarch *gdbarch,
a6d9a66e 8782 struct bp_target_info *bp_tgt)
c906108c 8783{
d471ea57
AC
8784 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8785 If it succeeds, then set the support to PACKET_ENABLE. If it
8786 fails, and the user has explicitly requested the Z support then
23860348 8787 report an error, otherwise, mark it disabled and go on. */
802188a7 8788
4082afcc 8789 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8790 {
0d5ed153 8791 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8792 struct remote_state *rs;
bba74b36 8793 char *p, *endbuf;
7c0f6dcc 8794 int bpsize;
b775012e 8795 struct condition_list *cond = NULL;
4fff2411 8796
28439a30
PA
8797 /* Make sure the remote is pointing at the right process, if
8798 necessary. */
8799 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8800 set_general_process ();
8801
a1dcb23a 8802 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8803
8804 rs = get_remote_state ();
8805 p = rs->buf;
bba74b36 8806 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8807
96baa820
JM
8808 *(p++) = 'Z';
8809 *(p++) = '0';
8810 *(p++) = ',';
7c0f6dcc 8811 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8812 p += hexnumstr (p, addr);
bba74b36 8813 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8814
efcc2da7 8815 if (remote_supports_cond_breakpoints (ops))
bba74b36 8816 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8817
78eff0ec 8818 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8819 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8820
6d820c5c
DJ
8821 putpkt (rs->buf);
8822 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8823
6d820c5c 8824 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8825 {
d471ea57
AC
8826 case PACKET_ERROR:
8827 return -1;
8828 case PACKET_OK:
7c0f6dcc
JL
8829 bp_tgt->placed_address = addr;
8830 bp_tgt->placed_size = bpsize;
d471ea57
AC
8831 return 0;
8832 case PACKET_UNKNOWN:
8833 break;
96baa820
JM
8834 }
8835 }
c906108c 8836
0000e5cc
PA
8837 /* If this breakpoint has target-side commands but this stub doesn't
8838 support Z0 packets, throw error. */
8839 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8840 throw_error (NOT_SUPPORTED_ERROR, _("\
8841Target doesn't support breakpoints that have target side commands."));
8842
3db08215 8843 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8844}
8845
8846static int
3db08215
MM
8847remote_remove_breakpoint (struct target_ops *ops,
8848 struct gdbarch *gdbarch,
a6d9a66e 8849 struct bp_target_info *bp_tgt)
c906108c 8850{
8181d85f 8851 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8852 struct remote_state *rs = get_remote_state ();
96baa820 8853
4082afcc 8854 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8855 {
6d820c5c 8856 char *p = rs->buf;
bba74b36 8857 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8858
28439a30
PA
8859 /* Make sure the remote is pointing at the right process, if
8860 necessary. */
8861 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8862 set_general_process ();
8863
96baa820
JM
8864 *(p++) = 'z';
8865 *(p++) = '0';
8866 *(p++) = ',';
8867
8181d85f
DJ
8868 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8869 p += hexnumstr (p, addr);
bba74b36 8870 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8871
6d820c5c
DJ
8872 putpkt (rs->buf);
8873 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8874
6d820c5c 8875 return (rs->buf[0] == 'E');
96baa820
JM
8876 }
8877
3db08215 8878 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8879}
8880
f486487f 8881static enum Z_packet_type
d471ea57
AC
8882watchpoint_to_Z_packet (int type)
8883{
8884 switch (type)
8885 {
8886 case hw_write:
bb858e6a 8887 return Z_PACKET_WRITE_WP;
d471ea57
AC
8888 break;
8889 case hw_read:
bb858e6a 8890 return Z_PACKET_READ_WP;
d471ea57
AC
8891 break;
8892 case hw_access:
bb858e6a 8893 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8894 break;
8895 default:
8e65ff28 8896 internal_error (__FILE__, __LINE__,
e2e0b3e5 8897 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8898 }
8899}
8900
3c3bea1c 8901static int
f486487f
SM
8902remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8903 enum target_hw_bp_type type, struct expression *cond)
96baa820 8904{
d01949b6 8905 struct remote_state *rs = get_remote_state ();
bba74b36 8906 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8907 char *p;
d471ea57 8908 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8909
4082afcc 8910 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8911 return 1;
802188a7 8912
28439a30
PA
8913 /* Make sure the remote is pointing at the right process, if
8914 necessary. */
8915 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8916 set_general_process ();
8917
bba74b36 8918 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8919 p = strchr (rs->buf, '\0');
96baa820
JM
8920 addr = remote_address_masked (addr);
8921 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8922 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8923
6d820c5c
DJ
8924 putpkt (rs->buf);
8925 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8926
6d820c5c 8927 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8928 {
8929 case PACKET_ERROR:
d471ea57 8930 return -1;
85d721b8
PA
8931 case PACKET_UNKNOWN:
8932 return 1;
d471ea57
AC
8933 case PACKET_OK:
8934 return 0;
8935 }
8e65ff28 8936 internal_error (__FILE__, __LINE__,
e2e0b3e5 8937 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8938}
8939
283002cf
MR
8940static int
8941remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8942 CORE_ADDR start, int length)
8943{
8944 CORE_ADDR diff = remote_address_masked (addr - start);
8945
8946 return diff < length;
8947}
8948
d471ea57 8949
3c3bea1c 8950static int
f486487f
SM
8951remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8952 enum target_hw_bp_type type, struct expression *cond)
96baa820 8953{
d01949b6 8954 struct remote_state *rs = get_remote_state ();
bba74b36 8955 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8956 char *p;
d471ea57
AC
8957 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8958
4082afcc 8959 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8960 return -1;
802188a7 8961
28439a30
PA
8962 /* Make sure the remote is pointing at the right process, if
8963 necessary. */
8964 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8965 set_general_process ();
8966
bba74b36 8967 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8968 p = strchr (rs->buf, '\0');
96baa820
JM
8969 addr = remote_address_masked (addr);
8970 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8971 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8972 putpkt (rs->buf);
8973 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8974
6d820c5c 8975 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8976 {
8977 case PACKET_ERROR:
8978 case PACKET_UNKNOWN:
8979 return -1;
8980 case PACKET_OK:
8981 return 0;
8982 }
8e65ff28 8983 internal_error (__FILE__, __LINE__,
e2e0b3e5 8984 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8985}
8986
3c3bea1c 8987
501eef12 8988int remote_hw_watchpoint_limit = -1;
480a3f21 8989int remote_hw_watchpoint_length_limit = -1;
501eef12 8990int remote_hw_breakpoint_limit = -1;
d471ea57 8991
480a3f21 8992static int
31568a15
TT
8993remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8994 CORE_ADDR addr, int len)
480a3f21
PW
8995{
8996 if (remote_hw_watchpoint_length_limit == 0)
8997 return 0;
8998 else if (remote_hw_watchpoint_length_limit < 0)
8999 return 1;
9000 else if (len <= remote_hw_watchpoint_length_limit)
9001 return 1;
9002 else
9003 return 0;
9004}
9005
b9362cc7 9006static int
5461485a 9007remote_check_watch_resources (struct target_ops *self,
f486487f 9008 enum bptype type, int cnt, int ot)
96baa820 9009{
3c3bea1c
GS
9010 if (type == bp_hardware_breakpoint)
9011 {
9012 if (remote_hw_breakpoint_limit == 0)
9013 return 0;
501eef12
AC
9014 else if (remote_hw_breakpoint_limit < 0)
9015 return 1;
3c3bea1c
GS
9016 else if (cnt <= remote_hw_breakpoint_limit)
9017 return 1;
9018 }
9019 else
9020 {
9021 if (remote_hw_watchpoint_limit == 0)
9022 return 0;
501eef12
AC
9023 else if (remote_hw_watchpoint_limit < 0)
9024 return 1;
3c3bea1c
GS
9025 else if (ot)
9026 return -1;
9027 else if (cnt <= remote_hw_watchpoint_limit)
9028 return 1;
9029 }
9030 return -1;
9031}
9032
f7e6eed5
PA
9033/* The to_stopped_by_sw_breakpoint method of target remote. */
9034
9035static int
9036remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9037{
9038 struct remote_state *rs = get_remote_state ();
9039
9040 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9041}
9042
9043/* The to_supports_stopped_by_sw_breakpoint method of target
9044 remote. */
9045
9046static int
9047remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9048{
9049 struct remote_state *rs = get_remote_state ();
9050
9051 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9052}
9053
9054/* The to_stopped_by_hw_breakpoint method of target remote. */
9055
9056static int
9057remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9058{
9059 struct remote_state *rs = get_remote_state ();
9060
9061 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9062}
9063
9064/* The to_supports_stopped_by_hw_breakpoint method of target
9065 remote. */
9066
9067static int
9068remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9069{
9070 struct remote_state *rs = get_remote_state ();
9071
9072 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9073}
9074
b9362cc7 9075static int
6a109b6b 9076remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9077{
ee154bee
TT
9078 struct remote_state *rs = get_remote_state ();
9079
f7e6eed5 9080 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
9081}
9082
4aa7a7f5
JJ
9083static int
9084remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9085{
ee154bee 9086 struct remote_state *rs = get_remote_state ();
4aa7a7f5 9087 int rc = 0;
a744cf53 9088
6a109b6b 9089 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 9090 {
ee154bee 9091 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
9092 rc = 1;
9093 }
9094
9095 return rc;
3c3bea1c
GS
9096}
9097
9098
9099static int
23a26771 9100remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9101 struct bp_target_info *bp_tgt)
3c3bea1c 9102{
0d5ed153 9103 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9104 struct remote_state *rs;
bba74b36 9105 char *p, *endbuf;
dd61ec5c 9106 char *message;
0d5ed153 9107 int bpsize;
802188a7 9108
c8189ed1 9109 /* The length field should be set to the size of a breakpoint
8181d85f 9110 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9111
0d5ed153 9112 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9113
4082afcc 9114 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9115 return -1;
2bc416ba 9116
28439a30
PA
9117 /* Make sure the remote is pointing at the right process, if
9118 necessary. */
9119 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9120 set_general_process ();
9121
4fff2411
JZ
9122 rs = get_remote_state ();
9123 p = rs->buf;
bba74b36 9124 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9125
96baa820
JM
9126 *(p++) = 'Z';
9127 *(p++) = '1';
9128 *(p++) = ',';
802188a7 9129
0d5ed153 9130 addr = remote_address_masked (addr);
96baa820 9131 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9132 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9133
efcc2da7 9134 if (remote_supports_cond_breakpoints (self))
bba74b36 9135 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9136
78eff0ec 9137 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9138 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9139
6d820c5c
DJ
9140 putpkt (rs->buf);
9141 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9142
6d820c5c 9143 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9144 {
9145 case PACKET_ERROR:
dd61ec5c
MW
9146 if (rs->buf[1] == '.')
9147 {
9148 message = strchr (rs->buf + 2, '.');
9149 if (message)
0316657e 9150 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9151 }
9152 return -1;
d471ea57
AC
9153 case PACKET_UNKNOWN:
9154 return -1;
9155 case PACKET_OK:
0d5ed153
MR
9156 bp_tgt->placed_address = addr;
9157 bp_tgt->placed_size = bpsize;
d471ea57
AC
9158 return 0;
9159 }
8e65ff28 9160 internal_error (__FILE__, __LINE__,
e2e0b3e5 9161 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9162}
9163
d471ea57 9164
802188a7 9165static int
a64dc96c 9166remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9167 struct bp_target_info *bp_tgt)
96baa820 9168{
8181d85f 9169 CORE_ADDR addr;
d01949b6 9170 struct remote_state *rs = get_remote_state ();
6d820c5c 9171 char *p = rs->buf;
bba74b36 9172 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9173
4082afcc 9174 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9175 return -1;
802188a7 9176
28439a30
PA
9177 /* Make sure the remote is pointing at the right process, if
9178 necessary. */
9179 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9180 set_general_process ();
9181
96baa820
JM
9182 *(p++) = 'z';
9183 *(p++) = '1';
9184 *(p++) = ',';
802188a7 9185
8181d85f 9186 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9187 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9188 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9189
6d820c5c
DJ
9190 putpkt (rs->buf);
9191 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9192
6d820c5c 9193 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9194 {
9195 case PACKET_ERROR:
9196 case PACKET_UNKNOWN:
9197 return -1;
9198 case PACKET_OK:
9199 return 0;
9200 }
8e65ff28 9201 internal_error (__FILE__, __LINE__,
e2e0b3e5 9202 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9203}
96baa820 9204
4a5e7a5b
PA
9205/* Verify memory using the "qCRC:" request. */
9206
9207static int
9208remote_verify_memory (struct target_ops *ops,
9209 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9210{
9211 struct remote_state *rs = get_remote_state ();
9212 unsigned long host_crc, target_crc;
9213 char *tmp;
9214
936d2992
PA
9215 /* It doesn't make sense to use qCRC if the remote target is
9216 connected but not running. */
9217 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9218 {
9219 enum packet_result result;
28439a30 9220
936d2992
PA
9221 /* Make sure the remote is pointing at the right process. */
9222 set_general_process ();
4a5e7a5b 9223
936d2992
PA
9224 /* FIXME: assumes lma can fit into long. */
9225 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9226 (long) lma, (long) size);
9227 putpkt (rs->buf);
4a5e7a5b 9228
936d2992
PA
9229 /* Be clever; compute the host_crc before waiting for target
9230 reply. */
9231 host_crc = xcrc32 (data, size, 0xffffffff);
9232
9233 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9234
936d2992
PA
9235 result = packet_ok (rs->buf,
9236 &remote_protocol_packets[PACKET_qCRC]);
9237 if (result == PACKET_ERROR)
9238 return -1;
9239 else if (result == PACKET_OK)
9240 {
9241 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9242 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9243
936d2992
PA
9244 return (host_crc == target_crc);
9245 }
9246 }
4a5e7a5b 9247
936d2992 9248 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9249}
9250
c906108c
SS
9251/* compare-sections command
9252
9253 With no arguments, compares each loadable section in the exec bfd
9254 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9255 Useful for verifying the image on the target against the exec file. */
e514a9d6 9256
c906108c 9257static void
fba45db2 9258compare_sections_command (char *args, int from_tty)
c906108c
SS
9259{
9260 asection *s;
c906108c 9261 struct cleanup *old_chain;
948f8e3d 9262 gdb_byte *sectdata;
ce359b09 9263 const char *sectname;
c906108c
SS
9264 bfd_size_type size;
9265 bfd_vma lma;
9266 int matched = 0;
9267 int mismatched = 0;
4a5e7a5b 9268 int res;
95cf3b38 9269 int read_only = 0;
c906108c
SS
9270
9271 if (!exec_bfd)
8a3fe4f8 9272 error (_("command cannot be used without an exec file"));
c906108c 9273
28439a30
PA
9274 /* Make sure the remote is pointing at the right process. */
9275 set_general_process ();
9276
95cf3b38
DT
9277 if (args != NULL && strcmp (args, "-r") == 0)
9278 {
9279 read_only = 1;
9280 args = NULL;
9281 }
9282
c5aa993b 9283 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9284 {
9285 if (!(s->flags & SEC_LOAD))
0df8b418 9286 continue; /* Skip non-loadable section. */
c906108c 9287
95cf3b38
DT
9288 if (read_only && (s->flags & SEC_READONLY) == 0)
9289 continue; /* Skip writeable sections */
9290
2c500098 9291 size = bfd_get_section_size (s);
c906108c 9292 if (size == 0)
0df8b418 9293 continue; /* Skip zero-length section. */
c906108c 9294
ce359b09 9295 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9296 if (args && strcmp (args, sectname) != 0)
0df8b418 9297 continue; /* Not the section selected by user. */
c906108c 9298
0df8b418 9299 matched = 1; /* Do this section. */
c906108c 9300 lma = s->lma;
c906108c 9301
c906108c 9302 sectdata = xmalloc (size);
b8c9b27d 9303 old_chain = make_cleanup (xfree, sectdata);
c906108c 9304 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9305
4a5e7a5b
PA
9306 res = target_verify_memory (sectdata, lma, size);
9307
9308 if (res == -1)
5af949e3 9309 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9310 paddress (target_gdbarch (), lma),
9311 paddress (target_gdbarch (), lma + size));
c906108c 9312
5af949e3 9313 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9314 paddress (target_gdbarch (), lma),
9315 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9316 if (res)
c906108c
SS
9317 printf_filtered ("matched.\n");
9318 else
c5aa993b
JM
9319 {
9320 printf_filtered ("MIS-MATCHED!\n");
9321 mismatched++;
9322 }
c906108c
SS
9323
9324 do_cleanups (old_chain);
9325 }
9326 if (mismatched > 0)
936d2992 9327 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9328the loaded file\n"));
c906108c 9329 if (args && !matched)
a3f17187 9330 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9331}
9332
0e7f50da
UW
9333/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9334 into remote target. The number of bytes written to the remote
9335 target is returned, or -1 for error. */
9336
9b409511 9337static enum target_xfer_status
0e7f50da
UW
9338remote_write_qxfer (struct target_ops *ops, const char *object_name,
9339 const char *annex, const gdb_byte *writebuf,
9b409511 9340 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9341 struct packet_config *packet)
9342{
9343 int i, buf_len;
9344 ULONGEST n;
0e7f50da
UW
9345 struct remote_state *rs = get_remote_state ();
9346 int max_size = get_memory_write_packet_size ();
9347
9348 if (packet->support == PACKET_DISABLE)
2ed4b548 9349 return TARGET_XFER_E_IO;
0e7f50da
UW
9350
9351 /* Insert header. */
9352 i = snprintf (rs->buf, max_size,
9353 "qXfer:%s:write:%s:%s:",
9354 object_name, annex ? annex : "",
9355 phex_nz (offset, sizeof offset));
9356 max_size -= (i + 1);
9357
9358 /* Escape as much data as fits into rs->buf. */
9359 buf_len = remote_escape_output
124e13d9 9360 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9361
9362 if (putpkt_binary (rs->buf, i + buf_len) < 0
9363 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9364 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9365 return TARGET_XFER_E_IO;
0e7f50da
UW
9366
9367 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9368
9369 *xfered_len = n;
9370 return TARGET_XFER_OK;
0e7f50da
UW
9371}
9372
0876f84a
DJ
9373/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9374 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9375 number of bytes read is returned, or 0 for EOF, or -1 for error.
9376 The number of bytes read may be less than LEN without indicating an
9377 EOF. PACKET is checked and updated to indicate whether the remote
9378 target supports this object. */
9379
9b409511 9380static enum target_xfer_status
0876f84a
DJ
9381remote_read_qxfer (struct target_ops *ops, const char *object_name,
9382 const char *annex,
9383 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9384 ULONGEST *xfered_len,
0876f84a
DJ
9385 struct packet_config *packet)
9386{
0876f84a 9387 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9388 LONGEST i, n, packet_len;
9389
9390 if (packet->support == PACKET_DISABLE)
2ed4b548 9391 return TARGET_XFER_E_IO;
0876f84a
DJ
9392
9393 /* Check whether we've cached an end-of-object packet that matches
9394 this request. */
8e88304f 9395 if (rs->finished_object)
0876f84a 9396 {
8e88304f
TT
9397 if (strcmp (object_name, rs->finished_object) == 0
9398 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9399 && offset == rs->finished_offset)
9b409511
YQ
9400 return TARGET_XFER_EOF;
9401
0876f84a
DJ
9402
9403 /* Otherwise, we're now reading something different. Discard
9404 the cache. */
8e88304f
TT
9405 xfree (rs->finished_object);
9406 xfree (rs->finished_annex);
9407 rs->finished_object = NULL;
9408 rs->finished_annex = NULL;
0876f84a
DJ
9409 }
9410
9411 /* Request only enough to fit in a single packet. The actual data
9412 may not, since we don't know how much of it will need to be escaped;
9413 the target is free to respond with slightly less data. We subtract
9414 five to account for the response type and the protocol frame. */
9415 n = min (get_remote_packet_size () - 5, len);
9416 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9417 object_name, annex ? annex : "",
9418 phex_nz (offset, sizeof offset),
9419 phex_nz (n, sizeof n));
9420 i = putpkt (rs->buf);
9421 if (i < 0)
2ed4b548 9422 return TARGET_XFER_E_IO;
0876f84a
DJ
9423
9424 rs->buf[0] = '\0';
9425 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9426 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9427 return TARGET_XFER_E_IO;
0876f84a
DJ
9428
9429 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9430 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9431
9432 /* 'm' means there is (or at least might be) more data after this
9433 batch. That does not make sense unless there's at least one byte
9434 of data in this reply. */
9435 if (rs->buf[0] == 'm' && packet_len == 1)
9436 error (_("Remote qXfer reply contained no data."));
9437
9438 /* Got some data. */
bc20a4af
PA
9439 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9440 packet_len - 1, readbuf, n);
0876f84a
DJ
9441
9442 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9443 or possibly empty. If we have the final block of a non-empty
9444 object, record this fact to bypass a subsequent partial read. */
9445 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9446 {
8e88304f
TT
9447 rs->finished_object = xstrdup (object_name);
9448 rs->finished_annex = xstrdup (annex ? annex : "");
9449 rs->finished_offset = offset + i;
0876f84a
DJ
9450 }
9451
9b409511
YQ
9452 if (i == 0)
9453 return TARGET_XFER_EOF;
9454 else
9455 {
9456 *xfered_len = i;
9457 return TARGET_XFER_OK;
9458 }
0876f84a
DJ
9459}
9460
9b409511 9461static enum target_xfer_status
4b8a223f 9462remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9463 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9464 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9465 ULONGEST *xfered_len)
c906108c 9466{
82f73884 9467 struct remote_state *rs;
c906108c 9468 int i;
6d820c5c 9469 char *p2;
1e3ff5ad 9470 char query_type;
124e13d9 9471 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9472
e6e4e701 9473 set_remote_traceframe ();
82f73884
PA
9474 set_general_thread (inferior_ptid);
9475
9476 rs = get_remote_state ();
9477
b2182ed2 9478 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9479 if (object == TARGET_OBJECT_MEMORY)
9480 {
2d717e4f
DJ
9481 /* If the remote target is connected but not running, we should
9482 pass this request down to a lower stratum (e.g. the executable
9483 file). */
9484 if (!target_has_execution)
9b409511 9485 return TARGET_XFER_EOF;
2d717e4f 9486
21e3b9b9 9487 if (writebuf != NULL)
124e13d9
SM
9488 return remote_write_bytes (offset, writebuf, len, unit_size,
9489 xfered_len);
21e3b9b9 9490 else
124e13d9
SM
9491 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9492 xfered_len);
21e3b9b9
DJ
9493 }
9494
0df8b418 9495 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9496 if (object == TARGET_OBJECT_SPU)
9497 {
9498 if (readbuf)
9499 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9500 xfered_len, &remote_protocol_packets
9501 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9502 else
9503 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9504 xfered_len, &remote_protocol_packets
9505 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9506 }
9507
4aa995e1
PA
9508 /* Handle extra signal info using qxfer packets. */
9509 if (object == TARGET_OBJECT_SIGNAL_INFO)
9510 {
9511 if (readbuf)
9512 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9513 xfered_len, &remote_protocol_packets
4aa995e1
PA
9514 [PACKET_qXfer_siginfo_read]);
9515 else
3e43a32a 9516 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9517 writebuf, offset, len, xfered_len,
4aa995e1
PA
9518 &remote_protocol_packets
9519 [PACKET_qXfer_siginfo_write]);
9520 }
9521
0fb4aa4b
PA
9522 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9523 {
9524 if (readbuf)
3e43a32a 9525 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9526 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9527 &remote_protocol_packets
9528 [PACKET_qXfer_statictrace_read]);
9529 else
2ed4b548 9530 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9531 }
9532
a76d924d
DJ
9533 /* Only handle flash writes. */
9534 if (writebuf != NULL)
9535 {
9536 LONGEST xfered;
9537
9538 switch (object)
9539 {
9540 case TARGET_OBJECT_FLASH:
9b409511
YQ
9541 return remote_flash_write (ops, offset, len, xfered_len,
9542 writebuf);
a76d924d
DJ
9543
9544 default:
2ed4b548 9545 return TARGET_XFER_E_IO;
a76d924d
DJ
9546 }
9547 }
4b8a223f 9548
1e3ff5ad
AC
9549 /* Map pre-existing objects onto letters. DO NOT do this for new
9550 objects!!! Instead specify new query packets. */
9551 switch (object)
c906108c 9552 {
1e3ff5ad
AC
9553 case TARGET_OBJECT_AVR:
9554 query_type = 'R';
9555 break;
802188a7
RM
9556
9557 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9558 gdb_assert (annex == NULL);
9559 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9560 xfered_len,
0876f84a 9561 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9562
23181151
DJ
9563 case TARGET_OBJECT_AVAILABLE_FEATURES:
9564 return remote_read_qxfer
9b409511 9565 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9566 &remote_protocol_packets[PACKET_qXfer_features]);
9567
cfa9d6d9
DJ
9568 case TARGET_OBJECT_LIBRARIES:
9569 return remote_read_qxfer
9b409511 9570 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9571 &remote_protocol_packets[PACKET_qXfer_libraries]);
9572
2268b414
JK
9573 case TARGET_OBJECT_LIBRARIES_SVR4:
9574 return remote_read_qxfer
9b409511 9575 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9576 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9577
fd79ecee
DJ
9578 case TARGET_OBJECT_MEMORY_MAP:
9579 gdb_assert (annex == NULL);
9580 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9581 xfered_len,
fd79ecee
DJ
9582 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9583
07e059b5
VP
9584 case TARGET_OBJECT_OSDATA:
9585 /* Should only get here if we're connected. */
5d93a237 9586 gdb_assert (rs->remote_desc);
07e059b5 9587 return remote_read_qxfer
9b409511 9588 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9589 &remote_protocol_packets[PACKET_qXfer_osdata]);
9590
dc146f7c
VP
9591 case TARGET_OBJECT_THREADS:
9592 gdb_assert (annex == NULL);
9593 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9594 xfered_len,
dc146f7c
VP
9595 &remote_protocol_packets[PACKET_qXfer_threads]);
9596
b3b9301e
PA
9597 case TARGET_OBJECT_TRACEFRAME_INFO:
9598 gdb_assert (annex == NULL);
9599 return remote_read_qxfer
9b409511 9600 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9601 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9602
9603 case TARGET_OBJECT_FDPIC:
9604 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9605 xfered_len,
78d85199 9606 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9607
9608 case TARGET_OBJECT_OPENVMS_UIB:
9609 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9610 xfered_len,
169081d0
TG
9611 &remote_protocol_packets[PACKET_qXfer_uib]);
9612
9accd112
MM
9613 case TARGET_OBJECT_BTRACE:
9614 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9615 xfered_len,
9accd112
MM
9616 &remote_protocol_packets[PACKET_qXfer_btrace]);
9617
f4abbc16
MM
9618 case TARGET_OBJECT_BTRACE_CONF:
9619 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9620 len, xfered_len,
9621 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9622
c78fa86a
GB
9623 case TARGET_OBJECT_EXEC_FILE:
9624 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9625 len, xfered_len,
9626 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9627
1e3ff5ad 9628 default:
2ed4b548 9629 return TARGET_XFER_E_IO;
c906108c
SS
9630 }
9631
0df8b418 9632 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9633 large enough let the caller deal with it. */
ea9c271d 9634 if (len < get_remote_packet_size ())
2ed4b548 9635 return TARGET_XFER_E_IO;
ea9c271d 9636 len = get_remote_packet_size ();
1e3ff5ad 9637
23860348 9638 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9639 if (!rs->remote_desc)
8a3fe4f8 9640 error (_("remote query is only available after target open"));
c906108c 9641
1e3ff5ad 9642 gdb_assert (annex != NULL);
4b8a223f 9643 gdb_assert (readbuf != NULL);
c906108c 9644
6d820c5c 9645 p2 = rs->buf;
c906108c
SS
9646 *p2++ = 'q';
9647 *p2++ = query_type;
9648
23860348
MS
9649 /* We used one buffer char for the remote protocol q command and
9650 another for the query type. As the remote protocol encapsulation
9651 uses 4 chars plus one extra in case we are debugging
9652 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9653 string. */
c906108c 9654 i = 0;
ea9c271d 9655 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9656 {
1e3ff5ad
AC
9657 /* Bad caller may have sent forbidden characters. */
9658 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9659 *p2++ = annex[i];
c906108c
SS
9660 i++;
9661 }
1e3ff5ad
AC
9662 *p2 = '\0';
9663 gdb_assert (annex[i] == '\0');
c906108c 9664
6d820c5c 9665 i = putpkt (rs->buf);
c5aa993b 9666 if (i < 0)
2ed4b548 9667 return TARGET_XFER_E_IO;
c906108c 9668
6d820c5c
DJ
9669 getpkt (&rs->buf, &rs->buf_size, 0);
9670 strcpy ((char *) readbuf, rs->buf);
c906108c 9671
9b409511
YQ
9672 *xfered_len = strlen ((char *) readbuf);
9673 return TARGET_XFER_OK;
c906108c
SS
9674}
9675
08388c79
DE
9676static int
9677remote_search_memory (struct target_ops* ops,
9678 CORE_ADDR start_addr, ULONGEST search_space_len,
9679 const gdb_byte *pattern, ULONGEST pattern_len,
9680 CORE_ADDR *found_addrp)
9681{
f5656ead 9682 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9683 struct remote_state *rs = get_remote_state ();
9684 int max_size = get_memory_write_packet_size ();
9685 struct packet_config *packet =
9686 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9687 /* Number of packet bytes used to encode the pattern;
9688 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9689 int escaped_pattern_len;
0df8b418 9690 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9691 int used_pattern_len;
9692 int i;
9693 int found;
9694 ULONGEST found_addr;
9695
9696 /* Don't go to the target if we don't have to.
9697 This is done before checking packet->support to avoid the possibility that
9698 a success for this edge case means the facility works in general. */
9699 if (pattern_len > search_space_len)
9700 return 0;
9701 if (pattern_len == 0)
9702 {
9703 *found_addrp = start_addr;
9704 return 1;
9705 }
9706
9707 /* If we already know the packet isn't supported, fall back to the simple
9708 way of searching memory. */
9709
4082afcc 9710 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9711 {
9712 /* Target doesn't provided special support, fall back and use the
9713 standard support (copy memory and do the search here). */
9714 return simple_search_memory (ops, start_addr, search_space_len,
9715 pattern, pattern_len, found_addrp);
9716 }
9717
28439a30
PA
9718 /* Make sure the remote is pointing at the right process. */
9719 set_general_process ();
9720
08388c79
DE
9721 /* Insert header. */
9722 i = snprintf (rs->buf, max_size,
9723 "qSearch:memory:%s;%s;",
5af949e3 9724 phex_nz (start_addr, addr_size),
08388c79
DE
9725 phex_nz (search_space_len, sizeof (search_space_len)));
9726 max_size -= (i + 1);
9727
9728 /* Escape as much data as fits into rs->buf. */
9729 escaped_pattern_len =
124e13d9 9730 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
9731 &used_pattern_len, max_size);
9732
9733 /* Bail if the pattern is too large. */
9734 if (used_pattern_len != pattern_len)
9b20d036 9735 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9736
9737 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9738 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9739 || packet_ok (rs->buf, packet) != PACKET_OK)
9740 {
9741 /* The request may not have worked because the command is not
9742 supported. If so, fall back to the simple way. */
9743 if (packet->support == PACKET_DISABLE)
9744 {
9745 return simple_search_memory (ops, start_addr, search_space_len,
9746 pattern, pattern_len, found_addrp);
9747 }
9748 return -1;
9749 }
9750
9751 if (rs->buf[0] == '0')
9752 found = 0;
9753 else if (rs->buf[0] == '1')
9754 {
9755 found = 1;
9756 if (rs->buf[1] != ',')
10e0fa18 9757 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9758 unpack_varlen_hex (rs->buf + 2, &found_addr);
9759 *found_addrp = found_addr;
9760 }
9761 else
10e0fa18 9762 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9763
9764 return found;
9765}
9766
96baa820 9767static void
a30bf1f1 9768remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9769 struct ui_file *outbuf)
96baa820 9770{
d01949b6 9771 struct remote_state *rs = get_remote_state ();
2e9f7625 9772 char *p = rs->buf;
96baa820 9773
5d93a237 9774 if (!rs->remote_desc)
8a3fe4f8 9775 error (_("remote rcmd is only available after target open"));
96baa820 9776
23860348 9777 /* Send a NULL command across as an empty command. */
7be570e7
JM
9778 if (command == NULL)
9779 command = "";
9780
23860348 9781 /* The query prefix. */
2e9f7625
DJ
9782 strcpy (rs->buf, "qRcmd,");
9783 p = strchr (rs->buf, '\0');
96baa820 9784
3e43a32a
MS
9785 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9786 > get_remote_packet_size ())
8a3fe4f8 9787 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9788
23860348 9789 /* Encode the actual command. */
a30bf1f1 9790 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9791
6d820c5c 9792 if (putpkt (rs->buf) < 0)
8a3fe4f8 9793 error (_("Communication problem with target."));
96baa820
JM
9794
9795 /* get/display the response */
9796 while (1)
9797 {
2e9f7625
DJ
9798 char *buf;
9799
00bf0b85 9800 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9801 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9802 rs->buf[0] = '\0';
5b37825d
PW
9803 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9804 {
9805 /* Timeout. Continue to (try to) read responses.
9806 This is better than stopping with an error, assuming the stub
9807 is still executing the (long) monitor command.
9808 If needed, the user can interrupt gdb using C-c, obtaining
9809 an effect similar to stop on timeout. */
9810 continue;
9811 }
2e9f7625 9812 buf = rs->buf;
96baa820 9813 if (buf[0] == '\0')
8a3fe4f8 9814 error (_("Target does not support this command."));
96baa820
JM
9815 if (buf[0] == 'O' && buf[1] != 'K')
9816 {
23860348 9817 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9818 continue;
9819 }
9820 if (strcmp (buf, "OK") == 0)
9821 break;
7be570e7
JM
9822 if (strlen (buf) == 3 && buf[0] == 'E'
9823 && isdigit (buf[1]) && isdigit (buf[2]))
9824 {
8a3fe4f8 9825 error (_("Protocol error with Rcmd"));
7be570e7 9826 }
96baa820
JM
9827 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9828 {
9829 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9830
96baa820
JM
9831 fputc_unfiltered (c, outbuf);
9832 }
9833 break;
9834 }
9835}
9836
fd79ecee
DJ
9837static VEC(mem_region_s) *
9838remote_memory_map (struct target_ops *ops)
9839{
9840 VEC(mem_region_s) *result = NULL;
9841 char *text = target_read_stralloc (&current_target,
9842 TARGET_OBJECT_MEMORY_MAP, NULL);
9843
9844 if (text)
9845 {
9846 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9847
fd79ecee
DJ
9848 result = parse_memory_map (text);
9849 do_cleanups (back_to);
9850 }
9851
9852 return result;
9853}
9854
c906108c 9855static void
fba45db2 9856packet_command (char *args, int from_tty)
c906108c 9857{
d01949b6 9858 struct remote_state *rs = get_remote_state ();
c906108c 9859
5d93a237 9860 if (!rs->remote_desc)
8a3fe4f8 9861 error (_("command can only be used with remote target"));
c906108c 9862
c5aa993b 9863 if (!args)
8a3fe4f8 9864 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9865
9866 puts_filtered ("sending: ");
9867 print_packet (args);
9868 puts_filtered ("\n");
9869 putpkt (args);
9870
6d820c5c 9871 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9872 puts_filtered ("received: ");
6d820c5c 9873 print_packet (rs->buf);
c906108c
SS
9874 puts_filtered ("\n");
9875}
9876
9877#if 0
23860348 9878/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9879
a14ed312 9880static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9881
a14ed312 9882static void threadset_test_cmd (char *cmd, int tty);
c906108c 9883
a14ed312 9884static void threadalive_test (char *cmd, int tty);
c906108c 9885
a14ed312 9886static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9887
23860348 9888int get_and_display_threadinfo (threadref *ref);
c906108c 9889
a14ed312 9890static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9891
23860348 9892static int thread_display_step (threadref *ref, void *context);
c906108c 9893
a14ed312 9894static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9895
a14ed312 9896static void init_remote_threadtests (void);
c906108c 9897
23860348 9898#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9899
9900static void
fba45db2 9901threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9902{
9903 int sample_thread = SAMPLE_THREAD;
9904
a3f17187 9905 printf_filtered (_("Remote threadset test\n"));
79d7f229 9906 set_general_thread (sample_thread);
c906108c
SS
9907}
9908
9909
9910static void
fba45db2 9911threadalive_test (char *cmd, int tty)
c906108c
SS
9912{
9913 int sample_thread = SAMPLE_THREAD;
79d7f229 9914 int pid = ptid_get_pid (inferior_ptid);
ba348170 9915 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9916
79d7f229 9917 if (remote_thread_alive (ptid))
c906108c
SS
9918 printf_filtered ("PASS: Thread alive test\n");
9919 else
9920 printf_filtered ("FAIL: Thread alive test\n");
9921}
9922
23860348 9923void output_threadid (char *title, threadref *ref);
c906108c
SS
9924
9925void
fba45db2 9926output_threadid (char *title, threadref *ref)
c906108c
SS
9927{
9928 char hexid[20];
9929
23860348 9930 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9931 hexid[16] = 0;
9932 printf_filtered ("%s %s\n", title, (&hexid[0]));
9933}
9934
9935static void
fba45db2 9936threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9937{
9938 int startflag = 1;
9939 threadref nextthread;
9940 int done, result_count;
9941 threadref threadlist[3];
9942
9943 printf_filtered ("Remote Threadlist test\n");
9944 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9945 &result_count, &threadlist[0]))
9946 printf_filtered ("FAIL: threadlist test\n");
9947 else
9948 {
9949 threadref *scan = threadlist;
9950 threadref *limit = scan + result_count;
9951
9952 while (scan < limit)
9953 output_threadid (" thread ", scan++);
9954 }
9955}
9956
9957void
fba45db2 9958display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9959{
9960 output_threadid ("Threadid: ", &info->threadid);
9961 printf_filtered ("Name: %s\n ", info->shortname);
9962 printf_filtered ("State: %s\n", info->display);
9963 printf_filtered ("other: %s\n\n", info->more_display);
9964}
9965
9966int
fba45db2 9967get_and_display_threadinfo (threadref *ref)
c906108c
SS
9968{
9969 int result;
9970 int set;
9971 struct gdb_ext_thread_info threadinfo;
9972
9973 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9974 | TAG_MOREDISPLAY | TAG_DISPLAY;
9975 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9976 display_thread_info (&threadinfo);
9977 return result;
9978}
9979
9980static void
fba45db2 9981threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9982{
9983 int athread = SAMPLE_THREAD;
9984 threadref thread;
9985 int set;
9986
9987 int_to_threadref (&thread, athread);
9988 printf_filtered ("Remote Threadinfo test\n");
9989 if (!get_and_display_threadinfo (&thread))
9990 printf_filtered ("FAIL cannot get thread info\n");
9991}
9992
9993static int
fba45db2 9994thread_display_step (threadref *ref, void *context)
c906108c
SS
9995{
9996 /* output_threadid(" threadstep ",ref); *//* simple test */
9997 return get_and_display_threadinfo (ref);
9998}
9999
10000static void
fba45db2 10001threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10002{
10003 printf_filtered ("Remote Threadlist update test\n");
10004 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10005}
10006
10007static void
10008init_remote_threadtests (void)
10009{
3e43a32a
MS
10010 add_com ("tlist", class_obscure, threadlist_test_cmd,
10011 _("Fetch and print the remote list of "
10012 "thread identifiers, one pkt only"));
c906108c 10013 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10014 _("Fetch and display info about one thread"));
c906108c 10015 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10016 _("Test setting to a different thread"));
c906108c 10017 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10018 _("Iterate through updating all remote thread info"));
c906108c 10019 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10020 _(" Remote thread alive test "));
c906108c
SS
10021}
10022
10023#endif /* 0 */
10024
f3fb8c85
MS
10025/* Convert a thread ID to a string. Returns the string in a static
10026 buffer. */
10027
10028static char *
117de6a9 10029remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10030{
79d7f229 10031 static char buf[64];
82f73884 10032 struct remote_state *rs = get_remote_state ();
f3fb8c85 10033
7cee1e54
PA
10034 if (ptid_equal (ptid, null_ptid))
10035 return normal_pid_to_str (ptid);
10036 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10037 {
10038 /* Printing an inferior target id. */
10039
10040 /* When multi-process extensions are off, there's no way in the
10041 remote protocol to know the remote process id, if there's any
10042 at all. There's one exception --- when we're connected with
10043 target extended-remote, and we manually attached to a process
10044 with "attach PID". We don't record anywhere a flag that
10045 allows us to distinguish that case from the case of
10046 connecting with extended-remote and the stub already being
10047 attached to a process, and reporting yes to qAttached, hence
10048 no smart special casing here. */
10049 if (!remote_multi_process_p (rs))
10050 {
10051 xsnprintf (buf, sizeof buf, "Remote target");
10052 return buf;
10053 }
10054
10055 return normal_pid_to_str (ptid);
82f73884 10056 }
ecd0ada5 10057 else
79d7f229 10058 {
ecd0ada5
PA
10059 if (ptid_equal (magic_null_ptid, ptid))
10060 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 10061 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
10062 if (ptid_get_lwp (ptid) == 0)
10063 return normal_pid_to_str (ptid);
10064 else
10065 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10066 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10067 else
10068 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10069 ptid_get_lwp (ptid));
79d7f229
PA
10070 return buf;
10071 }
f3fb8c85
MS
10072}
10073
38691318
KB
10074/* Get the address of the thread local variable in OBJFILE which is
10075 stored at OFFSET within the thread local storage for thread PTID. */
10076
10077static CORE_ADDR
117de6a9
PA
10078remote_get_thread_local_address (struct target_ops *ops,
10079 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10080{
4082afcc 10081 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10082 {
10083 struct remote_state *rs = get_remote_state ();
6d820c5c 10084 char *p = rs->buf;
82f73884 10085 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10086 enum packet_result result;
38691318
KB
10087
10088 strcpy (p, "qGetTLSAddr:");
10089 p += strlen (p);
82f73884 10090 p = write_ptid (p, endp, ptid);
38691318
KB
10091 *p++ = ',';
10092 p += hexnumstr (p, offset);
10093 *p++ = ',';
10094 p += hexnumstr (p, lm);
10095 *p++ = '\0';
10096
6d820c5c
DJ
10097 putpkt (rs->buf);
10098 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10099 result = packet_ok (rs->buf,
10100 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10101 if (result == PACKET_OK)
38691318
KB
10102 {
10103 ULONGEST result;
10104
6d820c5c 10105 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10106 return result;
10107 }
571dd617 10108 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10109 throw_error (TLS_GENERIC_ERROR,
10110 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10111 else
109c3e39
AC
10112 throw_error (TLS_GENERIC_ERROR,
10113 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10114 }
10115 else
109c3e39
AC
10116 throw_error (TLS_GENERIC_ERROR,
10117 _("TLS not supported or disabled on this target"));
38691318
KB
10118 /* Not reached. */
10119 return 0;
10120}
10121
711e434b
PM
10122/* Provide thread local base, i.e. Thread Information Block address.
10123 Returns 1 if ptid is found and thread_local_base is non zero. */
10124
70221824 10125static int
bd7ae0f5 10126remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10127{
4082afcc 10128 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10129 {
10130 struct remote_state *rs = get_remote_state ();
10131 char *p = rs->buf;
10132 char *endp = rs->buf + get_remote_packet_size ();
10133 enum packet_result result;
10134
10135 strcpy (p, "qGetTIBAddr:");
10136 p += strlen (p);
10137 p = write_ptid (p, endp, ptid);
10138 *p++ = '\0';
10139
10140 putpkt (rs->buf);
10141 getpkt (&rs->buf, &rs->buf_size, 0);
10142 result = packet_ok (rs->buf,
10143 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10144 if (result == PACKET_OK)
10145 {
10146 ULONGEST result;
10147
10148 unpack_varlen_hex (rs->buf, &result);
10149 if (addr)
10150 *addr = (CORE_ADDR) result;
10151 return 1;
10152 }
10153 else if (result == PACKET_UNKNOWN)
10154 error (_("Remote target doesn't support qGetTIBAddr packet"));
10155 else
10156 error (_("Remote target failed to process qGetTIBAddr request"));
10157 }
10158 else
10159 error (_("qGetTIBAddr not supported or disabled on this target"));
10160 /* Not reached. */
10161 return 0;
10162}
10163
29709017
DJ
10164/* Support for inferring a target description based on the current
10165 architecture and the size of a 'g' packet. While the 'g' packet
10166 can have any size (since optional registers can be left off the
10167 end), some sizes are easily recognizable given knowledge of the
10168 approximate architecture. */
10169
10170struct remote_g_packet_guess
10171{
10172 int bytes;
10173 const struct target_desc *tdesc;
10174};
10175typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10176DEF_VEC_O(remote_g_packet_guess_s);
10177
10178struct remote_g_packet_data
10179{
10180 VEC(remote_g_packet_guess_s) *guesses;
10181};
10182
10183static struct gdbarch_data *remote_g_packet_data_handle;
10184
10185static void *
10186remote_g_packet_data_init (struct obstack *obstack)
10187{
10188 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10189}
10190
10191void
10192register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10193 const struct target_desc *tdesc)
10194{
10195 struct remote_g_packet_data *data
10196 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10197 struct remote_g_packet_guess new_guess, *guess;
10198 int ix;
10199
10200 gdb_assert (tdesc != NULL);
10201
10202 for (ix = 0;
10203 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10204 ix++)
10205 if (guess->bytes == bytes)
10206 internal_error (__FILE__, __LINE__,
9b20d036 10207 _("Duplicate g packet description added for size %d"),
29709017
DJ
10208 bytes);
10209
10210 new_guess.bytes = bytes;
10211 new_guess.tdesc = tdesc;
10212 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10213}
10214
d962ef82
DJ
10215/* Return 1 if remote_read_description would do anything on this target
10216 and architecture, 0 otherwise. */
10217
10218static int
10219remote_read_description_p (struct target_ops *target)
10220{
10221 struct remote_g_packet_data *data
f5656ead 10222 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
10223
10224 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10225 return 1;
10226
10227 return 0;
10228}
10229
29709017
DJ
10230static const struct target_desc *
10231remote_read_description (struct target_ops *target)
10232{
10233 struct remote_g_packet_data *data
f5656ead 10234 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 10235
d962ef82
DJ
10236 /* Do not try this during initial connection, when we do not know
10237 whether there is a running but stopped thread. */
10238 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10239 return target->beneath->to_read_description (target->beneath);
d962ef82 10240
29709017
DJ
10241 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10242 {
10243 struct remote_g_packet_guess *guess;
10244 int ix;
10245 int bytes = send_g_packet ();
10246
10247 for (ix = 0;
10248 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10249 ix++)
10250 if (guess->bytes == bytes)
10251 return guess->tdesc;
10252
10253 /* We discard the g packet. A minor optimization would be to
10254 hold on to it, and fill the register cache once we have selected
10255 an architecture, but it's too tricky to do safely. */
10256 }
10257
2117c711 10258 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10259}
10260
a6b151f1
DJ
10261/* Remote file transfer support. This is host-initiated I/O, not
10262 target-initiated; for target-initiated, see remote-fileio.c. */
10263
10264/* If *LEFT is at least the length of STRING, copy STRING to
10265 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10266 decrease *LEFT. Otherwise raise an error. */
10267
10268static void
10269remote_buffer_add_string (char **buffer, int *left, char *string)
10270{
10271 int len = strlen (string);
10272
10273 if (len > *left)
10274 error (_("Packet too long for target."));
10275
10276 memcpy (*buffer, string, len);
10277 *buffer += len;
10278 *left -= len;
10279
10280 /* NUL-terminate the buffer as a convenience, if there is
10281 room. */
10282 if (*left)
10283 **buffer = '\0';
10284}
10285
10286/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10287 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10288 decrease *LEFT. Otherwise raise an error. */
10289
10290static void
10291remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10292 int len)
10293{
10294 if (2 * len > *left)
10295 error (_("Packet too long for target."));
10296
10297 bin2hex (bytes, *buffer, len);
10298 *buffer += 2 * len;
10299 *left -= 2 * len;
10300
10301 /* NUL-terminate the buffer as a convenience, if there is
10302 room. */
10303 if (*left)
10304 **buffer = '\0';
10305}
10306
10307/* If *LEFT is large enough, convert VALUE to hex and add it to
10308 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10309 decrease *LEFT. Otherwise raise an error. */
10310
10311static void
10312remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10313{
10314 int len = hexnumlen (value);
10315
10316 if (len > *left)
10317 error (_("Packet too long for target."));
10318
10319 hexnumstr (*buffer, value);
10320 *buffer += len;
10321 *left -= len;
10322
10323 /* NUL-terminate the buffer as a convenience, if there is
10324 room. */
10325 if (*left)
10326 **buffer = '\0';
10327}
10328
10329/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10330 value, *REMOTE_ERRNO to the remote error number or zero if none
10331 was included, and *ATTACHMENT to point to the start of the annex
10332 if any. The length of the packet isn't needed here; there may
10333 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10334
10335 Return 0 if the packet could be parsed, -1 if it could not. If
10336 -1 is returned, the other variables may not be initialized. */
10337
10338static int
10339remote_hostio_parse_result (char *buffer, int *retcode,
10340 int *remote_errno, char **attachment)
10341{
10342 char *p, *p2;
10343
10344 *remote_errno = 0;
10345 *attachment = NULL;
10346
10347 if (buffer[0] != 'F')
10348 return -1;
10349
10350 errno = 0;
10351 *retcode = strtol (&buffer[1], &p, 16);
10352 if (errno != 0 || p == &buffer[1])
10353 return -1;
10354
10355 /* Check for ",errno". */
10356 if (*p == ',')
10357 {
10358 errno = 0;
10359 *remote_errno = strtol (p + 1, &p2, 16);
10360 if (errno != 0 || p + 1 == p2)
10361 return -1;
10362 p = p2;
10363 }
10364
10365 /* Check for ";attachment". If there is no attachment, the
10366 packet should end here. */
10367 if (*p == ';')
10368 {
10369 *attachment = p + 1;
10370 return 0;
10371 }
10372 else if (*p == '\0')
10373 return 0;
10374 else
10375 return -1;
10376}
10377
10378/* Send a prepared I/O packet to the target and read its response.
10379 The prepared packet is in the global RS->BUF before this function
10380 is called, and the answer is there when we return.
10381
10382 COMMAND_BYTES is the length of the request to send, which may include
10383 binary data. WHICH_PACKET is the packet configuration to check
10384 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10385 is set to the error number and -1 is returned. Otherwise the value
10386 returned by the function is returned.
10387
10388 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10389 attachment is expected; an error will be reported if there's a
10390 mismatch. If one is found, *ATTACHMENT will be set to point into
10391 the packet buffer and *ATTACHMENT_LEN will be set to the
10392 attachment's length. */
10393
10394static int
10395remote_hostio_send_command (int command_bytes, int which_packet,
10396 int *remote_errno, char **attachment,
10397 int *attachment_len)
10398{
10399 struct remote_state *rs = get_remote_state ();
10400 int ret, bytes_read;
10401 char *attachment_tmp;
10402
5d93a237 10403 if (!rs->remote_desc
4082afcc 10404 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10405 {
10406 *remote_errno = FILEIO_ENOSYS;
10407 return -1;
10408 }
10409
10410 putpkt_binary (rs->buf, command_bytes);
10411 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10412
10413 /* If it timed out, something is wrong. Don't try to parse the
10414 buffer. */
10415 if (bytes_read < 0)
10416 {
10417 *remote_errno = FILEIO_EINVAL;
10418 return -1;
10419 }
10420
10421 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10422 {
10423 case PACKET_ERROR:
10424 *remote_errno = FILEIO_EINVAL;
10425 return -1;
10426 case PACKET_UNKNOWN:
10427 *remote_errno = FILEIO_ENOSYS;
10428 return -1;
10429 case PACKET_OK:
10430 break;
10431 }
10432
10433 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10434 &attachment_tmp))
10435 {
10436 *remote_errno = FILEIO_EINVAL;
10437 return -1;
10438 }
10439
10440 /* Make sure we saw an attachment if and only if we expected one. */
10441 if ((attachment_tmp == NULL && attachment != NULL)
10442 || (attachment_tmp != NULL && attachment == NULL))
10443 {
10444 *remote_errno = FILEIO_EINVAL;
10445 return -1;
10446 }
10447
10448 /* If an attachment was found, it must point into the packet buffer;
10449 work out how many bytes there were. */
10450 if (attachment_tmp != NULL)
10451 {
10452 *attachment = attachment_tmp;
10453 *attachment_len = bytes_read - (*attachment - rs->buf);
10454 }
10455
10456 return ret;
10457}
10458
80152258
PA
10459/* Invalidate the readahead cache. */
10460
10461static void
10462readahead_cache_invalidate (void)
10463{
10464 struct remote_state *rs = get_remote_state ();
10465
10466 rs->readahead_cache.fd = -1;
10467}
10468
10469/* Invalidate the readahead cache if it is holding data for FD. */
10470
10471static void
10472readahead_cache_invalidate_fd (int fd)
10473{
10474 struct remote_state *rs = get_remote_state ();
10475
10476 if (rs->readahead_cache.fd == fd)
10477 rs->readahead_cache.fd = -1;
10478}
10479
15a201c8
GB
10480/* Set the filesystem remote_hostio functions that take FILENAME
10481 arguments will use. Return 0 on success, or -1 if an error
10482 occurs (and set *REMOTE_ERRNO). */
10483
10484static int
10485remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10486{
10487 struct remote_state *rs = get_remote_state ();
10488 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10489 char *p = rs->buf;
10490 int left = get_remote_packet_size () - 1;
10491 char arg[9];
10492 int ret;
10493
10494 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10495 return 0;
10496
10497 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10498 return 0;
10499
10500 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10501
10502 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10503 remote_buffer_add_string (&p, &left, arg);
10504
10505 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10506 remote_errno, NULL, NULL);
10507
10508 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10509 return 0;
10510
10511 if (ret == 0)
10512 rs->fs_pid = required_pid;
10513
10514 return ret;
10515}
10516
12e2a5fd 10517/* Implementation of to_fileio_open. */
a6b151f1
DJ
10518
10519static int
cd897586 10520remote_hostio_open (struct target_ops *self,
07c138c8 10521 struct inferior *inf, const char *filename,
4313b8c0
GB
10522 int flags, int mode, int warn_if_slow,
10523 int *remote_errno)
a6b151f1
DJ
10524{
10525 struct remote_state *rs = get_remote_state ();
10526 char *p = rs->buf;
10527 int left = get_remote_packet_size () - 1;
10528
4313b8c0
GB
10529 if (warn_if_slow)
10530 {
10531 static int warning_issued = 0;
10532
10533 printf_unfiltered (_("Reading %s from remote target...\n"),
10534 filename);
10535
10536 if (!warning_issued)
10537 {
10538 warning (_("File transfers from remote targets can be slow."
10539 " Use \"set sysroot\" to access files locally"
10540 " instead."));
10541 warning_issued = 1;
10542 }
10543 }
10544
15a201c8
GB
10545 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10546 return -1;
10547
a6b151f1
DJ
10548 remote_buffer_add_string (&p, &left, "vFile:open:");
10549
10550 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10551 strlen (filename));
10552 remote_buffer_add_string (&p, &left, ",");
10553
10554 remote_buffer_add_int (&p, &left, flags);
10555 remote_buffer_add_string (&p, &left, ",");
10556
10557 remote_buffer_add_int (&p, &left, mode);
10558
10559 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10560 remote_errno, NULL, NULL);
10561}
10562
12e2a5fd 10563/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10564
10565static int
0d866f62
TT
10566remote_hostio_pwrite (struct target_ops *self,
10567 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10568 ULONGEST offset, int *remote_errno)
10569{
10570 struct remote_state *rs = get_remote_state ();
10571 char *p = rs->buf;
10572 int left = get_remote_packet_size ();
10573 int out_len;
10574
80152258
PA
10575 readahead_cache_invalidate_fd (fd);
10576
a6b151f1
DJ
10577 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10578
10579 remote_buffer_add_int (&p, &left, fd);
10580 remote_buffer_add_string (&p, &left, ",");
10581
10582 remote_buffer_add_int (&p, &left, offset);
10583 remote_buffer_add_string (&p, &left, ",");
10584
124e13d9 10585 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10586 get_remote_packet_size () - (p - rs->buf));
10587
10588 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10589 remote_errno, NULL, NULL);
10590}
10591
80152258
PA
10592/* Helper for the implementation of to_fileio_pread. Read the file
10593 from the remote side with vFile:pread. */
a6b151f1
DJ
10594
10595static int
80152258
PA
10596remote_hostio_pread_vFile (struct target_ops *self,
10597 int fd, gdb_byte *read_buf, int len,
10598 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
10599{
10600 struct remote_state *rs = get_remote_state ();
10601 char *p = rs->buf;
10602 char *attachment;
10603 int left = get_remote_packet_size ();
10604 int ret, attachment_len;
10605 int read_len;
10606
10607 remote_buffer_add_string (&p, &left, "vFile:pread:");
10608
10609 remote_buffer_add_int (&p, &left, fd);
10610 remote_buffer_add_string (&p, &left, ",");
10611
10612 remote_buffer_add_int (&p, &left, len);
10613 remote_buffer_add_string (&p, &left, ",");
10614
10615 remote_buffer_add_int (&p, &left, offset);
10616
10617 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10618 remote_errno, &attachment,
10619 &attachment_len);
10620
10621 if (ret < 0)
10622 return ret;
10623
bc20a4af 10624 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
10625 read_buf, len);
10626 if (read_len != ret)
10627 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10628
10629 return ret;
10630}
10631
80152258
PA
10632/* Serve pread from the readahead cache. Returns number of bytes
10633 read, or 0 if the request can't be served from the cache. */
10634
10635static int
10636remote_hostio_pread_from_cache (struct remote_state *rs,
10637 int fd, gdb_byte *read_buf, size_t len,
10638 ULONGEST offset)
10639{
10640 struct readahead_cache *cache = &rs->readahead_cache;
10641
10642 if (cache->fd == fd
10643 && cache->offset <= offset
10644 && offset < cache->offset + cache->bufsize)
10645 {
10646 ULONGEST max = cache->offset + cache->bufsize;
10647
10648 if (offset + len > max)
10649 len = max - offset;
10650
10651 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10652 return len;
10653 }
10654
10655 return 0;
10656}
10657
10658/* Implementation of to_fileio_pread. */
10659
10660static int
10661remote_hostio_pread (struct target_ops *self,
10662 int fd, gdb_byte *read_buf, int len,
10663 ULONGEST offset, int *remote_errno)
10664{
10665 int ret;
10666 struct remote_state *rs = get_remote_state ();
10667 struct readahead_cache *cache = &rs->readahead_cache;
10668
10669 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10670 if (ret > 0)
10671 {
10672 cache->hit_count++;
10673
10674 if (remote_debug)
10675 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10676 pulongest (cache->hit_count));
10677 return ret;
10678 }
10679
10680 cache->miss_count++;
10681 if (remote_debug)
10682 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10683 pulongest (cache->miss_count));
10684
10685 cache->fd = fd;
10686 cache->offset = offset;
10687 cache->bufsize = get_remote_packet_size ();
10688 cache->buf = xrealloc (cache->buf, cache->bufsize);
10689
10690 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10691 cache->offset, remote_errno);
10692 if (ret <= 0)
10693 {
10694 readahead_cache_invalidate_fd (fd);
10695 return ret;
10696 }
10697
10698 cache->bufsize = ret;
10699 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10700}
10701
12e2a5fd 10702/* Implementation of to_fileio_close. */
a6b151f1
DJ
10703
10704static int
df39ea25 10705remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
10706{
10707 struct remote_state *rs = get_remote_state ();
10708 char *p = rs->buf;
10709 int left = get_remote_packet_size () - 1;
10710
80152258
PA
10711 readahead_cache_invalidate_fd (fd);
10712
a6b151f1
DJ
10713 remote_buffer_add_string (&p, &left, "vFile:close:");
10714
10715 remote_buffer_add_int (&p, &left, fd);
10716
10717 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10718 remote_errno, NULL, NULL);
10719}
10720
12e2a5fd 10721/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
10722
10723static int
dbbca37d 10724remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
10725 struct inferior *inf, const char *filename,
10726 int *remote_errno)
a6b151f1
DJ
10727{
10728 struct remote_state *rs = get_remote_state ();
10729 char *p = rs->buf;
10730 int left = get_remote_packet_size () - 1;
10731
15a201c8
GB
10732 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10733 return -1;
10734
a6b151f1
DJ
10735 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10736
10737 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10738 strlen (filename));
10739
10740 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10741 remote_errno, NULL, NULL);
10742}
10743
12e2a5fd 10744/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
10745
10746static char *
fab5aa7c 10747remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
10748 struct inferior *inf, const char *filename,
10749 int *remote_errno)
b9e7b9c3
UW
10750{
10751 struct remote_state *rs = get_remote_state ();
10752 char *p = rs->buf;
10753 char *attachment;
10754 int left = get_remote_packet_size ();
10755 int len, attachment_len;
10756 int read_len;
10757 char *ret;
10758
15a201c8
GB
10759 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10760 return NULL;
10761
b9e7b9c3
UW
10762 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10763
10764 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10765 strlen (filename));
10766
10767 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10768 remote_errno, &attachment,
10769 &attachment_len);
10770
10771 if (len < 0)
10772 return NULL;
10773
10774 ret = xmalloc (len + 1);
10775
bc20a4af
PA
10776 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10777 (gdb_byte *) ret, len);
b9e7b9c3
UW
10778 if (read_len != len)
10779 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10780
10781 ret[len] = '\0';
10782 return ret;
10783}
10784
12e2a5fd 10785/* Implementation of to_fileio_fstat. */
0a93529c
GB
10786
10787static int
10788remote_hostio_fstat (struct target_ops *self,
10789 int fd, struct stat *st,
10790 int *remote_errno)
10791{
10792 struct remote_state *rs = get_remote_state ();
10793 char *p = rs->buf;
10794 int left = get_remote_packet_size ();
10795 int attachment_len, ret;
10796 char *attachment;
10797 struct fio_stat fst;
10798 int read_len;
10799
464b0089
GB
10800 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10801
10802 remote_buffer_add_int (&p, &left, fd);
10803
10804 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10805 remote_errno, &attachment,
10806 &attachment_len);
10807 if (ret < 0)
0a93529c 10808 {
464b0089
GB
10809 if (*remote_errno != FILEIO_ENOSYS)
10810 return ret;
10811
0a93529c
GB
10812 /* Strictly we should return -1, ENOSYS here, but when
10813 "set sysroot remote:" was implemented in August 2008
10814 BFD's need for a stat function was sidestepped with
10815 this hack. This was not remedied until March 2015
10816 so we retain the previous behavior to avoid breaking
10817 compatibility.
10818
10819 Note that the memset is a March 2015 addition; older
10820 GDBs set st_size *and nothing else* so the structure
10821 would have garbage in all other fields. This might
10822 break something but retaining the previous behavior
10823 here would be just too wrong. */
10824
10825 memset (st, 0, sizeof (struct stat));
10826 st->st_size = INT_MAX;
10827 return 0;
10828 }
10829
0a93529c
GB
10830 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10831 (gdb_byte *) &fst, sizeof (fst));
10832
10833 if (read_len != ret)
10834 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10835
10836 if (read_len != sizeof (fst))
10837 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10838 read_len, (int) sizeof (fst));
10839
10840 remote_fileio_to_host_stat (&fst, st);
10841
10842 return 0;
10843}
10844
12e2a5fd 10845/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
10846
10847static int
10848remote_filesystem_is_local (struct target_ops *self)
10849{
10850 /* Valgrind GDB presents itself as a remote target but works
10851 on the local filesystem: it does not implement remote get
10852 and users are not expected to set a sysroot. To handle
10853 this case we treat the remote filesystem as local if the
10854 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10855 does not support vFile:open. */
a3be80c3 10856 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
10857 {
10858 enum packet_support ps = packet_support (PACKET_vFile_open);
10859
10860 if (ps == PACKET_SUPPORT_UNKNOWN)
10861 {
10862 int fd, remote_errno;
10863
10864 /* Try opening a file to probe support. The supplied
10865 filename is irrelevant, we only care about whether
10866 the stub recognizes the packet or not. */
07c138c8 10867 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 10868 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
10869 &remote_errno);
10870
10871 if (fd >= 0)
10872 remote_hostio_close (self, fd, &remote_errno);
10873
10874 ps = packet_support (PACKET_vFile_open);
10875 }
10876
10877 if (ps == PACKET_DISABLE)
10878 {
10879 static int warning_issued = 0;
10880
10881 if (!warning_issued)
10882 {
10883 warning (_("remote target does not support file"
10884 " transfer, attempting to access files"
10885 " from local filesystem."));
10886 warning_issued = 1;
10887 }
10888
10889 return 1;
10890 }
10891 }
10892
10893 return 0;
10894}
10895
a6b151f1
DJ
10896static int
10897remote_fileio_errno_to_host (int errnum)
10898{
10899 switch (errnum)
10900 {
10901 case FILEIO_EPERM:
10902 return EPERM;
10903 case FILEIO_ENOENT:
10904 return ENOENT;
10905 case FILEIO_EINTR:
10906 return EINTR;
10907 case FILEIO_EIO:
10908 return EIO;
10909 case FILEIO_EBADF:
10910 return EBADF;
10911 case FILEIO_EACCES:
10912 return EACCES;
10913 case FILEIO_EFAULT:
10914 return EFAULT;
10915 case FILEIO_EBUSY:
10916 return EBUSY;
10917 case FILEIO_EEXIST:
10918 return EEXIST;
10919 case FILEIO_ENODEV:
10920 return ENODEV;
10921 case FILEIO_ENOTDIR:
10922 return ENOTDIR;
10923 case FILEIO_EISDIR:
10924 return EISDIR;
10925 case FILEIO_EINVAL:
10926 return EINVAL;
10927 case FILEIO_ENFILE:
10928 return ENFILE;
10929 case FILEIO_EMFILE:
10930 return EMFILE;
10931 case FILEIO_EFBIG:
10932 return EFBIG;
10933 case FILEIO_ENOSPC:
10934 return ENOSPC;
10935 case FILEIO_ESPIPE:
10936 return ESPIPE;
10937 case FILEIO_EROFS:
10938 return EROFS;
10939 case FILEIO_ENOSYS:
10940 return ENOSYS;
10941 case FILEIO_ENAMETOOLONG:
10942 return ENAMETOOLONG;
10943 }
10944 return -1;
10945}
10946
10947static char *
10948remote_hostio_error (int errnum)
10949{
10950 int host_error = remote_fileio_errno_to_host (errnum);
10951
10952 if (host_error == -1)
10953 error (_("Unknown remote I/O error %d"), errnum);
10954 else
10955 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10956}
10957
a6b151f1
DJ
10958static void
10959remote_hostio_close_cleanup (void *opaque)
10960{
10961 int fd = *(int *) opaque;
10962 int remote_errno;
10963
df39ea25 10964 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10965}
10966
10967void
10968remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10969{
10970 struct cleanup *back_to, *close_cleanup;
10971 int retcode, fd, remote_errno, bytes, io_size;
10972 FILE *file;
10973 gdb_byte *buffer;
10974 int bytes_in_buffer;
10975 int saw_eof;
10976 ULONGEST offset;
5d93a237 10977 struct remote_state *rs = get_remote_state ();
a6b151f1 10978
5d93a237 10979 if (!rs->remote_desc)
a6b151f1
DJ
10980 error (_("command can only be used with remote target"));
10981
614c279d 10982 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10983 if (file == NULL)
10984 perror_with_name (local_file);
7c8a8b04 10985 back_to = make_cleanup_fclose (file);
a6b151f1 10986
07c138c8 10987 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 10988 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 10989 | FILEIO_O_TRUNC),
4313b8c0 10990 0700, 0, &remote_errno);
a6b151f1
DJ
10991 if (fd == -1)
10992 remote_hostio_error (remote_errno);
10993
10994 /* Send up to this many bytes at once. They won't all fit in the
10995 remote packet limit, so we'll transfer slightly fewer. */
10996 io_size = get_remote_packet_size ();
10997 buffer = xmalloc (io_size);
10998 make_cleanup (xfree, buffer);
10999
11000 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11001
11002 bytes_in_buffer = 0;
11003 saw_eof = 0;
11004 offset = 0;
11005 while (bytes_in_buffer || !saw_eof)
11006 {
11007 if (!saw_eof)
11008 {
3e43a32a
MS
11009 bytes = fread (buffer + bytes_in_buffer, 1,
11010 io_size - bytes_in_buffer,
a6b151f1
DJ
11011 file);
11012 if (bytes == 0)
11013 {
11014 if (ferror (file))
11015 error (_("Error reading %s."), local_file);
11016 else
11017 {
11018 /* EOF. Unless there is something still in the
11019 buffer from the last iteration, we are done. */
11020 saw_eof = 1;
11021 if (bytes_in_buffer == 0)
11022 break;
11023 }
11024 }
11025 }
11026 else
11027 bytes = 0;
11028
11029 bytes += bytes_in_buffer;
11030 bytes_in_buffer = 0;
11031
0d866f62
TT
11032 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11033 fd, buffer, bytes,
3e43a32a 11034 offset, &remote_errno);
a6b151f1
DJ
11035
11036 if (retcode < 0)
11037 remote_hostio_error (remote_errno);
11038 else if (retcode == 0)
11039 error (_("Remote write of %d bytes returned 0!"), bytes);
11040 else if (retcode < bytes)
11041 {
11042 /* Short write. Save the rest of the read data for the next
11043 write. */
11044 bytes_in_buffer = bytes - retcode;
11045 memmove (buffer, buffer + retcode, bytes_in_buffer);
11046 }
11047
11048 offset += retcode;
11049 }
11050
11051 discard_cleanups (close_cleanup);
df39ea25 11052 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11053 remote_hostio_error (remote_errno);
11054
11055 if (from_tty)
11056 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11057 do_cleanups (back_to);
11058}
11059
11060void
11061remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11062{
11063 struct cleanup *back_to, *close_cleanup;
cea39f65 11064 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11065 FILE *file;
11066 gdb_byte *buffer;
11067 ULONGEST offset;
5d93a237 11068 struct remote_state *rs = get_remote_state ();
a6b151f1 11069
5d93a237 11070 if (!rs->remote_desc)
a6b151f1
DJ
11071 error (_("command can only be used with remote target"));
11072
07c138c8 11073 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11074 remote_file, FILEIO_O_RDONLY, 0, 0,
11075 &remote_errno);
a6b151f1
DJ
11076 if (fd == -1)
11077 remote_hostio_error (remote_errno);
11078
614c279d 11079 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11080 if (file == NULL)
11081 perror_with_name (local_file);
7c8a8b04 11082 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11083
11084 /* Send up to this many bytes at once. They won't all fit in the
11085 remote packet limit, so we'll transfer slightly fewer. */
11086 io_size = get_remote_packet_size ();
11087 buffer = xmalloc (io_size);
11088 make_cleanup (xfree, buffer);
11089
11090 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11091
11092 offset = 0;
11093 while (1)
11094 {
a3be983c
TT
11095 bytes = remote_hostio_pread (find_target_at (process_stratum),
11096 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11097 if (bytes == 0)
11098 /* Success, but no bytes, means end-of-file. */
11099 break;
11100 if (bytes == -1)
11101 remote_hostio_error (remote_errno);
11102
11103 offset += bytes;
11104
11105 bytes = fwrite (buffer, 1, bytes, file);
11106 if (bytes == 0)
11107 perror_with_name (local_file);
11108 }
11109
11110 discard_cleanups (close_cleanup);
df39ea25 11111 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11112 remote_hostio_error (remote_errno);
11113
11114 if (from_tty)
11115 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11116 do_cleanups (back_to);
11117}
11118
11119void
11120remote_file_delete (const char *remote_file, int from_tty)
11121{
11122 int retcode, remote_errno;
5d93a237 11123 struct remote_state *rs = get_remote_state ();
a6b151f1 11124
5d93a237 11125 if (!rs->remote_desc)
a6b151f1
DJ
11126 error (_("command can only be used with remote target"));
11127
dbbca37d 11128 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11129 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11130 if (retcode == -1)
11131 remote_hostio_error (remote_errno);
11132
11133 if (from_tty)
11134 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11135}
11136
11137static void
11138remote_put_command (char *args, int from_tty)
11139{
11140 struct cleanup *back_to;
11141 char **argv;
11142
d1a41061
PP
11143 if (args == NULL)
11144 error_no_arg (_("file to put"));
11145
11146 argv = gdb_buildargv (args);
a6b151f1
DJ
11147 back_to = make_cleanup_freeargv (argv);
11148 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11149 error (_("Invalid parameters to remote put"));
11150
11151 remote_file_put (argv[0], argv[1], from_tty);
11152
11153 do_cleanups (back_to);
11154}
11155
11156static void
11157remote_get_command (char *args, int from_tty)
11158{
11159 struct cleanup *back_to;
11160 char **argv;
11161
d1a41061
PP
11162 if (args == NULL)
11163 error_no_arg (_("file to get"));
11164
11165 argv = gdb_buildargv (args);
a6b151f1
DJ
11166 back_to = make_cleanup_freeargv (argv);
11167 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11168 error (_("Invalid parameters to remote get"));
11169
11170 remote_file_get (argv[0], argv[1], from_tty);
11171
11172 do_cleanups (back_to);
11173}
11174
11175static void
11176remote_delete_command (char *args, int from_tty)
11177{
11178 struct cleanup *back_to;
11179 char **argv;
11180
d1a41061
PP
11181 if (args == NULL)
11182 error_no_arg (_("file to delete"));
11183
11184 argv = gdb_buildargv (args);
a6b151f1
DJ
11185 back_to = make_cleanup_freeargv (argv);
11186 if (argv[0] == NULL || argv[1] != NULL)
11187 error (_("Invalid parameters to remote delete"));
11188
11189 remote_file_delete (argv[0], from_tty);
11190
11191 do_cleanups (back_to);
11192}
11193
11194static void
11195remote_command (char *args, int from_tty)
11196{
635c7e8a 11197 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11198}
11199
b2175913 11200static int
19db3e69 11201remote_can_execute_reverse (struct target_ops *self)
b2175913 11202{
4082afcc
PA
11203 if (packet_support (PACKET_bs) == PACKET_ENABLE
11204 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11205 return 1;
11206 else
11207 return 0;
b2175913
MS
11208}
11209
74531fed 11210static int
2a9a2795 11211remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11212{
11213 return 1;
11214}
11215
03583c20 11216static int
2bfc0540 11217remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11218{
11219 /* Only supported in extended mode. */
11220 return 0;
11221}
11222
8a305172 11223static int
86ce2668 11224remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11225{
11226 struct remote_state *rs = get_remote_state ();
a744cf53 11227
901f9912
UW
11228 /* Only extended-remote handles being attached to multiple
11229 processes, even though plain remote can use the multi-process
11230 thread id extensions, so that GDB knows the target process's
11231 PID. */
11232 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
11233}
11234
70221824 11235static int
782b2b07
SS
11236remote_supports_cond_tracepoints (void)
11237{
4082afcc 11238 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11239}
11240
3788aec7 11241static int
efcc2da7 11242remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11243{
4082afcc 11244 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11245}
11246
70221824 11247static int
7a697b8d
SS
11248remote_supports_fast_tracepoints (void)
11249{
4082afcc 11250 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11251}
11252
0fb4aa4b
PA
11253static int
11254remote_supports_static_tracepoints (void)
11255{
4082afcc 11256 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11257}
11258
1e4d1764
YQ
11259static int
11260remote_supports_install_in_trace (void)
11261{
4082afcc 11262 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11263}
11264
d248b706 11265static int
7d178d6a 11266remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11267{
4082afcc
PA
11268 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11269 == PACKET_ENABLE);
d248b706
KY
11270}
11271
3065dfb6 11272static int
6de37a3a 11273remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11274{
4082afcc 11275 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11276}
11277
d3ce09f5 11278static int
78eff0ec 11279remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11280{
4082afcc 11281 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11282}
11283
35b1e5cc 11284static void
ecae04e1 11285remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11286{
11287 putpkt ("QTinit");
11288 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11289 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11290 error (_("Target does not support this command."));
11291}
11292
11293static void free_actions_list (char **actions_list);
11294static void free_actions_list_cleanup_wrapper (void *);
11295static void
11296free_actions_list_cleanup_wrapper (void *al)
11297{
11298 free_actions_list (al);
11299}
11300
11301static void
11302free_actions_list (char **actions_list)
11303{
11304 int ndx;
11305
11306 if (actions_list == 0)
11307 return;
11308
11309 for (ndx = 0; actions_list[ndx]; ndx++)
11310 xfree (actions_list[ndx]);
11311
11312 xfree (actions_list);
11313}
11314
409873ef
SS
11315/* Recursive routine to walk through command list including loops, and
11316 download packets for each command. */
11317
11318static void
11319remote_download_command_source (int num, ULONGEST addr,
11320 struct command_line *cmds)
11321{
11322 struct remote_state *rs = get_remote_state ();
11323 struct command_line *cmd;
11324
11325 for (cmd = cmds; cmd; cmd = cmd->next)
11326 {
0df8b418 11327 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11328 strcpy (rs->buf, "QTDPsrc:");
11329 encode_source_string (num, addr, "cmd", cmd->line,
11330 rs->buf + strlen (rs->buf),
11331 rs->buf_size - strlen (rs->buf));
11332 putpkt (rs->buf);
11333 remote_get_noisy_reply (&target_buf, &target_buf_size);
11334 if (strcmp (target_buf, "OK"))
11335 warning (_("Target does not support source download."));
11336
11337 if (cmd->control_type == while_control
11338 || cmd->control_type == while_stepping_control)
11339 {
11340 remote_download_command_source (num, addr, *cmd->body_list);
11341
0df8b418 11342 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11343 strcpy (rs->buf, "QTDPsrc:");
11344 encode_source_string (num, addr, "cmd", "end",
11345 rs->buf + strlen (rs->buf),
11346 rs->buf_size - strlen (rs->buf));
11347 putpkt (rs->buf);
11348 remote_get_noisy_reply (&target_buf, &target_buf_size);
11349 if (strcmp (target_buf, "OK"))
11350 warning (_("Target does not support source download."));
11351 }
11352 }
11353}
11354
35b1e5cc 11355static void
548f7808 11356remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11357{
bba74b36 11358#define BUF_SIZE 2048
e8ba3115 11359
35b1e5cc 11360 CORE_ADDR tpaddr;
409873ef 11361 char addrbuf[40];
bba74b36 11362 char buf[BUF_SIZE];
35b1e5cc
SS
11363 char **tdp_actions;
11364 char **stepping_actions;
11365 int ndx;
11366 struct cleanup *old_chain = NULL;
11367 struct agent_expr *aexpr;
11368 struct cleanup *aexpr_chain = NULL;
11369 char *pkt;
e8ba3115 11370 struct breakpoint *b = loc->owner;
d9b3f62e 11371 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11372
dc673c81 11373 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11374 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11375 tdp_actions);
11376 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11377 stepping_actions);
11378
11379 tpaddr = loc->address;
11380 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11381 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11382 addrbuf, /* address */
11383 (b->enable_state == bp_enabled ? 'E' : 'D'),
11384 t->step_count, t->pass_count);
e8ba3115
YQ
11385 /* Fast tracepoints are mostly handled by the target, but we can
11386 tell the target how big of an instruction block should be moved
11387 around. */
11388 if (b->type == bp_fast_tracepoint)
11389 {
11390 /* Only test for support at download time; we may not know
11391 target capabilities at definition time. */
11392 if (remote_supports_fast_tracepoints ())
35b1e5cc 11393 {
6b940e6a
PL
11394 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11395 NULL))
bba74b36 11396 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11397 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11398 else
e8ba3115
YQ
11399 /* If it passed validation at definition but fails now,
11400 something is very wrong. */
11401 internal_error (__FILE__, __LINE__,
11402 _("Fast tracepoint not "
11403 "valid during download"));
35b1e5cc 11404 }
e8ba3115
YQ
11405 else
11406 /* Fast tracepoints are functionally identical to regular
11407 tracepoints, so don't take lack of support as a reason to
11408 give up on the trace run. */
11409 warning (_("Target does not support fast tracepoints, "
11410 "downloading %d as regular tracepoint"), b->number);
11411 }
11412 else if (b->type == bp_static_tracepoint)
11413 {
11414 /* Only test for support at download time; we may not know
11415 target capabilities at definition time. */
11416 if (remote_supports_static_tracepoints ())
0fb4aa4b 11417 {
e8ba3115 11418 struct static_tracepoint_marker marker;
0fb4aa4b 11419
e8ba3115
YQ
11420 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11421 strcat (buf, ":S");
0fb4aa4b 11422 else
e8ba3115 11423 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11424 }
e8ba3115
YQ
11425 else
11426 /* Fast tracepoints are functionally identical to regular
11427 tracepoints, so don't take lack of support as a reason
11428 to give up on the trace run. */
11429 error (_("Target does not support static tracepoints"));
11430 }
11431 /* If the tracepoint has a conditional, make it into an agent
11432 expression and append to the definition. */
11433 if (loc->cond)
11434 {
11435 /* Only test support at download time, we may not know target
11436 capabilities at definition time. */
11437 if (remote_supports_cond_tracepoints ())
35b1e5cc 11438 {
e8ba3115
YQ
11439 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11440 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11441 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11442 aexpr->len);
e8ba3115
YQ
11443 pkt = buf + strlen (buf);
11444 for (ndx = 0; ndx < aexpr->len; ++ndx)
11445 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11446 *pkt = '\0';
11447 do_cleanups (aexpr_chain);
35b1e5cc 11448 }
e8ba3115
YQ
11449 else
11450 warning (_("Target does not support conditional tracepoints, "
11451 "ignoring tp %d cond"), b->number);
11452 }
35b1e5cc 11453
d9b3f62e 11454 if (b->commands || *default_collect)
e8ba3115
YQ
11455 strcat (buf, "-");
11456 putpkt (buf);
11457 remote_get_noisy_reply (&target_buf, &target_buf_size);
11458 if (strcmp (target_buf, "OK"))
11459 error (_("Target does not support tracepoints."));
35b1e5cc 11460
e8ba3115
YQ
11461 /* do_single_steps (t); */
11462 if (tdp_actions)
11463 {
11464 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11465 {
e8ba3115 11466 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11467 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11468 b->number, addrbuf, /* address */
11469 tdp_actions[ndx],
11470 ((tdp_actions[ndx + 1] || stepping_actions)
11471 ? '-' : 0));
e8ba3115
YQ
11472 putpkt (buf);
11473 remote_get_noisy_reply (&target_buf,
11474 &target_buf_size);
11475 if (strcmp (target_buf, "OK"))
11476 error (_("Error on target while setting tracepoints."));
35b1e5cc 11477 }
e8ba3115
YQ
11478 }
11479 if (stepping_actions)
11480 {
11481 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11482 {
e8ba3115 11483 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11484 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11485 b->number, addrbuf, /* address */
11486 ((ndx == 0) ? "S" : ""),
11487 stepping_actions[ndx],
11488 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11489 putpkt (buf);
11490 remote_get_noisy_reply (&target_buf,
11491 &target_buf_size);
11492 if (strcmp (target_buf, "OK"))
11493 error (_("Error on target while setting tracepoints."));
35b1e5cc 11494 }
e8ba3115 11495 }
409873ef 11496
4082afcc 11497 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11498 {
f00aae0f 11499 if (b->location != NULL)
409873ef 11500 {
e8ba3115 11501 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11502 encode_source_string (b->number, loc->address, "at",
11503 event_location_to_string (b->location),
11504 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11505 putpkt (buf);
11506 remote_get_noisy_reply (&target_buf, &target_buf_size);
11507 if (strcmp (target_buf, "OK"))
11508 warning (_("Target does not support source download."));
409873ef 11509 }
e8ba3115
YQ
11510 if (b->cond_string)
11511 {
11512 strcpy (buf, "QTDPsrc:");
11513 encode_source_string (b->number, loc->address,
11514 "cond", b->cond_string, buf + strlen (buf),
11515 2048 - strlen (buf));
11516 putpkt (buf);
11517 remote_get_noisy_reply (&target_buf, &target_buf_size);
11518 if (strcmp (target_buf, "OK"))
11519 warning (_("Target does not support source download."));
11520 }
11521 remote_download_command_source (b->number, loc->address,
11522 breakpoint_commands (b));
35b1e5cc 11523 }
e8ba3115
YQ
11524
11525 do_cleanups (old_chain);
35b1e5cc
SS
11526}
11527
1e4d1764 11528static int
a52a8357 11529remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11530{
1e51243a
PA
11531 struct remote_state *rs = get_remote_state ();
11532 struct trace_status *ts;
11533 int status;
11534
11535 /* Don't try to install tracepoints until we've relocated our
11536 symbols, and fetched and merged the target's tracepoint list with
11537 ours. */
11538 if (rs->starting_up)
11539 return 0;
11540
11541 ts = current_trace_status ();
8bd200f1 11542 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11543
11544 if (status == -1 || !ts->running_known || !ts->running)
11545 return 0;
11546
11547 /* If we are in a tracing experiment, but remote stub doesn't support
11548 installing tracepoint in trace, we have to return. */
11549 if (!remote_supports_install_in_trace ())
11550 return 0;
11551
11552 return 1;
11553}
11554
11555
35b1e5cc 11556static void
559d2b81
TT
11557remote_download_trace_state_variable (struct target_ops *self,
11558 struct trace_state_variable *tsv)
35b1e5cc
SS
11559{
11560 struct remote_state *rs = get_remote_state ();
00bf0b85 11561 char *p;
35b1e5cc 11562
bba74b36
YQ
11563 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11564 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11565 tsv->builtin);
00bf0b85
SS
11566 p = rs->buf + strlen (rs->buf);
11567 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11568 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11569 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11570 *p++ = '\0';
35b1e5cc
SS
11571 putpkt (rs->buf);
11572 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11573 if (*target_buf == '\0')
11574 error (_("Target does not support this command."));
11575 if (strcmp (target_buf, "OK") != 0)
11576 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11577}
11578
d248b706 11579static void
46670d57
TT
11580remote_enable_tracepoint (struct target_ops *self,
11581 struct bp_location *location)
d248b706
KY
11582{
11583 struct remote_state *rs = get_remote_state ();
11584 char addr_buf[40];
11585
11586 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11587 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11588 location->owner->number, addr_buf);
d248b706
KY
11589 putpkt (rs->buf);
11590 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11591 if (*rs->buf == '\0')
11592 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11593 if (strcmp (rs->buf, "OK") != 0)
11594 error (_("Error on target while enabling tracepoint."));
11595}
11596
11597static void
780b049c
TT
11598remote_disable_tracepoint (struct target_ops *self,
11599 struct bp_location *location)
d248b706
KY
11600{
11601 struct remote_state *rs = get_remote_state ();
11602 char addr_buf[40];
11603
11604 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11605 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11606 location->owner->number, addr_buf);
d248b706
KY
11607 putpkt (rs->buf);
11608 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11609 if (*rs->buf == '\0')
11610 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11611 if (strcmp (rs->buf, "OK") != 0)
11612 error (_("Error on target while disabling tracepoint."));
11613}
11614
35b1e5cc 11615static void
583f9a86 11616remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
11617{
11618 asection *s;
81b9b86e 11619 bfd *abfd = NULL;
35b1e5cc 11620 bfd_size_type size;
608bcef2 11621 bfd_vma vma;
35b1e5cc 11622 int anysecs = 0;
c2fa21f1 11623 int offset = 0;
35b1e5cc
SS
11624
11625 if (!exec_bfd)
11626 return; /* No information to give. */
11627
11628 strcpy (target_buf, "QTro");
9779ab84 11629 offset = strlen (target_buf);
35b1e5cc
SS
11630 for (s = exec_bfd->sections; s; s = s->next)
11631 {
11632 char tmp1[40], tmp2[40];
c2fa21f1 11633 int sec_length;
35b1e5cc
SS
11634
11635 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 11636 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
11637 (s->flags & SEC_READONLY) == 0)
11638 continue;
11639
11640 anysecs = 1;
81b9b86e 11641 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 11642 size = bfd_get_section_size (s);
608bcef2
HZ
11643 sprintf_vma (tmp1, vma);
11644 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
11645 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11646 if (offset + sec_length + 1 > target_buf_size)
11647 {
4082afcc 11648 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 11649 warning (_("\
c2fa21f1
HZ
11650Too many sections for read-only sections definition packet."));
11651 break;
11652 }
bba74b36
YQ
11653 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11654 tmp1, tmp2);
c2fa21f1 11655 offset += sec_length;
35b1e5cc
SS
11656 }
11657 if (anysecs)
11658 {
11659 putpkt (target_buf);
11660 getpkt (&target_buf, &target_buf_size, 0);
11661 }
11662}
11663
11664static void
e2d1aae3 11665remote_trace_start (struct target_ops *self)
35b1e5cc
SS
11666{
11667 putpkt ("QTStart");
11668 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11669 if (*target_buf == '\0')
11670 error (_("Target does not support this command."));
11671 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11672 error (_("Bogus reply from target: %s"), target_buf);
11673}
11674
11675static int
8bd200f1 11676remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 11677{
953b98d1 11678 /* Initialize it just to avoid a GCC false warning. */
f652de6f 11679 char *p = NULL;
0df8b418 11680 /* FIXME we need to get register block size some other way. */
00bf0b85 11681 extern int trace_regblock_size;
bd3eecc3
PA
11682 enum packet_result result;
11683
4082afcc 11684 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 11685 return -1;
a744cf53 11686
00bf0b85
SS
11687 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11688
049dc89b
JK
11689 putpkt ("qTStatus");
11690
492d29ea 11691 TRY
67f41397
JK
11692 {
11693 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11694 }
492d29ea 11695 CATCH (ex, RETURN_MASK_ERROR)
67f41397 11696 {
598d3636
JK
11697 if (ex.error != TARGET_CLOSE_ERROR)
11698 {
11699 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11700 return -1;
11701 }
11702 throw_exception (ex);
67f41397 11703 }
492d29ea 11704 END_CATCH
00bf0b85 11705
bd3eecc3
PA
11706 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11707
00bf0b85 11708 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 11709 if (result == PACKET_UNKNOWN)
00bf0b85 11710 return -1;
35b1e5cc 11711
00bf0b85 11712 /* We're working with a live target. */
f5911ea1 11713 ts->filename = NULL;
00bf0b85 11714
00bf0b85 11715 if (*p++ != 'T')
35b1e5cc
SS
11716 error (_("Bogus trace status reply from target: %s"), target_buf);
11717
84cebc4a
YQ
11718 /* Function 'parse_trace_status' sets default value of each field of
11719 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
11720 parse_trace_status (p, ts);
11721
11722 return ts->running;
35b1e5cc
SS
11723}
11724
70221824 11725static void
db90e85c 11726remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
11727 struct uploaded_tp *utp)
11728{
11729 struct remote_state *rs = get_remote_state ();
f196051f
SS
11730 char *reply;
11731 struct bp_location *loc;
11732 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 11733 size_t size = get_remote_packet_size ();
f196051f
SS
11734
11735 if (tp)
11736 {
11737 tp->base.hit_count = 0;
11738 tp->traceframe_usage = 0;
11739 for (loc = tp->base.loc; loc; loc = loc->next)
11740 {
11741 /* If the tracepoint was never downloaded, don't go asking for
11742 any status. */
11743 if (tp->number_on_target == 0)
11744 continue;
bba74b36
YQ
11745 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11746 phex_nz (loc->address, 0));
f196051f
SS
11747 putpkt (rs->buf);
11748 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11749 if (reply && *reply)
11750 {
11751 if (*reply == 'V')
11752 parse_tracepoint_status (reply + 1, bp, utp);
11753 }
11754 }
11755 }
11756 else if (utp)
11757 {
11758 utp->hit_count = 0;
11759 utp->traceframe_usage = 0;
bba74b36
YQ
11760 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11761 phex_nz (utp->addr, 0));
f196051f
SS
11762 putpkt (rs->buf);
11763 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11764 if (reply && *reply)
11765 {
11766 if (*reply == 'V')
11767 parse_tracepoint_status (reply + 1, bp, utp);
11768 }
11769 }
11770}
11771
35b1e5cc 11772static void
74499f1b 11773remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11774{
11775 putpkt ("QTStop");
11776 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11777 if (*target_buf == '\0')
11778 error (_("Target does not support this command."));
11779 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11780 error (_("Bogus reply from target: %s"), target_buf);
11781}
11782
11783static int
bd4c6793
TT
11784remote_trace_find (struct target_ops *self,
11785 enum trace_find_type type, int num,
cc5925ad 11786 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11787 int *tpp)
11788{
11789 struct remote_state *rs = get_remote_state ();
bba74b36 11790 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11791 char *p, *reply;
11792 int target_frameno = -1, target_tracept = -1;
11793
e6e4e701
PA
11794 /* Lookups other than by absolute frame number depend on the current
11795 trace selected, so make sure it is correct on the remote end
11796 first. */
11797 if (type != tfind_number)
11798 set_remote_traceframe ();
11799
35b1e5cc
SS
11800 p = rs->buf;
11801 strcpy (p, "QTFrame:");
11802 p = strchr (p, '\0');
11803 switch (type)
11804 {
11805 case tfind_number:
bba74b36 11806 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11807 break;
11808 case tfind_pc:
bba74b36 11809 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11810 break;
11811 case tfind_tp:
bba74b36 11812 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11813 break;
11814 case tfind_range:
bba74b36
YQ
11815 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11816 phex_nz (addr2, 0));
35b1e5cc
SS
11817 break;
11818 case tfind_outside:
bba74b36
YQ
11819 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11820 phex_nz (addr2, 0));
35b1e5cc
SS
11821 break;
11822 default:
9b20d036 11823 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11824 }
11825
11826 putpkt (rs->buf);
2f65bcb7 11827 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11828 if (*reply == '\0')
11829 error (_("Target does not support this command."));
35b1e5cc
SS
11830
11831 while (reply && *reply)
11832 switch (*reply)
11833 {
11834 case 'F':
f197e0f1
VP
11835 p = ++reply;
11836 target_frameno = (int) strtol (p, &reply, 16);
11837 if (reply == p)
11838 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11839 /* Don't update our remote traceframe number cache on failure
11840 to select a remote traceframe. */
f197e0f1
VP
11841 if (target_frameno == -1)
11842 return -1;
35b1e5cc
SS
11843 break;
11844 case 'T':
f197e0f1
VP
11845 p = ++reply;
11846 target_tracept = (int) strtol (p, &reply, 16);
11847 if (reply == p)
11848 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11849 break;
11850 case 'O': /* "OK"? */
11851 if (reply[1] == 'K' && reply[2] == '\0')
11852 reply += 2;
11853 else
11854 error (_("Bogus reply from target: %s"), reply);
11855 break;
11856 default:
11857 error (_("Bogus reply from target: %s"), reply);
11858 }
11859 if (tpp)
11860 *tpp = target_tracept;
e6e4e701 11861
262e1174 11862 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11863 return target_frameno;
11864}
11865
11866static int
4011015b
TT
11867remote_get_trace_state_variable_value (struct target_ops *self,
11868 int tsvnum, LONGEST *val)
35b1e5cc
SS
11869{
11870 struct remote_state *rs = get_remote_state ();
11871 char *reply;
11872 ULONGEST uval;
11873
e6e4e701
PA
11874 set_remote_traceframe ();
11875
bba74b36 11876 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11877 putpkt (rs->buf);
11878 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11879 if (reply && *reply)
11880 {
11881 if (*reply == 'V')
11882 {
11883 unpack_varlen_hex (reply + 1, &uval);
11884 *val = (LONGEST) uval;
11885 return 1;
11886 }
11887 }
11888 return 0;
11889}
11890
00bf0b85 11891static int
dc3decaf 11892remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11893{
11894 struct remote_state *rs = get_remote_state ();
11895 char *p, *reply;
11896
11897 p = rs->buf;
11898 strcpy (p, "QTSave:");
11899 p += strlen (p);
11900 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11901 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11902 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11903 *p++ = '\0';
11904 putpkt (rs->buf);
ad91cd99 11905 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11906 if (*reply == '\0')
ad91cd99
PA
11907 error (_("Target does not support this command."));
11908 if (strcmp (reply, "OK") != 0)
11909 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11910 return 0;
11911}
11912
11913/* This is basically a memory transfer, but needs to be its own packet
11914 because we don't know how the target actually organizes its trace
11915 memory, plus we want to be able to ask for as much as possible, but
11916 not be unhappy if we don't get as much as we ask for. */
11917
11918static LONGEST
88ee6f45
TT
11919remote_get_raw_trace_data (struct target_ops *self,
11920 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11921{
11922 struct remote_state *rs = get_remote_state ();
11923 char *reply;
11924 char *p;
11925 int rslt;
11926
11927 p = rs->buf;
11928 strcpy (p, "qTBuffer:");
11929 p += strlen (p);
11930 p += hexnumstr (p, offset);
11931 *p++ = ',';
11932 p += hexnumstr (p, len);
11933 *p++ = '\0';
11934
11935 putpkt (rs->buf);
11936 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11937 if (reply && *reply)
11938 {
11939 /* 'l' by itself means we're at the end of the buffer and
11940 there is nothing more to get. */
11941 if (*reply == 'l')
11942 return 0;
11943
11944 /* Convert the reply into binary. Limit the number of bytes to
11945 convert according to our passed-in buffer size, rather than
11946 what was returned in the packet; if the target is
11947 unexpectedly generous and gives us a bigger reply than we
11948 asked for, we don't want to crash. */
11949 rslt = hex2bin (target_buf, buf, len);
11950 return rslt;
11951 }
11952
11953 /* Something went wrong, flag as an error. */
11954 return -1;
11955}
11956
35b1e5cc 11957static void
37b25738 11958remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11959{
11960 struct remote_state *rs = get_remote_state ();
11961
4082afcc 11962 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11963 {
ad91cd99
PA
11964 char *reply;
11965
bba74b36 11966 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11967 putpkt (rs->buf);
ad91cd99
PA
11968 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11969 if (*reply == '\0')
33da3f1c 11970 error (_("Target does not support this command."));
ad91cd99
PA
11971 if (strcmp (reply, "OK") != 0)
11972 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11973 }
11974 else if (val)
11975 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11976}
11977
dc146f7c
VP
11978static int
11979remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11980{
11981 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11982
fe978cb0
PA
11983 if (info && info->priv)
11984 return info->priv->core;
dc146f7c
VP
11985 return -1;
11986}
11987
4daf5ac0 11988static void
736d5b1f 11989remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11990{
11991 struct remote_state *rs = get_remote_state ();
ad91cd99 11992 char *reply;
4daf5ac0 11993
bba74b36 11994 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11995 putpkt (rs->buf);
ad91cd99
PA
11996 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11997 if (*reply == '\0')
4daf5ac0 11998 error (_("Target does not support this command."));
ad91cd99
PA
11999 if (strcmp (reply, "OK") != 0)
12000 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12001}
12002
b3b9301e 12003static struct traceframe_info *
a893e81f 12004remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12005{
12006 char *text;
12007
12008 text = target_read_stralloc (&current_target,
12009 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12010 if (text != NULL)
12011 {
12012 struct traceframe_info *info;
12013 struct cleanup *back_to = make_cleanup (xfree, text);
12014
12015 info = parse_traceframe_info (text);
12016 do_cleanups (back_to);
12017 return info;
12018 }
12019
12020 return NULL;
12021}
12022
405f8e94
SS
12023/* Handle the qTMinFTPILen packet. Returns the minimum length of
12024 instruction on which a fast tracepoint may be placed. Returns -1
12025 if the packet is not supported, and 0 if the minimum instruction
12026 length is unknown. */
12027
12028static int
0e67620a 12029remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12030{
12031 struct remote_state *rs = get_remote_state ();
12032 char *reply;
12033
e886a173
PA
12034 /* If we're not debugging a process yet, the IPA can't be
12035 loaded. */
12036 if (!target_has_execution)
12037 return 0;
12038
12039 /* Make sure the remote is pointing at the right process. */
12040 set_general_process ();
12041
bba74b36 12042 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12043 putpkt (rs->buf);
12044 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12045 if (*reply == '\0')
12046 return -1;
12047 else
12048 {
12049 ULONGEST min_insn_len;
12050
12051 unpack_varlen_hex (reply, &min_insn_len);
12052
12053 return (int) min_insn_len;
12054 }
12055}
12056
f6f899bf 12057static void
4da384be 12058remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12059{
4082afcc 12060 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12061 {
12062 struct remote_state *rs = get_remote_state ();
12063 char *buf = rs->buf;
12064 char *endbuf = rs->buf + get_remote_packet_size ();
12065 enum packet_result result;
12066
12067 gdb_assert (val >= 0 || val == -1);
12068 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12069 /* Send -1 as literal "-1" to avoid host size dependency. */
12070 if (val < 0)
12071 {
12072 *buf++ = '-';
12073 buf += hexnumstr (buf, (ULONGEST) -val);
12074 }
12075 else
12076 buf += hexnumstr (buf, (ULONGEST) val);
12077
12078 putpkt (rs->buf);
12079 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12080 result = packet_ok (rs->buf,
12081 &remote_protocol_packets[PACKET_QTBuffer_size]);
12082
12083 if (result != PACKET_OK)
12084 warning (_("Bogus reply from target: %s"), rs->buf);
12085 }
12086}
12087
f196051f 12088static int
d9e68a2c
TT
12089remote_set_trace_notes (struct target_ops *self,
12090 const char *user, const char *notes,
ca623f82 12091 const char *stop_notes)
f196051f
SS
12092{
12093 struct remote_state *rs = get_remote_state ();
12094 char *reply;
12095 char *buf = rs->buf;
12096 char *endbuf = rs->buf + get_remote_packet_size ();
12097 int nbytes;
12098
12099 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12100 if (user)
12101 {
12102 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12103 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12104 buf += 2 * nbytes;
12105 *buf++ = ';';
12106 }
12107 if (notes)
12108 {
12109 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12110 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12111 buf += 2 * nbytes;
12112 *buf++ = ';';
12113 }
12114 if (stop_notes)
12115 {
12116 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12117 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12118 buf += 2 * nbytes;
12119 *buf++ = ';';
12120 }
12121 /* Ensure the buffer is terminated. */
12122 *buf = '\0';
12123
12124 putpkt (rs->buf);
12125 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12126 if (*reply == '\0')
12127 return 0;
12128
12129 if (strcmp (reply, "OK") != 0)
12130 error (_("Bogus reply from target: %s"), reply);
12131
12132 return 1;
12133}
12134
d1feda86 12135static int
2c152180 12136remote_use_agent (struct target_ops *self, int use)
d1feda86 12137{
4082afcc 12138 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12139 {
12140 struct remote_state *rs = get_remote_state ();
12141
12142 /* If the stub supports QAgent. */
bba74b36 12143 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12144 putpkt (rs->buf);
12145 getpkt (&rs->buf, &rs->buf_size, 0);
12146
12147 if (strcmp (rs->buf, "OK") == 0)
12148 {
12149 use_agent = use;
12150 return 1;
12151 }
12152 }
12153
12154 return 0;
12155}
12156
12157static int
fe38f897 12158remote_can_use_agent (struct target_ops *self)
d1feda86 12159{
4082afcc 12160 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12161}
12162
9accd112
MM
12163struct btrace_target_info
12164{
12165 /* The ptid of the traced thread. */
12166 ptid_t ptid;
f4abbc16
MM
12167
12168 /* The obtained branch trace configuration. */
12169 struct btrace_config conf;
9accd112
MM
12170};
12171
f4abbc16
MM
12172/* Reset our idea of our target's btrace configuration. */
12173
12174static void
12175remote_btrace_reset (void)
12176{
12177 struct remote_state *rs = get_remote_state ();
12178
12179 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12180}
12181
9accd112
MM
12182/* Check whether the target supports branch tracing. */
12183
12184static int
043c3577 12185remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12186{
4082afcc 12187 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12188 return 0;
4082afcc 12189 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12190 return 0;
12191
043c3577
MM
12192 switch (format)
12193 {
12194 case BTRACE_FORMAT_NONE:
12195 return 0;
12196
12197 case BTRACE_FORMAT_BTS:
12198 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12199
12200 case BTRACE_FORMAT_PT:
12201 /* The trace is decoded on the host. Even if our target supports it,
12202 we still need to have libipt to decode the trace. */
12203#if defined (HAVE_LIBIPT)
12204 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12205#else /* !defined (HAVE_LIBIPT) */
12206 return 0;
12207#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12208 }
12209
12210 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12211}
12212
f4abbc16
MM
12213/* Synchronize the configuration with the target. */
12214
12215static void
12216btrace_sync_conf (const struct btrace_config *conf)
12217{
d33501a5
MM
12218 struct packet_config *packet;
12219 struct remote_state *rs;
12220 char *buf, *pos, *endbuf;
12221
12222 rs = get_remote_state ();
12223 buf = rs->buf;
12224 endbuf = buf + get_remote_packet_size ();
12225
12226 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12227 if (packet_config_support (packet) == PACKET_ENABLE
12228 && conf->bts.size != rs->btrace_config.bts.size)
12229 {
12230 pos = buf;
12231 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12232 conf->bts.size);
12233
12234 putpkt (buf);
12235 getpkt (&buf, &rs->buf_size, 0);
12236
12237 if (packet_ok (buf, packet) == PACKET_ERROR)
12238 {
12239 if (buf[0] == 'E' && buf[1] == '.')
12240 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12241 else
12242 error (_("Failed to configure the BTS buffer size."));
12243 }
12244
12245 rs->btrace_config.bts.size = conf->bts.size;
12246 }
b20a6524
MM
12247
12248 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12249 if (packet_config_support (packet) == PACKET_ENABLE
12250 && conf->pt.size != rs->btrace_config.pt.size)
12251 {
12252 pos = buf;
12253 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12254 conf->pt.size);
12255
12256 putpkt (buf);
12257 getpkt (&buf, &rs->buf_size, 0);
12258
12259 if (packet_ok (buf, packet) == PACKET_ERROR)
12260 {
12261 if (buf[0] == 'E' && buf[1] == '.')
12262 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12263 else
12264 error (_("Failed to configure the trace buffer size."));
12265 }
12266
12267 rs->btrace_config.pt.size = conf->pt.size;
12268 }
f4abbc16
MM
12269}
12270
12271/* Read the current thread's btrace configuration from the target and
12272 store it into CONF. */
12273
12274static void
12275btrace_read_config (struct btrace_config *conf)
12276{
12277 char *xml;
12278
12279 xml = target_read_stralloc (&current_target,
b20a6524 12280 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12281 if (xml != NULL)
12282 {
12283 struct cleanup *cleanup;
12284
12285 cleanup = make_cleanup (xfree, xml);
12286 parse_xml_btrace_conf (conf, xml);
12287 do_cleanups (cleanup);
12288 }
12289}
12290
9accd112
MM
12291/* Enable branch tracing. */
12292
12293static struct btrace_target_info *
f4abbc16
MM
12294remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12295 const struct btrace_config *conf)
9accd112
MM
12296{
12297 struct btrace_target_info *tinfo = NULL;
b20a6524 12298 struct packet_config *packet = NULL;
9accd112
MM
12299 struct remote_state *rs = get_remote_state ();
12300 char *buf = rs->buf;
12301 char *endbuf = rs->buf + get_remote_packet_size ();
12302
b20a6524
MM
12303 switch (conf->format)
12304 {
12305 case BTRACE_FORMAT_BTS:
12306 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12307 break;
12308
12309 case BTRACE_FORMAT_PT:
12310 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12311 break;
12312 }
12313
12314 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12315 error (_("Target does not support branch tracing."));
12316
f4abbc16
MM
12317 btrace_sync_conf (conf);
12318
9accd112
MM
12319 set_general_thread (ptid);
12320
12321 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12322 putpkt (rs->buf);
12323 getpkt (&rs->buf, &rs->buf_size, 0);
12324
12325 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12326 {
12327 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12328 error (_("Could not enable branch tracing for %s: %s"),
12329 target_pid_to_str (ptid), rs->buf + 2);
12330 else
12331 error (_("Could not enable branch tracing for %s."),
12332 target_pid_to_str (ptid));
12333 }
12334
8d749320 12335 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12336 tinfo->ptid = ptid;
12337
f4abbc16
MM
12338 /* If we fail to read the configuration, we lose some information, but the
12339 tracing itself is not impacted. */
492d29ea
PA
12340 TRY
12341 {
12342 btrace_read_config (&tinfo->conf);
12343 }
12344 CATCH (err, RETURN_MASK_ERROR)
12345 {
12346 if (err.message != NULL)
12347 warning ("%s", err.message);
12348 }
12349 END_CATCH
f4abbc16 12350
9accd112
MM
12351 return tinfo;
12352}
12353
12354/* Disable branch tracing. */
12355
12356static void
25e95349
TT
12357remote_disable_btrace (struct target_ops *self,
12358 struct btrace_target_info *tinfo)
9accd112
MM
12359{
12360 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12361 struct remote_state *rs = get_remote_state ();
12362 char *buf = rs->buf;
12363 char *endbuf = rs->buf + get_remote_packet_size ();
12364
4082afcc 12365 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12366 error (_("Target does not support branch tracing."));
12367
12368 set_general_thread (tinfo->ptid);
12369
12370 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12371 putpkt (rs->buf);
12372 getpkt (&rs->buf, &rs->buf_size, 0);
12373
12374 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12375 {
12376 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12377 error (_("Could not disable branch tracing for %s: %s"),
12378 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12379 else
12380 error (_("Could not disable branch tracing for %s."),
12381 target_pid_to_str (tinfo->ptid));
12382 }
12383
12384 xfree (tinfo);
12385}
12386
12387/* Teardown branch tracing. */
12388
12389static void
1777056d
TT
12390remote_teardown_btrace (struct target_ops *self,
12391 struct btrace_target_info *tinfo)
9accd112
MM
12392{
12393 /* We must not talk to the target during teardown. */
12394 xfree (tinfo);
12395}
12396
12397/* Read the branch trace. */
12398
969c39fb 12399static enum btrace_error
39c49f83 12400remote_read_btrace (struct target_ops *self,
734b0e4b 12401 struct btrace_data *btrace,
969c39fb 12402 struct btrace_target_info *tinfo,
9accd112
MM
12403 enum btrace_read_type type)
12404{
12405 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12406 struct remote_state *rs = get_remote_state ();
969c39fb 12407 struct cleanup *cleanup;
9accd112
MM
12408 const char *annex;
12409 char *xml;
12410
4082afcc 12411 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12412 error (_("Target does not support branch tracing."));
12413
12414#if !defined(HAVE_LIBEXPAT)
12415 error (_("Cannot process branch tracing result. XML parsing not supported."));
12416#endif
12417
12418 switch (type)
12419 {
864089d2 12420 case BTRACE_READ_ALL:
9accd112
MM
12421 annex = "all";
12422 break;
864089d2 12423 case BTRACE_READ_NEW:
9accd112
MM
12424 annex = "new";
12425 break;
969c39fb
MM
12426 case BTRACE_READ_DELTA:
12427 annex = "delta";
12428 break;
9accd112
MM
12429 default:
12430 internal_error (__FILE__, __LINE__,
12431 _("Bad branch tracing read type: %u."),
12432 (unsigned int) type);
12433 }
12434
12435 xml = target_read_stralloc (&current_target,
b20a6524 12436 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12437 if (xml == NULL)
12438 return BTRACE_ERR_UNKNOWN;
9accd112 12439
969c39fb 12440 cleanup = make_cleanup (xfree, xml);
734b0e4b 12441 parse_xml_btrace (btrace, xml);
969c39fb 12442 do_cleanups (cleanup);
9accd112 12443
969c39fb 12444 return BTRACE_ERR_NONE;
9accd112
MM
12445}
12446
f4abbc16
MM
12447static const struct btrace_config *
12448remote_btrace_conf (struct target_ops *self,
12449 const struct btrace_target_info *tinfo)
12450{
12451 return &tinfo->conf;
12452}
12453
ced63ec0 12454static int
5436ff03 12455remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12456{
4082afcc
PA
12457 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12458 == PACKET_ENABLE);
ced63ec0
GB
12459}
12460
9dd130a0
TT
12461/* Implementation of to_load. */
12462
12463static void
9cbe5fff 12464remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12465{
12466 generic_load (name, from_tty);
12467}
12468
c78fa86a
GB
12469/* Accepts an integer PID; returns a string representing a file that
12470 can be opened on the remote side to get the symbols for the child
12471 process. Returns NULL if the operation is not supported. */
12472
12473static char *
12474remote_pid_to_exec_file (struct target_ops *self, int pid)
12475{
12476 static char *filename = NULL;
835205d0
GB
12477 struct inferior *inf;
12478 char *annex = NULL;
c78fa86a
GB
12479
12480 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12481 return NULL;
12482
12483 if (filename != NULL)
12484 xfree (filename);
12485
835205d0
GB
12486 inf = find_inferior_pid (pid);
12487 if (inf == NULL)
12488 internal_error (__FILE__, __LINE__,
12489 _("not currently attached to process %d"), pid);
12490
12491 if (!inf->fake_pid_p)
12492 {
12493 const int annex_size = 9;
12494
12495 annex = alloca (annex_size);
12496 xsnprintf (annex, annex_size, "%x", pid);
12497 }
12498
c78fa86a
GB
12499 filename = target_read_stralloc (&current_target,
12500 TARGET_OBJECT_EXEC_FILE, annex);
12501
12502 return filename;
12503}
12504
c906108c 12505static void
fba45db2 12506init_remote_ops (void)
c906108c 12507{
c5aa993b 12508 remote_ops.to_shortname = "remote";
c906108c 12509 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12510 remote_ops.to_doc =
c906108c 12511 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12512Specify the serial device it is connected to\n\
12513(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12514 remote_ops.to_open = remote_open;
12515 remote_ops.to_close = remote_close;
c906108c 12516 remote_ops.to_detach = remote_detach;
6ad8ae5c 12517 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12518 remote_ops.to_resume = remote_resume;
c906108c
SS
12519 remote_ops.to_wait = remote_wait;
12520 remote_ops.to_fetch_registers = remote_fetch_registers;
12521 remote_ops.to_store_registers = remote_store_registers;
12522 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12523 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12524 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12525 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12526 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12527 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12528 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12529 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12530 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12531 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12532 remote_ops.to_watchpoint_addr_within_range =
12533 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12534 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12535 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12536 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12537 remote_ops.to_region_ok_for_hw_watchpoint
12538 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12539 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12540 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12541 remote_ops.to_kill = remote_kill;
9dd130a0 12542 remote_ops.to_load = remote_load;
c906108c 12543 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12544 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12545 remote_ops.to_program_signals = remote_program_signals;
c906108c 12546 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 12547 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12548 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12549 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12550 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12551 remote_ops.to_stop = remote_stop;
bfedc46a 12552 remote_ops.to_interrupt = remote_interrupt;
abc56d60 12553 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 12554 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12555 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12556 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12557 remote_ops.to_log_command = serial_log_command;
38691318 12558 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12559 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12560 remote_ops.to_has_all_memory = default_child_has_all_memory;
12561 remote_ops.to_has_memory = default_child_has_memory;
12562 remote_ops.to_has_stack = default_child_has_stack;
12563 remote_ops.to_has_registers = default_child_has_registers;
12564 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12565 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 12566 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 12567 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 12568 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
12569 remote_ops.to_flash_erase = remote_flash_erase;
12570 remote_ops.to_flash_done = remote_flash_done;
29709017 12571 remote_ops.to_read_description = remote_read_description;
08388c79 12572 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
12573 remote_ops.to_can_async_p = remote_can_async_p;
12574 remote_ops.to_is_async_p = remote_is_async_p;
12575 remote_ops.to_async = remote_async;
75c99385
PA
12576 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12577 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 12578 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 12579 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
12580 remote_ops.to_supports_disable_randomization
12581 = remote_supports_disable_randomization;
4bd7dc42 12582 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
12583 remote_ops.to_fileio_open = remote_hostio_open;
12584 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12585 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 12586 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
12587 remote_ops.to_fileio_close = remote_hostio_close;
12588 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 12589 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 12590 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 12591 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 12592 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 12593 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
12594 remote_ops.to_trace_init = remote_trace_init;
12595 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 12596 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
12597 remote_ops.to_download_trace_state_variable
12598 = remote_download_trace_state_variable;
d248b706
KY
12599 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12600 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
12601 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12602 remote_ops.to_trace_start = remote_trace_start;
12603 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 12604 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
12605 remote_ops.to_trace_stop = remote_trace_stop;
12606 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
12607 remote_ops.to_get_trace_state_variable_value
12608 = remote_get_trace_state_variable_value;
00bf0b85
SS
12609 remote_ops.to_save_trace_data = remote_save_trace_data;
12610 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
12611 remote_ops.to_upload_trace_state_variables
12612 = remote_upload_trace_state_variables;
00bf0b85 12613 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 12614 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 12615 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 12616 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 12617 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 12618 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 12619 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 12620 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 12621 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 12622 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
12623 remote_ops.to_static_tracepoint_marker_at
12624 = remote_static_tracepoint_marker_at;
12625 remote_ops.to_static_tracepoint_markers_by_strid
12626 = remote_static_tracepoint_markers_by_strid;
b3b9301e 12627 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
12628 remote_ops.to_use_agent = remote_use_agent;
12629 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
12630 remote_ops.to_supports_btrace = remote_supports_btrace;
12631 remote_ops.to_enable_btrace = remote_enable_btrace;
12632 remote_ops.to_disable_btrace = remote_disable_btrace;
12633 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12634 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 12635 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
12636 remote_ops.to_augmented_libraries_svr4_read =
12637 remote_augmented_libraries_svr4_read;
c906108c
SS
12638}
12639
12640/* Set up the extended remote vector by making a copy of the standard
12641 remote vector and adding to it. */
12642
12643static void
fba45db2 12644init_extended_remote_ops (void)
c906108c
SS
12645{
12646 extended_remote_ops = remote_ops;
12647
0f71a2f6 12648 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 12649 extended_remote_ops.to_longname =
c906108c 12650 "Extended remote serial target in gdb-specific protocol";
c5aa993b 12651 extended_remote_ops.to_doc =
c906108c 12652 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
12653Specify the serial device it is connected to (e.g. /dev/ttya).";
12654 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
12655 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12656 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
12657 extended_remote_ops.to_detach = extended_remote_detach;
12658 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 12659 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 12660 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
12661 extended_remote_ops.to_supports_disable_randomization
12662 = extended_remote_supports_disable_randomization;
de0d863e 12663 extended_remote_ops.to_follow_fork = remote_follow_fork;
cbb8991c
DB
12664 extended_remote_ops.to_insert_fork_catchpoint
12665 = remote_insert_fork_catchpoint;
12666 extended_remote_ops.to_remove_fork_catchpoint
12667 = remote_remove_fork_catchpoint;
12668 extended_remote_ops.to_insert_vfork_catchpoint
12669 = remote_insert_vfork_catchpoint;
12670 extended_remote_ops.to_remove_vfork_catchpoint
12671 = remote_remove_vfork_catchpoint;
0f71a2f6
JM
12672}
12673
6426a772 12674static int
6a109b6b 12675remote_can_async_p (struct target_ops *ops)
6426a772 12676{
5d93a237
TT
12677 struct remote_state *rs = get_remote_state ();
12678
c6ebd6cf 12679 if (!target_async_permitted)
75c99385
PA
12680 /* We only enable async when the user specifically asks for it. */
12681 return 0;
12682
23860348 12683 /* We're async whenever the serial device is. */
5d93a237 12684 return serial_can_async_p (rs->remote_desc);
6426a772
JM
12685}
12686
12687static int
6a109b6b 12688remote_is_async_p (struct target_ops *ops)
6426a772 12689{
5d93a237
TT
12690 struct remote_state *rs = get_remote_state ();
12691
c6ebd6cf 12692 if (!target_async_permitted)
75c99385
PA
12693 /* We only enable async when the user specifically asks for it. */
12694 return 0;
12695
23860348 12696 /* We're async whenever the serial device is. */
5d93a237 12697 return serial_is_async_p (rs->remote_desc);
6426a772
JM
12698}
12699
2acceee2
JM
12700/* Pass the SERIAL event on and up to the client. One day this code
12701 will be able to delay notifying the client of an event until the
23860348 12702 point where an entire packet has been received. */
2acceee2 12703
2acceee2
JM
12704static serial_event_ftype remote_async_serial_handler;
12705
6426a772 12706static void
819cc324 12707remote_async_serial_handler (struct serial *scb, void *context)
6426a772 12708{
88b496c3
TT
12709 struct remote_state *rs = context;
12710
2acceee2
JM
12711 /* Don't propogate error information up to the client. Instead let
12712 the client find out about the error by querying the target. */
6a3753b3 12713 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
12714}
12715
74531fed
PA
12716static void
12717remote_async_inferior_event_handler (gdb_client_data data)
12718{
12719 inferior_event_handler (INF_REG_EVENT, NULL);
12720}
12721
2acceee2 12722static void
6a3753b3 12723remote_async (struct target_ops *ops, int enable)
2acceee2 12724{
5d93a237
TT
12725 struct remote_state *rs = get_remote_state ();
12726
6a3753b3 12727 if (enable)
2acceee2 12728 {
88b496c3 12729 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
12730
12731 /* If there are pending events in the stop reply queue tell the
12732 event loop to process them. */
12733 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12734 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
12735 }
12736 else
b7d2e916
PA
12737 {
12738 serial_async (rs->remote_desc, NULL, NULL);
12739 clear_async_event_handler (remote_async_inferior_event_token);
12740 }
6426a772
JM
12741}
12742
5a2468f5 12743static void
c2d11a7d 12744set_remote_cmd (char *args, int from_tty)
5a2468f5 12745{
635c7e8a 12746 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
12747}
12748
d471ea57
AC
12749static void
12750show_remote_cmd (char *args, int from_tty)
12751{
37a105a1 12752 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 12753 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
12754 struct cleanup *showlist_chain;
12755 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 12756 struct ui_out *uiout = current_uiout;
37a105a1
DJ
12757
12758 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12759 for (; list != NULL; list = list->next)
12760 if (strcmp (list->name, "Z-packet") == 0)
12761 continue;
427c3a89
DJ
12762 else if (list->type == not_set_cmd)
12763 /* Alias commands are exactly like the original, except they
12764 don't have the normal type. */
12765 continue;
12766 else
37a105a1
DJ
12767 {
12768 struct cleanup *option_chain
12769 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 12770
37a105a1
DJ
12771 ui_out_field_string (uiout, "name", list->name);
12772 ui_out_text (uiout, ": ");
427c3a89 12773 if (list->type == show_cmd)
5b9afe8a 12774 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
12775 else
12776 cmd_func (list, NULL, from_tty);
37a105a1
DJ
12777 /* Close the tuple. */
12778 do_cleanups (option_chain);
12779 }
427c3a89
DJ
12780
12781 /* Close the tuple. */
12782 do_cleanups (showlist_chain);
d471ea57 12783}
5a2468f5 12784
0f71a2f6 12785
23860348 12786/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
12787static void
12788remote_new_objfile (struct objfile *objfile)
12789{
5d93a237
TT
12790 struct remote_state *rs = get_remote_state ();
12791
12792 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 12793 remote_check_symbols ();
dc8acb97
MS
12794}
12795
00bf0b85
SS
12796/* Pull all the tracepoints defined on the target and create local
12797 data structures representing them. We don't want to create real
12798 tracepoints yet, we don't want to mess up the user's existing
12799 collection. */
12800
12801static int
ab6617cc 12802remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 12803{
00bf0b85
SS
12804 struct remote_state *rs = get_remote_state ();
12805 char *p;
d5551862 12806
00bf0b85
SS
12807 /* Ask for a first packet of tracepoint definition. */
12808 putpkt ("qTfP");
12809 getpkt (&rs->buf, &rs->buf_size, 0);
12810 p = rs->buf;
12811 while (*p && *p != 'l')
d5551862 12812 {
00bf0b85
SS
12813 parse_tracepoint_definition (p, utpp);
12814 /* Ask for another packet of tracepoint definition. */
12815 putpkt ("qTsP");
12816 getpkt (&rs->buf, &rs->buf_size, 0);
12817 p = rs->buf;
d5551862 12818 }
00bf0b85 12819 return 0;
d5551862
SS
12820}
12821
00bf0b85 12822static int
181e3713
TT
12823remote_upload_trace_state_variables (struct target_ops *self,
12824 struct uploaded_tsv **utsvp)
d5551862 12825{
00bf0b85 12826 struct remote_state *rs = get_remote_state ();
d5551862 12827 char *p;
d5551862 12828
00bf0b85
SS
12829 /* Ask for a first packet of variable definition. */
12830 putpkt ("qTfV");
d5551862
SS
12831 getpkt (&rs->buf, &rs->buf_size, 0);
12832 p = rs->buf;
00bf0b85 12833 while (*p && *p != 'l')
d5551862 12834 {
00bf0b85
SS
12835 parse_tsv_definition (p, utsvp);
12836 /* Ask for another packet of variable definition. */
12837 putpkt ("qTsV");
d5551862
SS
12838 getpkt (&rs->buf, &rs->buf_size, 0);
12839 p = rs->buf;
12840 }
00bf0b85 12841 return 0;
d5551862
SS
12842}
12843
c1e36e3e
PA
12844/* The "set/show range-stepping" show hook. */
12845
12846static void
12847show_range_stepping (struct ui_file *file, int from_tty,
12848 struct cmd_list_element *c,
12849 const char *value)
12850{
12851 fprintf_filtered (file,
12852 _("Debugger's willingness to use range stepping "
12853 "is %s.\n"), value);
12854}
12855
12856/* The "set/show range-stepping" set hook. */
12857
12858static void
12859set_range_stepping (char *ignore_args, int from_tty,
12860 struct cmd_list_element *c)
12861{
5d93a237
TT
12862 struct remote_state *rs = get_remote_state ();
12863
c1e36e3e
PA
12864 /* Whene enabling, check whether range stepping is actually
12865 supported by the target, and warn if not. */
12866 if (use_range_stepping)
12867 {
5d93a237 12868 if (rs->remote_desc != NULL)
c1e36e3e 12869 {
4082afcc 12870 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
12871 remote_vcont_probe (rs);
12872
4082afcc 12873 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
12874 && rs->supports_vCont.r)
12875 return;
12876 }
12877
12878 warning (_("Range stepping is not supported by the current target"));
12879 }
12880}
12881
c906108c 12882void
fba45db2 12883_initialize_remote (void)
c906108c 12884{
ea9c271d 12885 struct remote_state *rs;
9a7071a8 12886 struct cmd_list_element *cmd;
6f937416 12887 const char *cmd_name;
ea9c271d 12888
0f71a2f6 12889 /* architecture specific data */
2bc416ba 12890 remote_gdbarch_data_handle =
23860348 12891 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
12892 remote_g_packet_data_handle =
12893 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 12894
ea9c271d
DJ
12895 /* Initialize the per-target state. At the moment there is only one
12896 of these, not one per target. Only one target is active at a
cf792862
TT
12897 time. */
12898 remote_state = new_remote_state ();
ea9c271d 12899
c906108c
SS
12900 init_remote_ops ();
12901 add_target (&remote_ops);
12902
12903 init_extended_remote_ops ();
12904 add_target (&extended_remote_ops);
cce74817 12905
dc8acb97 12906 /* Hook into new objfile notification. */
06d3b283 12907 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
12908 /* We're no longer interested in notification events of an inferior
12909 when it exits. */
12910 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 12911
b803fb0f 12912 /* Set up signal handlers. */
934b9bac 12913 async_sigint_remote_token =
b803fb0f 12914 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 12915 async_sigint_remote_twice_token =
6d549500 12916 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 12917
c906108c
SS
12918#if 0
12919 init_remote_threadtests ();
12920#endif
12921
722247f1 12922 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 12923 /* set/show remote ... */
d471ea57 12924
1bedd215 12925 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
12926Remote protocol specific variables\n\
12927Configure various remote-protocol specific variables such as\n\
1bedd215 12928the packets being used"),
cff3e48b 12929 &remote_set_cmdlist, "set remote ",
23860348 12930 0 /* allow-unknown */, &setlist);
1bedd215 12931 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
12932Remote protocol specific variables\n\
12933Configure various remote-protocol specific variables such as\n\
1bedd215 12934the packets being used"),
cff3e48b 12935 &remote_show_cmdlist, "show remote ",
23860348 12936 0 /* allow-unknown */, &showlist);
5a2468f5 12937
1a966eab
AC
12938 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12939Compare section data on target to the exec file.\n\
95cf3b38
DT
12940Argument is a single section name (default: all loaded sections).\n\
12941To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
12942 &cmdlist);
12943
1a966eab
AC
12944 add_cmd ("packet", class_maintenance, packet_command, _("\
12945Send an arbitrary packet to a remote target.\n\
c906108c
SS
12946 maintenance packet TEXT\n\
12947If GDB is talking to an inferior via the GDB serial protocol, then\n\
12948this command sends the string TEXT to the inferior, and displays the\n\
12949response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 12950terminating `#' character and checksum."),
c906108c
SS
12951 &maintenancelist);
12952
7915a72c
AC
12953 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12954Set whether to send break if interrupted."), _("\
12955Show whether to send break if interrupted."), _("\
12956If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 12957 set_remotebreak, show_remotebreak,
e707bbc2 12958 &setlist, &showlist);
9a7071a8
JB
12959 cmd_name = "remotebreak";
12960 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12961 deprecate_cmd (cmd, "set remote interrupt-sequence");
12962 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12963 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12964 deprecate_cmd (cmd, "show remote interrupt-sequence");
12965
12966 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
12967 interrupt_sequence_modes, &interrupt_sequence_mode,
12968 _("\
9a7071a8
JB
12969Set interrupt sequence to remote target."), _("\
12970Show interrupt sequence to remote target."), _("\
12971Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12972 NULL, show_interrupt_sequence,
12973 &remote_set_cmdlist,
12974 &remote_show_cmdlist);
12975
12976 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12977 &interrupt_on_connect, _("\
12978Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12979Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12980If set, interrupt sequence is sent to remote target."),
12981 NULL, NULL,
12982 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 12983
23860348 12984 /* Install commands for configuring memory read/write packets. */
11cf8741 12985
1a966eab
AC
12986 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12987Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 12988 &setlist);
1a966eab
AC
12989 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12990Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
12991 &showlist);
12992 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
12993 set_memory_write_packet_size, _("\
12994Set the maximum number of bytes per memory-write packet.\n\
12995Specify the number of bytes in a packet or 0 (zero) for the\n\
12996default packet size. The actual limit is further reduced\n\
12997dependent on the target. Specify ``fixed'' to disable the\n\
12998further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12999 &remote_set_cmdlist);
13000 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13001 set_memory_read_packet_size, _("\
13002Set the maximum number of bytes per memory-read packet.\n\
13003Specify the number of bytes in a packet or 0 (zero) for the\n\
13004default packet size. The actual limit is further reduced\n\
13005dependent on the target. Specify ``fixed'' to disable the\n\
13006further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13007 &remote_set_cmdlist);
13008 add_cmd ("memory-write-packet-size", no_class,
13009 show_memory_write_packet_size,
1a966eab 13010 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13011 &remote_show_cmdlist);
13012 add_cmd ("memory-read-packet-size", no_class,
13013 show_memory_read_packet_size,
1a966eab 13014 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13015 &remote_show_cmdlist);
c906108c 13016
b3f42336 13017 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13018 &remote_hw_watchpoint_limit, _("\
13019Set the maximum number of target hardware watchpoints."), _("\
13020Show the maximum number of target hardware watchpoints."), _("\
13021Specify a negative limit for unlimited."),
3e43a32a
MS
13022 NULL, NULL, /* FIXME: i18n: The maximum
13023 number of target hardware
13024 watchpoints is %s. */
b3f42336 13025 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13026 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13027 &remote_hw_watchpoint_length_limit, _("\
13028Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13029Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13030Specify a negative limit for unlimited."),
13031 NULL, NULL, /* FIXME: i18n: The maximum
13032 length (in bytes) of a target
13033 hardware watchpoint is %s. */
13034 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13035 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13036 &remote_hw_breakpoint_limit, _("\
13037Set the maximum number of target hardware breakpoints."), _("\
13038Show the maximum number of target hardware breakpoints."), _("\
13039Specify a negative limit for unlimited."),
3e43a32a
MS
13040 NULL, NULL, /* FIXME: i18n: The maximum
13041 number of target hardware
13042 breakpoints is %s. */
b3f42336 13043 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13044
1b493192
PA
13045 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13046 &remote_address_size, _("\
4d28ad1e
AC
13047Set the maximum size of the address (in bits) in a memory packet."), _("\
13048Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13049 NULL,
13050 NULL, /* FIXME: i18n: */
13051 &setlist, &showlist);
c906108c 13052
ca4f7f8b
PA
13053 init_all_packet_configs ();
13054
444abaca 13055 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13056 "X", "binary-download", 1);
0f71a2f6 13057
444abaca 13058 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13059 "vCont", "verbose-resume", 0);
506fb367 13060
89be2091
DJ
13061 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13062 "QPassSignals", "pass-signals", 0);
13063
9b224c5e
PA
13064 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13065 "QProgramSignals", "program-signals", 0);
13066
444abaca 13067 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13068 "qSymbol", "symbol-lookup", 0);
dc8acb97 13069
444abaca 13070 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13071 "P", "set-register", 1);
d471ea57 13072
444abaca 13073 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13074 "p", "fetch-register", 1);
b96ec7ac 13075
444abaca 13076 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13077 "Z0", "software-breakpoint", 0);
d471ea57 13078
444abaca 13079 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13080 "Z1", "hardware-breakpoint", 0);
d471ea57 13081
444abaca 13082 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13083 "Z2", "write-watchpoint", 0);
d471ea57 13084
444abaca 13085 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13086 "Z3", "read-watchpoint", 0);
d471ea57 13087
444abaca 13088 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13089 "Z4", "access-watchpoint", 0);
d471ea57 13090
0876f84a
DJ
13091 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13092 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13093
c78fa86a
GB
13094 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13095 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13096
23181151
DJ
13097 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13098 "qXfer:features:read", "target-features", 0);
13099
cfa9d6d9
DJ
13100 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13101 "qXfer:libraries:read", "library-info", 0);
13102
2268b414
JK
13103 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13104 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13105
fd79ecee
DJ
13106 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13107 "qXfer:memory-map:read", "memory-map", 0);
13108
0e7f50da
UW
13109 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13110 "qXfer:spu:read", "read-spu-object", 0);
13111
13112 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13113 "qXfer:spu:write", "write-spu-object", 0);
13114
07e059b5
VP
13115 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13116 "qXfer:osdata:read", "osdata", 0);
13117
dc146f7c
VP
13118 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13119 "qXfer:threads:read", "threads", 0);
13120
4aa995e1
PA
13121 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13122 "qXfer:siginfo:read", "read-siginfo-object", 0);
13123
13124 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13125 "qXfer:siginfo:write", "write-siginfo-object", 0);
13126
b3b9301e
PA
13127 add_packet_config_cmd
13128 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13129 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13130
169081d0
TG
13131 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13132 "qXfer:uib:read", "unwind-info-block", 0);
13133
444abaca 13134 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13135 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13136 0);
13137
711e434b
PM
13138 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13139 "qGetTIBAddr", "get-thread-information-block-address",
13140 0);
13141
40ab02ce
MS
13142 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13143 "bc", "reverse-continue", 0);
13144
13145 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13146 "bs", "reverse-step", 0);
13147
be2a5f71
DJ
13148 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13149 "qSupported", "supported-packets", 0);
13150
08388c79
DE
13151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13152 "qSearch:memory", "search-memory", 0);
13153
bd3eecc3
PA
13154 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13155 "qTStatus", "trace-status", 0);
13156
15a201c8
GB
13157 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13158 "vFile:setfs", "hostio-setfs", 0);
13159
a6b151f1
DJ
13160 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13161 "vFile:open", "hostio-open", 0);
13162
13163 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13164 "vFile:pread", "hostio-pread", 0);
13165
13166 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13167 "vFile:pwrite", "hostio-pwrite", 0);
13168
13169 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13170 "vFile:close", "hostio-close", 0);
13171
13172 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13173 "vFile:unlink", "hostio-unlink", 0);
13174
b9e7b9c3
UW
13175 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13176 "vFile:readlink", "hostio-readlink", 0);
13177
0a93529c
GB
13178 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13179 "vFile:fstat", "hostio-fstat", 0);
13180
2d717e4f
DJ
13181 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13182 "vAttach", "attach", 0);
13183
13184 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13185 "vRun", "run", 0);
13186
a6f3e723
SL
13187 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13188 "QStartNoAckMode", "noack", 0);
13189
82f73884
PA
13190 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13191 "vKill", "kill", 0);
13192
0b16c5cf
PA
13193 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13194 "qAttached", "query-attached", 0);
13195
782b2b07 13196 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13197 "ConditionalTracepoints",
13198 "conditional-tracepoints", 0);
3788aec7
LM
13199
13200 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13201 "ConditionalBreakpoints",
13202 "conditional-breakpoints", 0);
13203
d3ce09f5
SS
13204 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13205 "BreakpointCommands",
13206 "breakpoint-commands", 0);
13207
7a697b8d
SS
13208 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13209 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13210
409873ef
SS
13211 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13212 "TracepointSource", "TracepointSource", 0);
13213
d914c394
SS
13214 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13215 "QAllow", "allow", 0);
13216
0fb4aa4b
PA
13217 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13218 "StaticTracepoints", "static-tracepoints", 0);
13219
1e4d1764
YQ
13220 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13221 "InstallInTrace", "install-in-trace", 0);
13222
0fb4aa4b
PA
13223 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13224 "qXfer:statictrace:read", "read-sdata-object", 0);
13225
78d85199
YQ
13226 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13227 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13228
03583c20
UW
13229 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13230 "QDisableRandomization", "disable-randomization", 0);
13231
d1feda86
YQ
13232 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13233 "QAgent", "agent", 0);
13234
f6f899bf
HAQ
13235 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13236 "QTBuffer:size", "trace-buffer-size", 0);
13237
9accd112
MM
13238 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13239 "Qbtrace:off", "disable-btrace", 0);
13240
13241 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13242 "Qbtrace:bts", "enable-btrace-bts", 0);
13243
13244 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13245 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13246
13247 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13248 "qXfer:btrace", "read-btrace", 0);
13249
f4abbc16
MM
13250 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13251 "qXfer:btrace-conf", "read-btrace-conf", 0);
13252
d33501a5
MM
13253 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13254 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13255
73b8c1fd
PA
13256 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13257 "multiprocess-feature", "multiprocess-feature", 0);
13258
f7e6eed5
PA
13259 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13260 "swbreak-feature", "swbreak-feature", 0);
13261
13262 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13263 "hwbreak-feature", "hwbreak-feature", 0);
13264
89245bc0
DB
13265 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13266 "fork-event-feature", "fork-event-feature", 0);
13267
13268 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13269 "vfork-event-feature", "vfork-event-feature", 0);
13270
b20a6524
MM
13271 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13272 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13273
0b736949
DB
13274 /* Assert that we've registered "set remote foo-packet" commands
13275 for all packet configs. */
ca4f7f8b
PA
13276 {
13277 int i;
13278
13279 for (i = 0; i < PACKET_MAX; i++)
13280 {
13281 /* Ideally all configs would have a command associated. Some
13282 still don't though. */
13283 int excepted;
13284
13285 switch (i)
13286 {
13287 case PACKET_QNonStop:
ca4f7f8b
PA
13288 case PACKET_EnableDisableTracepoints_feature:
13289 case PACKET_tracenz_feature:
13290 case PACKET_DisconnectedTracing_feature:
13291 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13292 case PACKET_qCRC:
13293 /* Additions to this list need to be well justified:
13294 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13295 excepted = 1;
13296 break;
13297 default:
13298 excepted = 0;
13299 break;
13300 }
13301
13302 /* This catches both forgetting to add a config command, and
13303 forgetting to remove a packet from the exception list. */
13304 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13305 }
13306 }
13307
37a105a1
DJ
13308 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13309 Z sub-packet has its own set and show commands, but users may
13310 have sets to this variable in their .gdbinit files (or in their
13311 documentation). */
e9e68a56 13312 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13313 &remote_Z_packet_detect, _("\
13314Set use of remote protocol `Z' packets"), _("\
13315Show use of remote protocol `Z' packets "), _("\
3b64bf98 13316When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13317packets."),
e9e68a56 13318 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13319 show_remote_protocol_Z_packet_cmd,
13320 /* FIXME: i18n: Use of remote protocol
13321 `Z' packets is %s. */
e9e68a56 13322 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13323
a6b151f1
DJ
13324 add_prefix_cmd ("remote", class_files, remote_command, _("\
13325Manipulate files on the remote system\n\
13326Transfer files to and from the remote target system."),
13327 &remote_cmdlist, "remote ",
13328 0 /* allow-unknown */, &cmdlist);
13329
13330 add_cmd ("put", class_files, remote_put_command,
13331 _("Copy a local file to the remote system."),
13332 &remote_cmdlist);
13333
13334 add_cmd ("get", class_files, remote_get_command,
13335 _("Copy a remote file to the local system."),
13336 &remote_cmdlist);
13337
13338 add_cmd ("delete", class_files, remote_delete_command,
13339 _("Delete a remote file."),
13340 &remote_cmdlist);
13341
2d717e4f
DJ
13342 remote_exec_file = xstrdup ("");
13343 add_setshow_string_noescape_cmd ("exec-file", class_files,
13344 &remote_exec_file, _("\
13345Set the remote pathname for \"run\""), _("\
13346Show the remote pathname for \"run\""), NULL, NULL, NULL,
13347 &remote_set_cmdlist, &remote_show_cmdlist);
13348
c1e36e3e
PA
13349 add_setshow_boolean_cmd ("range-stepping", class_run,
13350 &use_range_stepping, _("\
13351Enable or disable range stepping."), _("\
13352Show whether target-assisted range stepping is enabled."), _("\
13353If on, and the target supports it, when stepping a source line, GDB\n\
13354tells the target to step the corresponding range of addresses itself instead\n\
13355of issuing multiple single-steps. This speeds up source level\n\
13356stepping. If off, GDB always issues single-steps, even if range\n\
13357stepping is supported by the target. The default is on."),
13358 set_range_stepping,
13359 show_range_stepping,
13360 &setlist,
13361 &showlist);
13362
449092f6
CV
13363 /* Eventually initialize fileio. See fileio.c */
13364 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13365
ba348170 13366 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13367 special ptids with it set to != 0. */
ba348170
PA
13368 magic_null_ptid = ptid_build (42000, -1, 1);
13369 not_sent_ptid = ptid_build (42000, -2, 1);
13370 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13371
13372 target_buf_size = 2048;
13373 target_buf = xmalloc (target_buf_size);
c906108c 13374}
10760264 13375