gdb - Local mods (compile)
[dragonfly.git] / contrib / gdb-7 / gdb / remote.c
CommitLineData
5796c8dc
SS
1/* Remote target communications for serial-line targets in custom GDB protocol
2
25e4902b 3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
5796c8dc
SS
4
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
9 the Free Software Foundation; either version 3 of the License, or
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
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20/* See the GDB User Guide for details of the GDB remote protocol. */
21
22#include "defs.h"
5796c8dc
SS
23#include <ctype.h>
24#include <fcntl.h>
25#include "inferior.h"
25e4902b 26#include "infrun.h"
5796c8dc
SS
27#include "bfd.h"
28#include "symfile.h"
5796c8dc
SS
29#include "target.h"
30/*#include "terminal.h" */
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
35#include "remote.h"
ef5ccd6c 36#include "remote-notif.h"
5796c8dc
SS
37#include "regcache.h"
38#include "value.h"
5796c8dc
SS
39#include "observer.h"
40#include "solib.h"
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
43#include "target-descriptions.h"
ef5ccd6c 44#include "gdb_bfd.h"
25e4902b
AHJ
45#include "filestuff.h"
46#include "rsp-low.h"
5796c8dc 47
5796c8dc
SS
48#include <sys/time.h>
49
50#include "event-loop.h"
51#include "event-top.h"
52#include "inf-loop.h"
53
54#include <signal.h>
55#include "serial.h"
56
57#include "gdbcore.h" /* for exec_bfd */
58
59#include "remote-fileio.h"
60#include "gdb/fileio.h"
25e4902b 61#include <sys/stat.h>
cf7f2e2d 62#include "xml-support.h"
5796c8dc
SS
63
64#include "memory-map.h"
65
cf7f2e2d
JM
66#include "tracepoint.h"
67#include "ax.h"
68#include "ax-gdb.h"
ef5ccd6c
JM
69#include "agent.h"
70#include "btrace.h"
cf7f2e2d 71
c50c785c 72/* Temp hacks for tracepoint encoding migration. */
cf7f2e2d
JM
73static char *target_buf;
74static long target_buf_size;
cf7f2e2d 75
5796c8dc
SS
76/* The size to align memory write packets, when practical. The protocol
77 does not guarantee any alignment, and gdb will generate short
78 writes and unaligned writes, but even as a best-effort attempt this
79 can improve bulk transfers. For instance, if a write is misaligned
80 relative to the target's data bus, the stub may need to make an extra
81 round trip fetching data from the target. This doesn't make a
82 huge difference, but it's easy to do, so we try to be helpful.
83
84 The alignment chosen is arbitrary; usually data bus width is
85 important here, not the possibly larger cache line size. */
86enum { REMOTE_ALIGN_WRITES = 16 };
87
88/* Prototypes for local functions. */
25e4902b 89static void async_cleanup_sigint_signal_handler (void *dummy);
5796c8dc
SS
90static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
91static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
ef5ccd6c 92 int forever, int *is_notif);
5796c8dc 93
25e4902b
AHJ
94static void async_handle_remote_sigint (int);
95static void async_handle_remote_sigint_twice (int);
5796c8dc
SS
96
97static void remote_files_info (struct target_ops *ignore);
98
25e4902b
AHJ
99static void remote_prepare_to_store (struct target_ops *self,
100 struct regcache *regcache);
5796c8dc 101
25e4902b
AHJ
102static void remote_open_1 (const char *, int, struct target_ops *,
103 int extended_p);
5796c8dc 104
25e4902b 105static void remote_close (struct target_ops *self);
5796c8dc 106
25e4902b 107struct remote_state;
5796c8dc 108
25e4902b 109static int remote_vkill (int pid, struct remote_state *rs);
5796c8dc
SS
110
111static void remote_mourn (struct target_ops *ops);
112
113static void extended_remote_restart (void);
114
115static void extended_remote_mourn (struct target_ops *);
116
5796c8dc
SS
117static void remote_send (char **buf, long *sizeof_buf_p);
118
119static int readchar (int timeout);
120
ef5ccd6c
JM
121static void remote_serial_write (const char *str, int len);
122
5796c8dc
SS
123static void remote_kill (struct target_ops *ops);
124
25e4902b 125static int remote_can_async_p (struct target_ops *);
5796c8dc 126
25e4902b 127static int remote_is_async_p (struct target_ops *);
5796c8dc 128
25e4902b 129static void remote_async (struct target_ops *ops, int enable);
5796c8dc 130
25e4902b 131static void sync_remote_interrupt_twice (int signo);
5796c8dc
SS
132
133static void interrupt_query (void);
134
135static void set_general_thread (struct ptid ptid);
136static void set_continue_thread (struct ptid ptid);
137
138static void get_offsets (void);
139
140static void skip_frame (void);
141
142static long read_frame (char **buf_p, long *sizeof_buf);
143
144static int hexnumlen (ULONGEST num);
145
146static void init_remote_ops (void);
147
148static void init_extended_remote_ops (void);
149
25e4902b 150static void remote_stop (struct target_ops *self, ptid_t);
5796c8dc
SS
151
152static int stubhex (int ch);
153
154static int hexnumstr (char *, ULONGEST);
155
156static int hexnumnstr (char *, ULONGEST, int);
157
158static CORE_ADDR remote_address_masked (CORE_ADDR);
159
25e4902b 160static void print_packet (const char *);
5796c8dc 161
5796c8dc
SS
162static void compare_sections_command (char *, int);
163
164static void packet_command (char *, int);
165
166static int stub_unpack_int (char *buff, int fieldlength);
167
168static ptid_t remote_current_thread (ptid_t oldptid);
169
25e4902b 170static int putpkt_binary (const char *buf, int cnt);
5796c8dc
SS
171
172static void check_binary_download (CORE_ADDR addr);
173
174struct packet_config;
175
176static void show_packet_config_cmd (struct packet_config *config);
177
5796c8dc
SS
178static void show_remote_protocol_packet_cmd (struct ui_file *file,
179 int from_tty,
180 struct cmd_list_element *c,
181 const char *value);
182
183static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
184static ptid_t read_ptid (char *buf, char **obuf);
185
25e4902b 186static void remote_set_permissions (struct target_ops *self);
cf7f2e2d 187
25e4902b
AHJ
188static int remote_get_trace_status (struct target_ops *self,
189 struct trace_status *ts);
cf7f2e2d 190
25e4902b
AHJ
191static int remote_upload_tracepoints (struct target_ops *self,
192 struct uploaded_tp **utpp);
cf7f2e2d 193
25e4902b
AHJ
194static int remote_upload_trace_state_variables (struct target_ops *self,
195 struct uploaded_tsv **utsvp);
cf7f2e2d 196
5796c8dc
SS
197static void remote_query_supported (void);
198
25e4902b 199static void remote_check_symbols (void);
5796c8dc
SS
200
201void _initialize_remote (void);
202
203struct stop_reply;
5796c8dc 204static void stop_reply_xfree (struct stop_reply *);
ef5ccd6c 205static void remote_parse_stop_reply (char *, struct stop_reply *);
5796c8dc 206static void push_stop_reply (struct stop_reply *);
25e4902b 207static void discard_pending_stop_replies_in_queue (struct remote_state *);
5796c8dc
SS
208static int peek_stop_reply (ptid_t ptid);
209
25e4902b
AHJ
210struct threads_listing_context;
211static void remove_new_fork_children (struct threads_listing_context *);
212
5796c8dc 213static void remote_async_inferior_event_handler (gdb_client_data);
5796c8dc 214
25e4902b 215static void remote_terminal_ours (struct target_ops *self);
5796c8dc
SS
216
217static int remote_read_description_p (struct target_ops *target);
218
cf7f2e2d
JM
219static void remote_console_output (char *msg);
220
25e4902b
AHJ
221static int remote_supports_cond_breakpoints (struct target_ops *self);
222
223static int remote_can_run_breakpoint_commands (struct target_ops *self);
224
225static void remote_btrace_reset (void);
5796c8dc 226
25e4902b 227static void readahead_cache_invalidate (void);
5796c8dc
SS
228
229/* For "remote". */
230
231static struct cmd_list_element *remote_cmdlist;
232
233/* For "set remote" and "show remote". */
234
235static struct cmd_list_element *remote_set_cmdlist;
236static struct cmd_list_element *remote_show_cmdlist;
237
25e4902b
AHJ
238/* Stub vCont actions support.
239
240 Each field is a boolean flag indicating whether the stub reports
241 support for the corresponding action. */
242
243struct vCont_action_support
244{
245 /* vCont;t */
246 int t;
247
248 /* vCont;r */
249 int r;
250};
251
252/* Controls whether GDB is willing to use range stepping. */
253
254static int use_range_stepping = 1;
255
256#define OPAQUETHREADBYTES 8
257
258/* a 64 bit opaque identifier */
259typedef unsigned char threadref[OPAQUETHREADBYTES];
260
261/* About this many threadisds fit in a packet. */
262
263#define MAXTHREADLISTRESULTS 32
264
265/* Data for the vFile:pread readahead cache. */
266
267struct readahead_cache
268{
269 /* The file descriptor for the file that is being cached. -1 if the
270 cache is invalid. */
271 int fd;
272
273 /* The offset into the file that the cache buffer corresponds
274 to. */
275 ULONGEST offset;
276
277 /* The buffer holding the cache contents. */
278 gdb_byte *buf;
279 /* The buffer's size. We try to read as much as fits into a packet
280 at a time. */
281 size_t bufsize;
282
283 /* Cache hit and miss counters. */
284 ULONGEST hit_count;
285 ULONGEST miss_count;
286};
287
5796c8dc
SS
288/* Description of the remote protocol state for the currently
289 connected target. This is per-target state, and independent of the
290 selected architecture. */
291
292struct remote_state
293{
294 /* A buffer to use for incoming packets, and its current size. The
295 buffer is grown dynamically for larger incoming packets.
296 Outgoing packets may also be constructed in this buffer.
297 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
298 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
299 packets. */
300 char *buf;
301 long buf_size;
302
a45ae5f8
JM
303 /* True if we're going through initial connection setup (finding out
304 about the remote side's threads, relocating symbols, etc.). */
305 int starting_up;
306
5796c8dc
SS
307 /* If we negotiated packet size explicitly (and thus can bypass
308 heuristics for the largest packet size that will not overflow
309 a buffer in the stub), this will be set to that packet size.
310 Otherwise zero, meaning to use the guessed size. */
311 long explicit_packet_size;
312
313 /* remote_wait is normally called when the target is running and
314 waits for a stop reply packet. But sometimes we need to call it
315 when the target is already stopped. We can send a "?" packet
316 and have remote_wait read the response. Or, if we already have
317 the response, we can stash it in BUF and tell remote_wait to
318 skip calling getpkt. This flag is set when BUF contains a
319 stop reply packet and the target is not waiting. */
320 int cached_wait_status;
321
322 /* True, if in no ack mode. That is, neither GDB nor the stub will
323 expect acks from each other. The connection is assumed to be
324 reliable. */
325 int noack_mode;
326
327 /* True if we're connected in extended remote mode. */
328 int extended;
329
5796c8dc
SS
330 /* True if we resumed the target and we're waiting for the target to
331 stop. In the mean time, we can't start another command/query.
332 The remote server wouldn't be ready to process it, so we'd
333 timeout waiting for a reply that would never come and eventually
334 we'd close the connection. This can happen in asynchronous mode
335 because we allow GDB commands while the target is running. */
336 int waiting_for_stop_reply;
337
25e4902b
AHJ
338 /* The status of the stub support for the various vCont actions. */
339 struct vCont_action_support supports_vCont;
5796c8dc 340
25e4902b
AHJ
341 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
342 responded to that. */
343 int ctrlc_pending_p;
5796c8dc 344
25e4902b
AHJ
345 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
346 remote_open knows that we don't have a file open when the program
347 starts. */
348 struct serial *remote_desc;
cf7f2e2d 349
25e4902b
AHJ
350 /* These are the threads which we last sent to the remote system. The
351 TID member will be -1 for all or -2 for not sent yet. */
352 ptid_t general_thread;
353 ptid_t continue_thread;
ef5ccd6c 354
25e4902b
AHJ
355 /* This is the traceframe which we last selected on the remote system.
356 It will be -1 if no traceframe is selected. */
357 int remote_traceframe_number;
ef5ccd6c 358
25e4902b 359 char *last_pass_packet;
cf7f2e2d 360
25e4902b
AHJ
361 /* The last QProgramSignals packet sent to the target. We bypass
362 sending a new program signals list down to the target if the new
363 packet is exactly the same as the last we sent. IOW, we only let
364 the target know about program signals list changes. */
365 char *last_program_signals_packet;
cf7f2e2d 366
25e4902b 367 enum gdb_signal last_sent_signal;
a45ae5f8 368
25e4902b 369 int last_sent_step;
cf7f2e2d 370
25e4902b
AHJ
371 char *finished_object;
372 char *finished_annex;
373 ULONGEST finished_offset;
a45ae5f8 374
25e4902b 375 /* Should we try the 'ThreadInfo' query packet?
a45ae5f8 376
25e4902b
AHJ
377 This variable (NOT available to the user: auto-detect only!)
378 determines whether GDB will use the new, simpler "ThreadInfo"
379 query or the older, more complex syntax for thread queries.
380 This is an auto-detect variable (set to true at each connect,
381 and set to false when the target fails to recognize it). */
382 int use_threadinfo_query;
383 int use_threadextra_query;
384
385 /* This is set to the data address of the access causing the target
386 to stop for a watchpoint. */
387 CORE_ADDR remote_watch_data_address;
388
389 /* Whether the target stopped for a breakpoint/watchpoint. */
390 enum target_stop_reason stop_reason;
391
392 threadref echo_nextthread;
393 threadref nextthread;
394 threadref resultthreadlist[MAXTHREADLISTRESULTS];
395
396 /* The state of remote notification. */
397 struct remote_notif_state *notif_state;
398
399 /* The branch trace configuration. */
400 struct btrace_config btrace_config;
401
402 /* The argument to the last "vFile:setfs:" packet we sent, used
403 to avoid sending repeated unnecessary "vFile:setfs:" packets.
404 Initialized to -1 to indicate that no "vFile:setfs:" packet
405 has yet been sent. */
406 int fs_pid;
407
408 /* A readahead cache for vFile:pread. Often, reading a binary
409 involves a sequence of small reads. E.g., when parsing an ELF
410 file. A readahead cache helps mostly the case of remote
411 debugging on a connection with higher latency, due to the
412 request/reply nature of the RSP. We only cache data for a single
413 file descriptor at a time. */
414 struct readahead_cache readahead_cache;
5796c8dc
SS
415};
416
cf7f2e2d
JM
417/* Private data that we'll store in (struct thread_info)->private. */
418struct private_thread_info
419{
420 char *extra;
421 int core;
422};
423
424static void
425free_private_thread_info (struct private_thread_info *info)
426{
427 xfree (info->extra);
428 xfree (info);
429}
430
5796c8dc
SS
431/* This data could be associated with a target, but we do not always
432 have access to the current target when we need it, so for now it is
433 static. This will be fine for as long as only one target is in use
434 at a time. */
25e4902b 435static struct remote_state *remote_state;
5796c8dc
SS
436
437static struct remote_state *
438get_remote_state_raw (void)
439{
25e4902b
AHJ
440 return remote_state;
441}
442
443/* Allocate a new struct remote_state with xmalloc, initialize it, and
444 return it. */
445
446static struct remote_state *
447new_remote_state (void)
448{
449 struct remote_state *result = XCNEW (struct remote_state);
450
451 /* The default buffer size is unimportant; it will be expanded
452 whenever a larger buffer is needed. */
453 result->buf_size = 400;
454 result->buf = xmalloc (result->buf_size);
455 result->remote_traceframe_number = -1;
456 result->last_sent_signal = GDB_SIGNAL_0;
457 result->fs_pid = -1;
458
459 return result;
5796c8dc
SS
460}
461
462/* Description of the remote protocol for a given architecture. */
463
464struct packet_reg
465{
466 long offset; /* Offset into G packet. */
467 long regnum; /* GDB's internal register number. */
468 LONGEST pnum; /* Remote protocol register number. */
469 int in_g_packet; /* Always part of G packet. */
ef5ccd6c 470 /* long size in bytes; == register_size (target_gdbarch (), regnum);
5796c8dc 471 at present. */
ef5ccd6c 472 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
5796c8dc
SS
473 at present. */
474};
475
476struct remote_arch_state
477{
478 /* Description of the remote protocol registers. */
479 long sizeof_g_packet;
480
481 /* Description of the remote protocol registers indexed by REGNUM
482 (making an array gdbarch_num_regs in size). */
483 struct packet_reg *regs;
484
485 /* This is the size (in chars) of the first response to the ``g''
486 packet. It is used as a heuristic when determining the maximum
487 size of memory-read and memory-write packets. A target will
488 typically only reserve a buffer large enough to hold the ``g''
489 packet. The size does not include packet overhead (headers and
490 trailers). */
491 long actual_register_packet_size;
492
493 /* This is the maximum size (in chars) of a non read/write packet.
494 It is also used as a cap on the size of read/write packets. */
495 long remote_packet_size;
496};
497
cf7f2e2d
JM
498/* Utility: generate error from an incoming stub packet. */
499static void
500trace_error (char *buf)
501{
502 if (*buf++ != 'E')
503 return; /* not an error msg */
504 switch (*buf)
505 {
506 case '1': /* malformed packet error */
507 if (*++buf == '0') /* general case: */
508 error (_("remote.c: error in outgoing packet."));
509 else
510 error (_("remote.c: error in outgoing packet at field #%ld."),
511 strtol (buf, NULL, 16));
cf7f2e2d
JM
512 default:
513 error (_("Target returns error code '%s'."), buf);
514 }
515}
516
517/* Utility: wait for reply from stub, while accepting "O" packets. */
518static char *
519remote_get_noisy_reply (char **buf_p,
520 long *sizeof_buf)
521{
522 do /* Loop on reply from remote stub. */
523 {
524 char *buf;
525
c50c785c 526 QUIT; /* Allow user to bail out with ^C. */
cf7f2e2d
JM
527 getpkt (buf_p, sizeof_buf, 0);
528 buf = *buf_p;
529 if (buf[0] == 'E')
530 trace_error (buf);
25e4902b 531 else if (startswith (buf, "qRelocInsn:"))
cf7f2e2d
JM
532 {
533 ULONGEST ul;
534 CORE_ADDR from, to, org_to;
535 char *p, *pp;
536 int adjusted_size = 0;
25e4902b 537 int relocated = 0;
cf7f2e2d
JM
538
539 p = buf + strlen ("qRelocInsn:");
540 pp = unpack_varlen_hex (p, &ul);
541 if (*pp != ';')
542 error (_("invalid qRelocInsn packet: %s"), buf);
543 from = ul;
544
545 p = pp + 1;
c50c785c 546 unpack_varlen_hex (p, &ul);
cf7f2e2d
JM
547 to = ul;
548
549 org_to = to;
550
25e4902b 551 TRY
cf7f2e2d 552 {
ef5ccd6c 553 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
25e4902b
AHJ
554 relocated = 1;
555 }
556 CATCH (ex, RETURN_MASK_ALL)
557 {
558 if (ex.error == MEMORY_ERROR)
559 {
560 /* Propagate memory errors silently back to the
561 target. The stub may have limited the range of
562 addresses we can write to, for example. */
563 }
564 else
565 {
566 /* Something unexpectedly bad happened. Be verbose
567 so we can tell what, and propagate the error back
568 to the stub, so it doesn't get stuck waiting for
569 a response. */
570 exception_fprintf (gdb_stderr, ex,
571 _("warning: relocating instruction: "));
572 }
573 putpkt ("E01");
cf7f2e2d 574 }
25e4902b
AHJ
575 END_CATCH
576
577 if (relocated)
cf7f2e2d
JM
578 {
579 adjusted_size = to - org_to;
580
ef5ccd6c 581 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
cf7f2e2d
JM
582 putpkt (buf);
583 }
cf7f2e2d
JM
584 }
585 else if (buf[0] == 'O' && buf[1] != 'K')
586 remote_console_output (buf + 1); /* 'O' message from stub */
587 else
c50c785c 588 return buf; /* Here's the actual reply. */
cf7f2e2d
JM
589 }
590 while (1);
591}
5796c8dc
SS
592
593/* Handle for retreving the remote protocol data from gdbarch. */
594static struct gdbarch_data *remote_gdbarch_data_handle;
595
596static struct remote_arch_state *
597get_remote_arch_state (void)
598{
ef5ccd6c 599 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
5796c8dc
SS
600}
601
602/* Fetch the global remote target state. */
603
604static struct remote_state *
605get_remote_state (void)
606{
607 /* Make sure that the remote architecture state has been
608 initialized, because doing so might reallocate rs->buf. Any
609 function which calls getpkt also needs to be mindful of changes
610 to rs->buf, but this call limits the number of places which run
611 into trouble. */
612 get_remote_arch_state ();
613
614 return get_remote_state_raw ();
615}
616
617static int
618compare_pnums (const void *lhs_, const void *rhs_)
619{
620 const struct packet_reg * const *lhs = lhs_;
621 const struct packet_reg * const *rhs = rhs_;
622
623 if ((*lhs)->pnum < (*rhs)->pnum)
624 return -1;
625 else if ((*lhs)->pnum == (*rhs)->pnum)
626 return 0;
627 else
628 return 1;
629}
630
a45ae5f8
JM
631static int
632map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
5796c8dc
SS
633{
634 int regnum, num_remote_regs, offset;
5796c8dc
SS
635 struct packet_reg **remote_regs;
636
5796c8dc
SS
637 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
638 {
a45ae5f8 639 struct packet_reg *r = &regs[regnum];
5796c8dc
SS
640
641 if (register_size (gdbarch, regnum) == 0)
642 /* Do not try to fetch zero-sized (placeholder) registers. */
643 r->pnum = -1;
644 else
645 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
646
647 r->regnum = regnum;
648 }
649
650 /* Define the g/G packet format as the contents of each register
651 with a remote protocol number, in order of ascending protocol
652 number. */
653
654 remote_regs = alloca (gdbarch_num_regs (gdbarch)
a45ae5f8 655 * sizeof (struct packet_reg *));
5796c8dc
SS
656 for (num_remote_regs = 0, regnum = 0;
657 regnum < gdbarch_num_regs (gdbarch);
658 regnum++)
a45ae5f8
JM
659 if (regs[regnum].pnum != -1)
660 remote_regs[num_remote_regs++] = &regs[regnum];
5796c8dc
SS
661
662 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
663 compare_pnums);
664
665 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
666 {
667 remote_regs[regnum]->in_g_packet = 1;
668 remote_regs[regnum]->offset = offset;
669 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
670 }
671
a45ae5f8
JM
672 return offset;
673}
674
675/* Given the architecture described by GDBARCH, return the remote
676 protocol register's number and the register's offset in the g/G
677 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
678 If the target does not have a mapping for REGNUM, return false,
679 otherwise, return true. */
680
681int
682remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
683 int *pnum, int *poffset)
684{
685 int sizeof_g_packet;
686 struct packet_reg *regs;
687 struct cleanup *old_chain;
688
689 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
690
691 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
692 old_chain = make_cleanup (xfree, regs);
693
694 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
695
696 *pnum = regs[regnum].pnum;
697 *poffset = regs[regnum].offset;
698
699 do_cleanups (old_chain);
700
701 return *pnum != -1;
702}
703
704static void *
705init_remote_state (struct gdbarch *gdbarch)
706{
707 struct remote_state *rs = get_remote_state_raw ();
708 struct remote_arch_state *rsa;
709
710 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
711
712 /* Use the architecture to build a regnum<->pnum table, which will be
713 1:1 unless a feature set specifies otherwise. */
714 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
715 gdbarch_num_regs (gdbarch),
716 struct packet_reg);
717
5796c8dc
SS
718 /* Record the maximum possible size of the g packet - it may turn out
719 to be smaller. */
a45ae5f8 720 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
5796c8dc 721
c50c785c 722 /* Default maximum number of characters in a packet body. Many
5796c8dc
SS
723 remote stubs have a hardwired buffer size of 400 bytes
724 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
725 as the maximum packet-size to ensure that the packet and an extra
726 NUL character can always fit in the buffer. This stops GDB
727 trashing stubs that try to squeeze an extra NUL into what is
728 already a full buffer (As of 1999-12-04 that was most stubs). */
729 rsa->remote_packet_size = 400 - 1;
730
731 /* This one is filled in when a ``g'' packet is received. */
732 rsa->actual_register_packet_size = 0;
733
734 /* Should rsa->sizeof_g_packet needs more space than the
c50c785c
JM
735 default, adjust the size accordingly. Remember that each byte is
736 encoded as two characters. 32 is the overhead for the packet
737 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
5796c8dc
SS
738 (``$NN:G...#NN'') is a better guess, the below has been padded a
739 little. */
740 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
741 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
742
743 /* Make sure that the packet buffer is plenty big enough for
744 this architecture. */
745 if (rs->buf_size < rsa->remote_packet_size)
746 {
747 rs->buf_size = 2 * rsa->remote_packet_size;
748 rs->buf = xrealloc (rs->buf, rs->buf_size);
749 }
750
751 return rsa;
752}
753
754/* Return the current allowed size of a remote packet. This is
755 inferred from the current architecture, and should be used to
756 limit the length of outgoing packets. */
757static long
758get_remote_packet_size (void)
759{
760 struct remote_state *rs = get_remote_state ();
761 struct remote_arch_state *rsa = get_remote_arch_state ();
762
763 if (rs->explicit_packet_size)
764 return rs->explicit_packet_size;
765
766 return rsa->remote_packet_size;
767}
768
769static struct packet_reg *
770packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
771{
ef5ccd6c 772 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
5796c8dc
SS
773 return NULL;
774 else
775 {
776 struct packet_reg *r = &rsa->regs[regnum];
cf7f2e2d 777
5796c8dc
SS
778 gdb_assert (r->regnum == regnum);
779 return r;
780 }
781}
782
783static struct packet_reg *
784packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
785{
786 int i;
cf7f2e2d 787
ef5ccd6c 788 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
5796c8dc
SS
789 {
790 struct packet_reg *r = &rsa->regs[i];
cf7f2e2d 791
5796c8dc
SS
792 if (r->pnum == pnum)
793 return r;
794 }
795 return NULL;
796}
797
5796c8dc
SS
798static struct target_ops remote_ops;
799
800static struct target_ops extended_remote_ops;
801
5796c8dc
SS
802/* FIXME: cagney/1999-09-23: Even though getpkt was called with
803 ``forever'' still use the normal timeout mechanism. This is
804 currently used by the ASYNC code to guarentee that target reads
805 during the initial connect always time-out. Once getpkt has been
806 modified to return a timeout indication and, in turn
807 remote_wait()/wait_for_inferior() have gained a timeout parameter
808 this can go away. */
809static int wait_forever_enabled_p = 1;
810
cf7f2e2d
JM
811/* Allow the user to specify what sequence to send to the remote
812 when he requests a program interruption: Although ^C is usually
813 what remote systems expect (this is the default, here), it is
814 sometimes preferable to send a break. On other systems such
815 as the Linux kernel, a break followed by g, which is Magic SysRq g
816 is required in order to interrupt the execution. */
817const char interrupt_sequence_control_c[] = "Ctrl-C";
818const char interrupt_sequence_break[] = "BREAK";
819const char interrupt_sequence_break_g[] = "BREAK-g";
ef5ccd6c 820static const char *const interrupt_sequence_modes[] =
cf7f2e2d
JM
821 {
822 interrupt_sequence_control_c,
823 interrupt_sequence_break,
824 interrupt_sequence_break_g,
825 NULL
826 };
827static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
828
829static void
830show_interrupt_sequence (struct ui_file *file, int from_tty,
831 struct cmd_list_element *c,
832 const char *value)
833{
834 if (interrupt_sequence_mode == interrupt_sequence_control_c)
835 fprintf_filtered (file,
836 _("Send the ASCII ETX character (Ctrl-c) "
837 "to the remote target to interrupt the "
838 "execution of the program.\n"));
839 else if (interrupt_sequence_mode == interrupt_sequence_break)
840 fprintf_filtered (file,
841 _("send a break signal to the remote target "
842 "to interrupt the execution of the program.\n"));
843 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
844 fprintf_filtered (file,
845 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
846 "the remote target to interrupt the execution "
847 "of Linux kernel.\n"));
848 else
849 internal_error (__FILE__, __LINE__,
850 _("Invalid value for interrupt_sequence_mode: %s."),
851 interrupt_sequence_mode);
852}
5796c8dc 853
cf7f2e2d
JM
854/* This boolean variable specifies whether interrupt_sequence is sent
855 to the remote target when gdb connects to it.
856 This is mostly needed when you debug the Linux kernel: The Linux kernel
857 expects BREAK g which is Magic SysRq g for connecting gdb. */
858static int interrupt_on_connect = 0;
5796c8dc 859
cf7f2e2d
JM
860/* This variable is used to implement the "set/show remotebreak" commands.
861 Since these commands are now deprecated in favor of "set/show remote
862 interrupt-sequence", it no longer has any effect on the code. */
5796c8dc
SS
863static int remote_break;
864
cf7f2e2d
JM
865static void
866set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
867{
868 if (remote_break)
869 interrupt_sequence_mode = interrupt_sequence_break;
870 else
871 interrupt_sequence_mode = interrupt_sequence_control_c;
872}
873
874static void
875show_remotebreak (struct ui_file *file, int from_tty,
876 struct cmd_list_element *c,
877 const char *value)
878{
879}
880
5796c8dc
SS
881/* This variable sets the number of bits in an address that are to be
882 sent in a memory ("M" or "m") packet. Normally, after stripping
c50c785c 883 leading zeros, the entire address would be sent. This variable
5796c8dc
SS
884 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
885 initial implementation of remote.c restricted the address sent in
886 memory packets to ``host::sizeof long'' bytes - (typically 32
887 bits). Consequently, for 64 bit targets, the upper 32 bits of an
888 address was never sent. Since fixing this bug may cause a break in
889 some remote targets this variable is principly provided to
890 facilitate backward compatibility. */
891
ef5ccd6c 892static unsigned int remote_address_size;
5796c8dc
SS
893
894/* Temporary to track who currently owns the terminal. See
895 remote_terminal_* for more details. */
896
897static int remote_async_terminal_ours_p;
898
899/* The executable file to use for "run" on the remote side. */
900
901static char *remote_exec_file = "";
902
903\f
904/* User configurable variables for the number of characters in a
905 memory read/write packet. MIN (rsa->remote_packet_size,
906 rsa->sizeof_g_packet) is the default. Some targets need smaller
907 values (fifo overruns, et.al.) and some users need larger values
908 (speed up transfers). The variables ``preferred_*'' (the user
909 request), ``current_*'' (what was actually set) and ``forced_*''
910 (Positive - a soft limit, negative - a hard limit). */
911
912struct memory_packet_config
913{
914 char *name;
915 long size;
916 int fixed_p;
917};
918
919/* Compute the current size of a read/write packet. Since this makes
920 use of ``actual_register_packet_size'' the computation is dynamic. */
921
922static long
923get_memory_packet_size (struct memory_packet_config *config)
924{
925 struct remote_state *rs = get_remote_state ();
926 struct remote_arch_state *rsa = get_remote_arch_state ();
927
928 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
929 law?) that some hosts don't cope very well with large alloca()
930 calls. Eventually the alloca() code will be replaced by calls to
931 xmalloc() and make_cleanups() allowing this restriction to either
932 be lifted or removed. */
933#ifndef MAX_REMOTE_PACKET_SIZE
934#define MAX_REMOTE_PACKET_SIZE 16384
935#endif
936 /* NOTE: 20 ensures we can write at least one byte. */
937#ifndef MIN_REMOTE_PACKET_SIZE
938#define MIN_REMOTE_PACKET_SIZE 20
939#endif
940 long what_they_get;
941 if (config->fixed_p)
942 {
943 if (config->size <= 0)
944 what_they_get = MAX_REMOTE_PACKET_SIZE;
945 else
946 what_they_get = config->size;
947 }
948 else
949 {
950 what_they_get = get_remote_packet_size ();
951 /* Limit the packet to the size specified by the user. */
952 if (config->size > 0
953 && what_they_get > config->size)
954 what_they_get = config->size;
955
956 /* Limit it to the size of the targets ``g'' response unless we have
957 permission from the stub to use a larger packet size. */
958 if (rs->explicit_packet_size == 0
959 && rsa->actual_register_packet_size > 0
960 && what_they_get > rsa->actual_register_packet_size)
961 what_they_get = rsa->actual_register_packet_size;
962 }
963 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
964 what_they_get = MAX_REMOTE_PACKET_SIZE;
965 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
966 what_they_get = MIN_REMOTE_PACKET_SIZE;
967
968 /* Make sure there is room in the global buffer for this packet
969 (including its trailing NUL byte). */
970 if (rs->buf_size < what_they_get + 1)
971 {
972 rs->buf_size = 2 * what_they_get;
973 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
974 }
975
976 return what_they_get;
977}
978
c50c785c 979/* Update the size of a read/write packet. If they user wants
5796c8dc
SS
980 something really big then do a sanity check. */
981
982static void
983set_memory_packet_size (char *args, struct memory_packet_config *config)
984{
985 int fixed_p = config->fixed_p;
986 long size = config->size;
cf7f2e2d 987
5796c8dc
SS
988 if (args == NULL)
989 error (_("Argument required (integer, `fixed' or `limited')."));
990 else if (strcmp (args, "hard") == 0
991 || strcmp (args, "fixed") == 0)
992 fixed_p = 1;
993 else if (strcmp (args, "soft") == 0
994 || strcmp (args, "limit") == 0)
995 fixed_p = 0;
996 else
997 {
998 char *end;
cf7f2e2d 999
5796c8dc
SS
1000 size = strtoul (args, &end, 0);
1001 if (args == end)
1002 error (_("Invalid %s (bad syntax)."), config->name);
1003#if 0
1004 /* Instead of explicitly capping the size of a packet to
1005 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
1006 instead allowed to set the size to something arbitrarily
1007 large. */
1008 if (size > MAX_REMOTE_PACKET_SIZE)
1009 error (_("Invalid %s (too large)."), config->name);
1010#endif
1011 }
1012 /* Extra checks? */
1013 if (fixed_p && !config->fixed_p)
1014 {
1015 if (! query (_("The target may not be able to correctly handle a %s\n"
1016 "of %ld bytes. Change the packet size? "),
1017 config->name, size))
1018 error (_("Packet size not changed."));
1019 }
1020 /* Update the config. */
1021 config->fixed_p = fixed_p;
1022 config->size = size;
1023}
1024
1025static void
1026show_memory_packet_size (struct memory_packet_config *config)
1027{
1028 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1029 if (config->fixed_p)
1030 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1031 get_memory_packet_size (config));
1032 else
1033 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1034 get_memory_packet_size (config));
1035}
1036
1037static struct memory_packet_config memory_write_packet_config =
1038{
1039 "memory-write-packet-size",
1040};
1041
1042static void
1043set_memory_write_packet_size (char *args, int from_tty)
1044{
1045 set_memory_packet_size (args, &memory_write_packet_config);
1046}
1047
1048static void
1049show_memory_write_packet_size (char *args, int from_tty)
1050{
1051 show_memory_packet_size (&memory_write_packet_config);
1052}
1053
1054static long
1055get_memory_write_packet_size (void)
1056{
1057 return get_memory_packet_size (&memory_write_packet_config);
1058}
1059
1060static struct memory_packet_config memory_read_packet_config =
1061{
1062 "memory-read-packet-size",
1063};
1064
1065static void
1066set_memory_read_packet_size (char *args, int from_tty)
1067{
1068 set_memory_packet_size (args, &memory_read_packet_config);
1069}
1070
1071static void
1072show_memory_read_packet_size (char *args, int from_tty)
1073{
1074 show_memory_packet_size (&memory_read_packet_config);
1075}
1076
1077static long
1078get_memory_read_packet_size (void)
1079{
1080 long size = get_memory_packet_size (&memory_read_packet_config);
cf7f2e2d 1081
5796c8dc
SS
1082 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1083 extra buffer size argument before the memory read size can be
1084 increased beyond this. */
1085 if (size > get_remote_packet_size ())
1086 size = get_remote_packet_size ();
1087 return size;
1088}
1089
1090\f
1091/* Generic configuration support for packets the stub optionally
c50c785c 1092 supports. Allows the user to specify the use of the packet as well
5796c8dc
SS
1093 as allowing GDB to auto-detect support in the remote stub. */
1094
1095enum packet_support
1096 {
1097 PACKET_SUPPORT_UNKNOWN = 0,
1098 PACKET_ENABLE,
1099 PACKET_DISABLE
1100 };
1101
1102struct packet_config
1103 {
1104 const char *name;
1105 const char *title;
25e4902b
AHJ
1106
1107 /* If auto, GDB auto-detects support for this packet or feature,
1108 either through qSupported, or by trying the packet and looking
1109 at the response. If true, GDB assumes the target supports this
1110 packet. If false, the packet is disabled. Configs that don't
1111 have an associated command always have this set to auto. */
5796c8dc 1112 enum auto_boolean detect;
25e4902b
AHJ
1113
1114 /* Does the target support this packet? */
5796c8dc
SS
1115 enum packet_support support;
1116 };
1117
1118/* Analyze a packet's return value and update the packet config
1119 accordingly. */
1120
1121enum packet_result
1122{
1123 PACKET_ERROR,
1124 PACKET_OK,
1125 PACKET_UNKNOWN
1126};
1127
25e4902b
AHJ
1128static enum packet_support packet_config_support (struct packet_config *config);
1129static enum packet_support packet_support (int packet);
5796c8dc
SS
1130
1131static void
1132show_packet_config_cmd (struct packet_config *config)
1133{
1134 char *support = "internal-error";
cf7f2e2d 1135
25e4902b 1136 switch (packet_config_support (config))
5796c8dc
SS
1137 {
1138 case PACKET_ENABLE:
1139 support = "enabled";
1140 break;
1141 case PACKET_DISABLE:
1142 support = "disabled";
1143 break;
1144 case PACKET_SUPPORT_UNKNOWN:
1145 support = "unknown";
1146 break;
1147 }
1148 switch (config->detect)
1149 {
1150 case AUTO_BOOLEAN_AUTO:
c50c785c
JM
1151 printf_filtered (_("Support for the `%s' packet "
1152 "is auto-detected, currently %s.\n"),
5796c8dc
SS
1153 config->name, support);
1154 break;
1155 case AUTO_BOOLEAN_TRUE:
1156 case AUTO_BOOLEAN_FALSE:
1157 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1158 config->name, support);
1159 break;
1160 }
1161}
1162
1163static void
1164add_packet_config_cmd (struct packet_config *config, const char *name,
1165 const char *title, int legacy)
1166{
1167 char *set_doc;
1168 char *show_doc;
1169 char *cmd_name;
1170
1171 config->name = name;
1172 config->title = title;
5796c8dc
SS
1173 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1174 name, title);
c50c785c
JM
1175 show_doc = xstrprintf ("Show current use of remote "
1176 "protocol `%s' (%s) packet",
5796c8dc
SS
1177 name, title);
1178 /* set/show TITLE-packet {auto,on,off} */
1179 cmd_name = xstrprintf ("%s-packet", title);
1180 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
c50c785c
JM
1181 &config->detect, set_doc,
1182 show_doc, NULL, /* help_doc */
25e4902b 1183 NULL,
5796c8dc
SS
1184 show_remote_protocol_packet_cmd,
1185 &remote_set_cmdlist, &remote_show_cmdlist);
1186 /* The command code copies the documentation strings. */
1187 xfree (set_doc);
1188 xfree (show_doc);
1189 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1190 if (legacy)
1191 {
1192 char *legacy_name;
cf7f2e2d 1193
5796c8dc
SS
1194 legacy_name = xstrprintf ("%s-packet", name);
1195 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1196 &remote_set_cmdlist);
1197 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1198 &remote_show_cmdlist);
1199 }
1200}
1201
1202static enum packet_result
1203packet_check_result (const char *buf)
1204{
1205 if (buf[0] != '\0')
1206 {
1207 /* The stub recognized the packet request. Check that the
1208 operation succeeded. */
1209 if (buf[0] == 'E'
1210 && isxdigit (buf[1]) && isxdigit (buf[2])
1211 && buf[3] == '\0')
1212 /* "Enn" - definitly an error. */
1213 return PACKET_ERROR;
1214
1215 /* Always treat "E." as an error. This will be used for
1216 more verbose error messages, such as E.memtypes. */
1217 if (buf[0] == 'E' && buf[1] == '.')
1218 return PACKET_ERROR;
1219
1220 /* The packet may or may not be OK. Just assume it is. */
1221 return PACKET_OK;
1222 }
1223 else
1224 /* The stub does not support the packet. */
1225 return PACKET_UNKNOWN;
1226}
1227
1228static enum packet_result
1229packet_ok (const char *buf, struct packet_config *config)
1230{
1231 enum packet_result result;
1232
25e4902b
AHJ
1233 if (config->detect != AUTO_BOOLEAN_TRUE
1234 && config->support == PACKET_DISABLE)
1235 internal_error (__FILE__, __LINE__,
1236 _("packet_ok: attempt to use a disabled packet"));
1237
5796c8dc
SS
1238 result = packet_check_result (buf);
1239 switch (result)
1240 {
1241 case PACKET_OK:
1242 case PACKET_ERROR:
1243 /* The stub recognized the packet request. */
25e4902b 1244 if (config->support == PACKET_SUPPORT_UNKNOWN)
5796c8dc 1245 {
5796c8dc
SS
1246 if (remote_debug)
1247 fprintf_unfiltered (gdb_stdlog,
25e4902b
AHJ
1248 "Packet %s (%s) is supported\n",
1249 config->name, config->title);
5796c8dc 1250 config->support = PACKET_ENABLE;
5796c8dc
SS
1251 }
1252 break;
1253 case PACKET_UNKNOWN:
1254 /* The stub does not support the packet. */
25e4902b
AHJ
1255 if (config->detect == AUTO_BOOLEAN_AUTO
1256 && config->support == PACKET_ENABLE)
5796c8dc 1257 {
25e4902b
AHJ
1258 /* If the stub previously indicated that the packet was
1259 supported then there is a protocol error. */
1260 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1261 config->name, config->title);
5796c8dc 1262 }
25e4902b
AHJ
1263 else if (config->detect == AUTO_BOOLEAN_TRUE)
1264 {
1265 /* The user set it wrong. */
1266 error (_("Enabled packet %s (%s) not recognized by stub"),
1267 config->name, config->title);
1268 }
1269
1270 if (remote_debug)
1271 fprintf_unfiltered (gdb_stdlog,
1272 "Packet %s (%s) is NOT supported\n",
1273 config->name, config->title);
1274 config->support = PACKET_DISABLE;
5796c8dc
SS
1275 break;
1276 }
1277
1278 return result;
1279}
1280
1281enum {
1282 PACKET_vCont = 0,
1283 PACKET_X,
1284 PACKET_qSymbol,
1285 PACKET_P,
1286 PACKET_p,
1287 PACKET_Z0,
1288 PACKET_Z1,
1289 PACKET_Z2,
1290 PACKET_Z3,
1291 PACKET_Z4,
25e4902b 1292 PACKET_vFile_setfs,
5796c8dc
SS
1293 PACKET_vFile_open,
1294 PACKET_vFile_pread,
1295 PACKET_vFile_pwrite,
1296 PACKET_vFile_close,
1297 PACKET_vFile_unlink,
ef5ccd6c 1298 PACKET_vFile_readlink,
25e4902b 1299 PACKET_vFile_fstat,
5796c8dc
SS
1300 PACKET_qXfer_auxv,
1301 PACKET_qXfer_features,
25e4902b 1302 PACKET_qXfer_exec_file,
5796c8dc 1303 PACKET_qXfer_libraries,
a45ae5f8 1304 PACKET_qXfer_libraries_svr4,
5796c8dc
SS
1305 PACKET_qXfer_memory_map,
1306 PACKET_qXfer_spu_read,
1307 PACKET_qXfer_spu_write,
1308 PACKET_qXfer_osdata,
cf7f2e2d
JM
1309 PACKET_qXfer_threads,
1310 PACKET_qXfer_statictrace_read,
c50c785c 1311 PACKET_qXfer_traceframe_info,
ef5ccd6c 1312 PACKET_qXfer_uib,
cf7f2e2d 1313 PACKET_qGetTIBAddr,
5796c8dc
SS
1314 PACKET_qGetTLSAddr,
1315 PACKET_qSupported,
25e4902b 1316 PACKET_qTStatus,
5796c8dc 1317 PACKET_QPassSignals,
ef5ccd6c 1318 PACKET_QProgramSignals,
25e4902b 1319 PACKET_qCRC,
5796c8dc
SS
1320 PACKET_qSearch_memory,
1321 PACKET_vAttach,
1322 PACKET_vRun,
1323 PACKET_QStartNoAckMode,
1324 PACKET_vKill,
1325 PACKET_qXfer_siginfo_read,
1326 PACKET_qXfer_siginfo_write,
1327 PACKET_qAttached,
25e4902b
AHJ
1328
1329 /* Support for conditional tracepoints. */
5796c8dc 1330 PACKET_ConditionalTracepoints,
25e4902b
AHJ
1331
1332 /* Support for target-side breakpoint conditions. */
ef5ccd6c 1333 PACKET_ConditionalBreakpoints,
25e4902b
AHJ
1334
1335 /* Support for target-side breakpoint commands. */
ef5ccd6c 1336 PACKET_BreakpointCommands,
25e4902b
AHJ
1337
1338 /* Support for fast tracepoints. */
cf7f2e2d 1339 PACKET_FastTracepoints,
25e4902b
AHJ
1340
1341 /* Support for static tracepoints. */
cf7f2e2d 1342 PACKET_StaticTracepoints,
25e4902b
AHJ
1343
1344 /* Support for installing tracepoints while a trace experiment is
1345 running. */
a45ae5f8 1346 PACKET_InstallInTrace,
25e4902b 1347
5796c8dc
SS
1348 PACKET_bc,
1349 PACKET_bs,
cf7f2e2d
JM
1350 PACKET_TracepointSource,
1351 PACKET_QAllow,
a45ae5f8
JM
1352 PACKET_qXfer_fdpic,
1353 PACKET_QDisableRandomization,
ef5ccd6c
JM
1354 PACKET_QAgent,
1355 PACKET_QTBuffer_size,
1356 PACKET_Qbtrace_off,
1357 PACKET_Qbtrace_bts,
25e4902b 1358 PACKET_Qbtrace_pt,
ef5ccd6c 1359 PACKET_qXfer_btrace,
25e4902b
AHJ
1360
1361 /* Support for the QNonStop packet. */
1362 PACKET_QNonStop,
1363
1364 /* Support for multi-process extensions. */
1365 PACKET_multiprocess_feature,
1366
1367 /* Support for enabling and disabling tracepoints while a trace
1368 experiment is running. */
1369 PACKET_EnableDisableTracepoints_feature,
1370
1371 /* Support for collecting strings using the tracenz bytecode. */
1372 PACKET_tracenz_feature,
1373
1374 /* Support for continuing to run a trace experiment while GDB is
1375 disconnected. */
1376 PACKET_DisconnectedTracing_feature,
1377
1378 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1379 PACKET_augmented_libraries_svr4_read_feature,
1380
1381 /* Support for the qXfer:btrace-conf:read packet. */
1382 PACKET_qXfer_btrace_conf,
1383
1384 /* Support for the Qbtrace-conf:bts:size packet. */
1385 PACKET_Qbtrace_conf_bts_size,
1386
1387 /* Support for swbreak+ feature. */
1388 PACKET_swbreak_feature,
1389
1390 /* Support for hwbreak+ feature. */
1391 PACKET_hwbreak_feature,
1392
1393 /* Support for fork events. */
1394 PACKET_fork_event_feature,
1395
1396 /* Support for vfork events. */
1397 PACKET_vfork_event_feature,
1398
1399 /* Support for the Qbtrace-conf:pt:size packet. */
1400 PACKET_Qbtrace_conf_pt_size,
1401
5796c8dc
SS
1402 PACKET_MAX
1403};
1404
1405static struct packet_config remote_protocol_packets[PACKET_MAX];
1406
25e4902b
AHJ
1407/* Returns the packet's corresponding "set remote foo-packet" command
1408 state. See struct packet_config for more details. */
1409
1410static enum auto_boolean
1411packet_set_cmd_state (int packet)
5796c8dc 1412{
25e4902b
AHJ
1413 return remote_protocol_packets[packet].detect;
1414}
5796c8dc 1415
25e4902b
AHJ
1416/* Returns whether a given packet or feature is supported. This takes
1417 into account the state of the corresponding "set remote foo-packet"
1418 command, which may be used to bypass auto-detection. */
1419
1420static enum packet_support
1421packet_config_support (struct packet_config *config)
1422{
1423 switch (config->detect)
5796c8dc 1424 {
25e4902b
AHJ
1425 case AUTO_BOOLEAN_TRUE:
1426 return PACKET_ENABLE;
1427 case AUTO_BOOLEAN_FALSE:
1428 return PACKET_DISABLE;
1429 case AUTO_BOOLEAN_AUTO:
1430 return config->support;
1431 default:
1432 gdb_assert_not_reached (_("bad switch"));
5796c8dc 1433 }
25e4902b
AHJ
1434}
1435
1436/* Same as packet_config_support, but takes the packet's enum value as
1437 argument. */
1438
1439static enum packet_support
1440packet_support (int packet)
1441{
1442 struct packet_config *config = &remote_protocol_packets[packet];
1443
1444 return packet_config_support (config);
5796c8dc
SS
1445}
1446
1447static void
1448show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1449 struct cmd_list_element *c,
1450 const char *value)
1451{
1452 struct packet_config *packet;
1453
1454 for (packet = remote_protocol_packets;
1455 packet < &remote_protocol_packets[PACKET_MAX];
1456 packet++)
1457 {
1458 if (&packet->detect == c->var)
1459 {
1460 show_packet_config_cmd (packet);
1461 return;
1462 }
1463 }
c50c785c 1464 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
5796c8dc
SS
1465 c->name);
1466}
1467
1468/* Should we try one of the 'Z' requests? */
1469
1470enum Z_packet_type
1471{
1472 Z_PACKET_SOFTWARE_BP,
1473 Z_PACKET_HARDWARE_BP,
1474 Z_PACKET_WRITE_WP,
1475 Z_PACKET_READ_WP,
1476 Z_PACKET_ACCESS_WP,
1477 NR_Z_PACKET_TYPES
1478};
1479
1480/* For compatibility with older distributions. Provide a ``set remote
1481 Z-packet ...'' command that updates all the Z packet types. */
1482
1483static enum auto_boolean remote_Z_packet_detect;
1484
1485static void
1486set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1487 struct cmd_list_element *c)
1488{
1489 int i;
cf7f2e2d 1490
5796c8dc 1491 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
25e4902b 1492 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
5796c8dc
SS
1493}
1494
1495static void
1496show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1497 struct cmd_list_element *c,
1498 const char *value)
1499{
1500 int i;
cf7f2e2d 1501
5796c8dc
SS
1502 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1503 {
1504 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1505 }
1506}
1507
25e4902b
AHJ
1508/* Returns true if the multi-process extensions are in effect. */
1509
1510static int
1511remote_multi_process_p (struct remote_state *rs)
1512{
1513 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1514}
1515
1516/* Returns true if fork events are supported. */
1517
1518static int
1519remote_fork_event_p (struct remote_state *rs)
1520{
1521 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1522}
1523
1524/* Returns true if vfork events are supported. */
1525
1526static int
1527remote_vfork_event_p (struct remote_state *rs)
1528{
1529 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1530}
1531
1532/* Insert fork catchpoint target routine. If fork events are enabled
1533 then return success, nothing more to do. */
1534
1535static int
1536remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1537{
1538 struct remote_state *rs = get_remote_state ();
1539
1540 return !remote_fork_event_p (rs);
1541}
1542
1543/* Remove fork catchpoint target routine. Nothing to do, just
1544 return success. */
1545
1546static int
1547remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1548{
1549 return 0;
1550}
1551
1552/* Insert vfork catchpoint target routine. If vfork events are enabled
1553 then return success, nothing more to do. */
1554
1555static int
1556remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1557{
1558 struct remote_state *rs = get_remote_state ();
1559
1560 return !remote_vfork_event_p (rs);
1561}
5796c8dc 1562
25e4902b
AHJ
1563/* Remove vfork catchpoint target routine. Nothing to do, just
1564 return success. */
5796c8dc 1565
25e4902b
AHJ
1566static int
1567remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1568{
1569 return 0;
1570}
5796c8dc
SS
1571
1572/* Tokens for use by the asynchronous signal handlers for SIGINT. */
25e4902b
AHJ
1573static struct async_signal_handler *async_sigint_remote_twice_token;
1574static struct async_signal_handler *async_sigint_remote_token;
5796c8dc
SS
1575
1576\f
1577/* Asynchronous signal handle registered as event loop source for
1578 when we have pending events ready to be passed to the core. */
1579
1580static struct async_event_handler *remote_async_inferior_event_token;
1581
5796c8dc
SS
1582\f
1583
1584static ptid_t magic_null_ptid;
1585static ptid_t not_sent_ptid;
1586static ptid_t any_thread_ptid;
1587
5796c8dc
SS
1588/* Find out if the stub attached to PID (and hence GDB should offer to
1589 detach instead of killing it when bailing out). */
1590
1591static int
1592remote_query_attached (int pid)
1593{
1594 struct remote_state *rs = get_remote_state ();
ef5ccd6c 1595 size_t size = get_remote_packet_size ();
5796c8dc 1596
25e4902b 1597 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
5796c8dc
SS
1598 return 0;
1599
1600 if (remote_multi_process_p (rs))
ef5ccd6c 1601 xsnprintf (rs->buf, size, "qAttached:%x", pid);
5796c8dc 1602 else
ef5ccd6c 1603 xsnprintf (rs->buf, size, "qAttached");
5796c8dc
SS
1604
1605 putpkt (rs->buf);
1606 getpkt (&rs->buf, &rs->buf_size, 0);
1607
1608 switch (packet_ok (rs->buf,
1609 &remote_protocol_packets[PACKET_qAttached]))
1610 {
1611 case PACKET_OK:
1612 if (strcmp (rs->buf, "1") == 0)
1613 return 1;
1614 break;
1615 case PACKET_ERROR:
1616 warning (_("Remote failure reply: %s"), rs->buf);
1617 break;
1618 case PACKET_UNKNOWN:
1619 break;
1620 }
1621
1622 return 0;
1623}
1624
ef5ccd6c
JM
1625/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1626 has been invented by GDB, instead of reported by the target. Since
1627 we can be connected to a remote system before before knowing about
1628 any inferior, mark the target with execution when we find the first
1629 inferior. If ATTACHED is 1, then we had just attached to this
1630 inferior. If it is 0, then we just created this inferior. If it
1631 is -1, then try querying the remote stub to find out if it had
25e4902b
AHJ
1632 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1633 attempt to open this inferior's executable as the main executable
1634 if no main executable is open already. */
5796c8dc
SS
1635
1636static struct inferior *
25e4902b
AHJ
1637remote_add_inferior (int fake_pid_p, int pid, int attached,
1638 int try_open_exec)
5796c8dc
SS
1639{
1640 struct inferior *inf;
1641
1642 /* Check whether this process we're learning about is to be
1643 considered attached, or if is to be considered to have been
1644 spawned by the stub. */
1645 if (attached == -1)
1646 attached = remote_query_attached (pid);
1647
ef5ccd6c 1648 if (gdbarch_has_global_solist (target_gdbarch ()))
cf7f2e2d
JM
1649 {
1650 /* If the target shares code across all inferiors, then every
1651 attach adds a new inferior. */
1652 inf = add_inferior (pid);
1653
1654 /* ... and every inferior is bound to the same program space.
1655 However, each inferior may still have its own address
1656 space. */
1657 inf->aspace = maybe_new_address_space ();
1658 inf->pspace = current_program_space;
1659 }
1660 else
1661 {
1662 /* In the traditional debugging scenario, there's a 1-1 match
1663 between program/address spaces. We simply bind the inferior
1664 to the program space's address space. */
1665 inf = current_inferior ();
1666 inferior_appeared (inf, pid);
1667 }
5796c8dc
SS
1668
1669 inf->attach_flag = attached;
ef5ccd6c 1670 inf->fake_pid_p = fake_pid_p;
5796c8dc 1671
25e4902b
AHJ
1672 /* If no main executable is currently open then attempt to
1673 open the file that was executed to create this inferior. */
1674 if (try_open_exec && get_exec_file (0) == NULL)
1675 exec_file_locate_attach (pid, 1);
1676
5796c8dc
SS
1677 return inf;
1678}
1679
1680/* Add thread PTID to GDB's thread list. Tag it as executing/running
1681 according to RUNNING. */
1682
1683static void
1684remote_add_thread (ptid_t ptid, int running)
1685{
25e4902b
AHJ
1686 struct remote_state *rs = get_remote_state ();
1687
1688 /* GDB historically didn't pull threads in the initial connection
1689 setup. If the remote target doesn't even have a concept of
1690 threads (e.g., a bare-metal target), even if internally we
1691 consider that a single-threaded target, mentioning a new thread
1692 might be confusing to the user. Be silent then, preserving the
1693 age old behavior. */
1694 if (rs->starting_up)
1695 add_thread_silent (ptid);
1696 else
1697 add_thread (ptid);
5796c8dc
SS
1698
1699 set_executing (ptid, running);
1700 set_running (ptid, running);
1701}
1702
1703/* Come here when we learn about a thread id from the remote target.
1704 It may be the first time we hear about such thread, so take the
1705 opportunity to add it to GDB's thread list. In case this is the
1706 first time we're noticing its corresponding inferior, add it to
1707 GDB's inferior list as well. */
1708
1709static void
1710remote_notice_new_inferior (ptid_t currthread, int running)
1711{
1712 /* If this is a new thread, add it to GDB's thread list.
1713 If we leave it up to WFI to do this, bad things will happen. */
1714
1715 if (in_thread_list (currthread) && is_exited (currthread))
1716 {
1717 /* We're seeing an event on a thread id we knew had exited.
1718 This has to be a new thread reusing the old id. Add it. */
1719 remote_add_thread (currthread, running);
1720 return;
1721 }
1722
1723 if (!in_thread_list (currthread))
1724 {
1725 struct inferior *inf = NULL;
1726 int pid = ptid_get_pid (currthread);
1727
1728 if (ptid_is_pid (inferior_ptid)
1729 && pid == ptid_get_pid (inferior_ptid))
1730 {
1731 /* inferior_ptid has no thread member yet. This can happen
1732 with the vAttach -> remote_wait,"TAAthread:" path if the
1733 stub doesn't support qC. This is the first stop reported
1734 after an attach, so this is the main thread. Update the
1735 ptid in the thread list. */
1736 if (in_thread_list (pid_to_ptid (pid)))
1737 thread_change_ptid (inferior_ptid, currthread);
1738 else
1739 {
1740 remote_add_thread (currthread, running);
1741 inferior_ptid = currthread;
1742 }
cf7f2e2d 1743 return;
5796c8dc
SS
1744 }
1745
1746 if (ptid_equal (magic_null_ptid, inferior_ptid))
1747 {
1748 /* inferior_ptid is not set yet. This can happen with the
1749 vRun -> remote_wait,"TAAthread:" path if the stub
1750 doesn't support qC. This is the first stop reported
1751 after an attach, so this is the main thread. Update the
1752 ptid in the thread list. */
cf7f2e2d 1753 thread_change_ptid (inferior_ptid, currthread);
5796c8dc
SS
1754 return;
1755 }
1756
1757 /* When connecting to a target remote, or to a target
1758 extended-remote which already was debugging an inferior, we
1759 may not know about it yet. Add it before adding its child
1760 thread, so notifications are emitted in a sensible order. */
1761 if (!in_inferior_list (ptid_get_pid (currthread)))
ef5ccd6c
JM
1762 {
1763 struct remote_state *rs = get_remote_state ();
1764 int fake_pid_p = !remote_multi_process_p (rs);
1765
1766 inf = remote_add_inferior (fake_pid_p,
25e4902b 1767 ptid_get_pid (currthread), -1, 1);
ef5ccd6c 1768 }
5796c8dc
SS
1769
1770 /* This is really a new thread. Add it. */
1771 remote_add_thread (currthread, running);
1772
1773 /* If we found a new inferior, let the common code do whatever
1774 it needs to with it (e.g., read shared libraries, insert
25e4902b
AHJ
1775 breakpoints), unless we're just setting up an all-stop
1776 connection. */
5796c8dc 1777 if (inf != NULL)
25e4902b
AHJ
1778 {
1779 struct remote_state *rs = get_remote_state ();
1780
1781 if (non_stop || !rs->starting_up)
1782 notice_new_inferior (currthread, running, 0);
1783 }
5796c8dc
SS
1784 }
1785}
1786
cf7f2e2d
JM
1787/* Return the private thread data, creating it if necessary. */
1788
ef5ccd6c 1789static struct private_thread_info *
cf7f2e2d
JM
1790demand_private_info (ptid_t ptid)
1791{
1792 struct thread_info *info = find_thread_ptid (ptid);
1793
1794 gdb_assert (info);
1795
25e4902b 1796 if (!info->priv)
cf7f2e2d 1797 {
25e4902b 1798 info->priv = xmalloc (sizeof (*(info->priv)));
cf7f2e2d 1799 info->private_dtor = free_private_thread_info;
25e4902b
AHJ
1800 info->priv->core = -1;
1801 info->priv->extra = 0;
cf7f2e2d
JM
1802 }
1803
25e4902b 1804 return info->priv;
cf7f2e2d
JM
1805}
1806
5796c8dc
SS
1807/* Call this function as a result of
1808 1) A halt indication (T packet) containing a thread id
1809 2) A direct query of currthread
c50c785c 1810 3) Successful execution of set thread */
5796c8dc
SS
1811
1812static void
25e4902b 1813record_currthread (struct remote_state *rs, ptid_t currthread)
5796c8dc 1814{
25e4902b 1815 rs->general_thread = currthread;
5796c8dc
SS
1816}
1817
5796c8dc
SS
1818/* If 'QPassSignals' is supported, tell the remote stub what signals
1819 it can simply pass through to the inferior without reporting. */
1820
1821static void
25e4902b
AHJ
1822remote_pass_signals (struct target_ops *self,
1823 int numsigs, unsigned char *pass_signals)
5796c8dc 1824{
25e4902b 1825 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
5796c8dc
SS
1826 {
1827 char *pass_packet, *p;
5796c8dc 1828 int count = 0, i;
25e4902b 1829 struct remote_state *rs = get_remote_state ();
5796c8dc
SS
1830
1831 gdb_assert (numsigs < 256);
1832 for (i = 0; i < numsigs; i++)
1833 {
a45ae5f8 1834 if (pass_signals[i])
5796c8dc
SS
1835 count++;
1836 }
1837 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1838 strcpy (pass_packet, "QPassSignals:");
1839 p = pass_packet + strlen (pass_packet);
1840 for (i = 0; i < numsigs; i++)
1841 {
a45ae5f8 1842 if (pass_signals[i])
5796c8dc
SS
1843 {
1844 if (i >= 16)
1845 *p++ = tohex (i >> 4);
1846 *p++ = tohex (i & 15);
1847 if (count)
1848 *p++ = ';';
1849 else
1850 break;
1851 count--;
1852 }
1853 }
1854 *p = 0;
25e4902b 1855 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
5796c8dc 1856 {
5796c8dc
SS
1857 putpkt (pass_packet);
1858 getpkt (&rs->buf, &rs->buf_size, 0);
25e4902b
AHJ
1859 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1860 if (rs->last_pass_packet)
1861 xfree (rs->last_pass_packet);
1862 rs->last_pass_packet = pass_packet;
5796c8dc
SS
1863 }
1864 else
1865 xfree (pass_packet);
1866 }
1867}
1868
ef5ccd6c
JM
1869/* If 'QProgramSignals' is supported, tell the remote stub what
1870 signals it should pass through to the inferior when detaching. */
1871
1872static void
25e4902b
AHJ
1873remote_program_signals (struct target_ops *self,
1874 int numsigs, unsigned char *signals)
ef5ccd6c 1875{
25e4902b 1876 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
ef5ccd6c
JM
1877 {
1878 char *packet, *p;
1879 int count = 0, i;
25e4902b 1880 struct remote_state *rs = get_remote_state ();
ef5ccd6c
JM
1881
1882 gdb_assert (numsigs < 256);
1883 for (i = 0; i < numsigs; i++)
1884 {
1885 if (signals[i])
1886 count++;
1887 }
1888 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1889 strcpy (packet, "QProgramSignals:");
1890 p = packet + strlen (packet);
1891 for (i = 0; i < numsigs; i++)
1892 {
1893 if (signal_pass_state (i))
1894 {
1895 if (i >= 16)
1896 *p++ = tohex (i >> 4);
1897 *p++ = tohex (i & 15);
1898 if (count)
1899 *p++ = ';';
1900 else
1901 break;
1902 count--;
1903 }
1904 }
1905 *p = 0;
25e4902b
AHJ
1906 if (!rs->last_program_signals_packet
1907 || strcmp (rs->last_program_signals_packet, packet) != 0)
ef5ccd6c 1908 {
ef5ccd6c
JM
1909 putpkt (packet);
1910 getpkt (&rs->buf, &rs->buf_size, 0);
25e4902b
AHJ
1911 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1912 xfree (rs->last_program_signals_packet);
1913 rs->last_program_signals_packet = packet;
ef5ccd6c
JM
1914 }
1915 else
1916 xfree (packet);
1917 }
1918}
1919
5796c8dc
SS
1920/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1921 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1922 thread. If GEN is set, set the general thread, if not, then set
1923 the step/continue thread. */
1924static void
1925set_thread (struct ptid ptid, int gen)
1926{
1927 struct remote_state *rs = get_remote_state ();
25e4902b 1928 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
5796c8dc
SS
1929 char *buf = rs->buf;
1930 char *endbuf = rs->buf + get_remote_packet_size ();
1931
1932 if (ptid_equal (state, ptid))
1933 return;
1934
1935 *buf++ = 'H';
1936 *buf++ = gen ? 'g' : 'c';
1937 if (ptid_equal (ptid, magic_null_ptid))
1938 xsnprintf (buf, endbuf - buf, "0");
1939 else if (ptid_equal (ptid, any_thread_ptid))
1940 xsnprintf (buf, endbuf - buf, "0");
1941 else if (ptid_equal (ptid, minus_one_ptid))
1942 xsnprintf (buf, endbuf - buf, "-1");
1943 else
1944 write_ptid (buf, endbuf, ptid);
1945 putpkt (rs->buf);
1946 getpkt (&rs->buf, &rs->buf_size, 0);
1947 if (gen)
25e4902b 1948 rs->general_thread = ptid;
5796c8dc 1949 else
25e4902b 1950 rs->continue_thread = ptid;
5796c8dc
SS
1951}
1952
1953static void
1954set_general_thread (struct ptid ptid)
1955{
1956 set_thread (ptid, 1);
1957}
1958
1959static void
1960set_continue_thread (struct ptid ptid)
1961{
1962 set_thread (ptid, 0);
1963}
1964
1965/* Change the remote current process. Which thread within the process
1966 ends up selected isn't important, as long as it is the same process
1967 as what INFERIOR_PTID points to.
1968
1969 This comes from that fact that there is no explicit notion of
1970 "selected process" in the protocol. The selected process for
1971 general operations is the process the selected general thread
1972 belongs to. */
1973
1974static void
1975set_general_process (void)
1976{
1977 struct remote_state *rs = get_remote_state ();
1978
1979 /* If the remote can't handle multiple processes, don't bother. */
ef5ccd6c 1980 if (!rs->extended || !remote_multi_process_p (rs))
5796c8dc
SS
1981 return;
1982
1983 /* We only need to change the remote current thread if it's pointing
1984 at some other process. */
25e4902b 1985 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
5796c8dc
SS
1986 set_general_thread (inferior_ptid);
1987}
1988
1989\f
25e4902b
AHJ
1990/* Return nonzero if this is the main thread that we made up ourselves
1991 to model non-threaded targets as single-threaded. */
5796c8dc
SS
1992
1993static int
25e4902b 1994remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
5796c8dc
SS
1995{
1996 struct remote_state *rs = get_remote_state ();
1997 char *p, *endp;
1998
1999 if (ptid_equal (ptid, magic_null_ptid))
2000 /* The main thread is always alive. */
2001 return 1;
2002
25e4902b 2003 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
5796c8dc
SS
2004 /* The main thread is always alive. This can happen after a
2005 vAttach, if the remote side doesn't support
2006 multi-threading. */
2007 return 1;
2008
25e4902b
AHJ
2009 return 0;
2010}
2011
2012/* Return nonzero if the thread PTID is still alive on the remote
2013 system. */
2014
2015static int
2016remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2017{
2018 struct remote_state *rs = get_remote_state ();
2019 char *p, *endp;
2020
2021 /* Check if this is a thread that we made up ourselves to model
2022 non-threaded targets as single-threaded. */
2023 if (remote_thread_always_alive (ops, ptid))
2024 return 1;
2025
5796c8dc
SS
2026 p = rs->buf;
2027 endp = rs->buf + get_remote_packet_size ();
2028
2029 *p++ = 'T';
2030 write_ptid (p, endp, ptid);
2031
2032 putpkt (rs->buf);
2033 getpkt (&rs->buf, &rs->buf_size, 0);
2034 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2035}
2036
2037/* About these extended threadlist and threadinfo packets. They are
2038 variable length packets but, the fields within them are often fixed
2039 length. They are redundent enough to send over UDP as is the
2040 remote protocol in general. There is a matching unit test module
2041 in libstub. */
2042
5796c8dc 2043/* WARNING: This threadref data structure comes from the remote O.S.,
c50c785c 2044 libstub protocol encoding, and remote.c. It is not particularly
5796c8dc
SS
2045 changable. */
2046
2047/* Right now, the internal structure is int. We want it to be bigger.
c50c785c 2048 Plan to fix this. */
5796c8dc
SS
2049
2050typedef int gdb_threadref; /* Internal GDB thread reference. */
2051
2052/* gdb_ext_thread_info is an internal GDB data structure which is
2053 equivalent to the reply of the remote threadinfo packet. */
2054
2055struct gdb_ext_thread_info
2056 {
2057 threadref threadid; /* External form of thread reference. */
2058 int active; /* Has state interesting to GDB?
2059 regs, stack. */
2060 char display[256]; /* Brief state display, name,
2061 blocked/suspended. */
2062 char shortname[32]; /* To be used to name threads. */
2063 char more_display[256]; /* Long info, statistics, queue depth,
2064 whatever. */
2065 };
2066
2067/* The volume of remote transfers can be limited by submitting
2068 a mask containing bits specifying the desired information.
2069 Use a union of these values as the 'selection' parameter to
c50c785c 2070 get_thread_info. FIXME: Make these TAG names more thread specific. */
5796c8dc
SS
2071
2072#define TAG_THREADID 1
2073#define TAG_EXISTS 2
2074#define TAG_DISPLAY 4
2075#define TAG_THREADNAME 8
2076#define TAG_MOREDISPLAY 16
2077
2078#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2079
5796c8dc
SS
2080static char *unpack_nibble (char *buf, int *val);
2081
5796c8dc
SS
2082static char *unpack_byte (char *buf, int *value);
2083
2084static char *pack_int (char *buf, int value);
2085
2086static char *unpack_int (char *buf, int *value);
2087
2088static char *unpack_string (char *src, char *dest, int length);
2089
2090static char *pack_threadid (char *pkt, threadref *id);
2091
2092static char *unpack_threadid (char *inbuf, threadref *id);
2093
2094void int_to_threadref (threadref *id, int value);
2095
2096static int threadref_to_int (threadref *ref);
2097
2098static void copy_threadref (threadref *dest, threadref *src);
2099
2100static int threadmatch (threadref *dest, threadref *src);
2101
2102static char *pack_threadinfo_request (char *pkt, int mode,
2103 threadref *id);
2104
2105static int remote_unpack_thread_info_response (char *pkt,
2106 threadref *expectedref,
2107 struct gdb_ext_thread_info
2108 *info);
2109
2110
2111static int remote_get_threadinfo (threadref *threadid,
2112 int fieldset, /*TAG mask */
2113 struct gdb_ext_thread_info *info);
2114
2115static char *pack_threadlist_request (char *pkt, int startflag,
2116 int threadcount,
2117 threadref *nextthread);
2118
2119static int parse_threadlist_response (char *pkt,
2120 int result_limit,
2121 threadref *original_echo,
2122 threadref *resultlist,
2123 int *doneflag);
2124
2125static int remote_get_threadlist (int startflag,
2126 threadref *nextthread,
2127 int result_limit,
2128 int *done,
2129 int *result_count,
2130 threadref *threadlist);
2131
2132typedef int (*rmt_thread_action) (threadref *ref, void *context);
2133
2134static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2135 void *context, int looplimit);
2136
2137static int remote_newthread_step (threadref *ref, void *context);
2138
2139
2140/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2141 buffer we're allowed to write to. Returns
2142 BUF+CHARACTERS_WRITTEN. */
2143
2144static char *
2145write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2146{
2147 int pid, tid;
2148 struct remote_state *rs = get_remote_state ();
2149
2150 if (remote_multi_process_p (rs))
2151 {
2152 pid = ptid_get_pid (ptid);
2153 if (pid < 0)
2154 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2155 else
2156 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2157 }
25e4902b 2158 tid = ptid_get_lwp (ptid);
5796c8dc
SS
2159 if (tid < 0)
2160 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2161 else
2162 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2163
2164 return buf;
2165}
2166
2167/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2168 passed the last parsed char. Returns null_ptid on error. */
2169
2170static ptid_t
2171read_ptid (char *buf, char **obuf)
2172{
2173 char *p = buf;
2174 char *pp;
2175 ULONGEST pid = 0, tid = 0;
2176
2177 if (*p == 'p')
2178 {
2179 /* Multi-process ptid. */
2180 pp = unpack_varlen_hex (p + 1, &pid);
2181 if (*pp != '.')
c50c785c 2182 error (_("invalid remote ptid: %s"), p);
5796c8dc
SS
2183
2184 p = pp;
2185 pp = unpack_varlen_hex (p + 1, &tid);
2186 if (obuf)
2187 *obuf = pp;
25e4902b 2188 return ptid_build (pid, tid, 0);
5796c8dc
SS
2189 }
2190
2191 /* No multi-process. Just a tid. */
2192 pp = unpack_varlen_hex (p, &tid);
2193
2194 /* Since the stub is not sending a process id, then default to
2195 what's in inferior_ptid, unless it's null at this point. If so,
2196 then since there's no way to know the pid of the reported
2197 threads, use the magic number. */
2198 if (ptid_equal (inferior_ptid, null_ptid))
2199 pid = ptid_get_pid (magic_null_ptid);
2200 else
2201 pid = ptid_get_pid (inferior_ptid);
2202
2203 if (obuf)
2204 *obuf = pp;
25e4902b 2205 return ptid_build (pid, tid, 0);
5796c8dc
SS
2206}
2207
2208static int
2209stubhex (int ch)
2210{
2211 if (ch >= 'a' && ch <= 'f')
2212 return ch - 'a' + 10;
2213 if (ch >= '0' && ch <= '9')
2214 return ch - '0';
2215 if (ch >= 'A' && ch <= 'F')
2216 return ch - 'A' + 10;
2217 return -1;
2218}
2219
2220static int
2221stub_unpack_int (char *buff, int fieldlength)
2222{
2223 int nibble;
2224 int retval = 0;
2225
2226 while (fieldlength)
2227 {
2228 nibble = stubhex (*buff++);
2229 retval |= nibble;
2230 fieldlength--;
2231 if (fieldlength)
2232 retval = retval << 4;
2233 }
2234 return retval;
2235}
2236
5796c8dc
SS
2237static char *
2238unpack_nibble (char *buf, int *val)
2239{
2240 *val = fromhex (*buf++);
2241 return buf;
2242}
2243
5796c8dc
SS
2244static char *
2245unpack_byte (char *buf, int *value)
2246{
2247 *value = stub_unpack_int (buf, 2);
2248 return buf + 2;
2249}
2250
2251static char *
2252pack_int (char *buf, int value)
2253{
2254 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2255 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2256 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2257 buf = pack_hex_byte (buf, (value & 0xff));
2258 return buf;
2259}
2260
2261static char *
2262unpack_int (char *buf, int *value)
2263{
2264 *value = stub_unpack_int (buf, 8);
2265 return buf + 8;
2266}
2267
2268#if 0 /* Currently unused, uncomment when needed. */
2269static char *pack_string (char *pkt, char *string);
2270
2271static char *
2272pack_string (char *pkt, char *string)
2273{
2274 char ch;
2275 int len;
2276
2277 len = strlen (string);
2278 if (len > 200)
2279 len = 200; /* Bigger than most GDB packets, junk??? */
2280 pkt = pack_hex_byte (pkt, len);
2281 while (len-- > 0)
2282 {
2283 ch = *string++;
2284 if ((ch == '\0') || (ch == '#'))
2285 ch = '*'; /* Protect encapsulation. */
2286 *pkt++ = ch;
2287 }
2288 return pkt;
2289}
2290#endif /* 0 (unused) */
2291
2292static char *
2293unpack_string (char *src, char *dest, int length)
2294{
2295 while (length--)
2296 *dest++ = *src++;
2297 *dest = '\0';
2298 return src;
2299}
2300
2301static char *
2302pack_threadid (char *pkt, threadref *id)
2303{
2304 char *limit;
2305 unsigned char *altid;
2306
2307 altid = (unsigned char *) id;
2308 limit = pkt + BUF_THREAD_ID_SIZE;
2309 while (pkt < limit)
2310 pkt = pack_hex_byte (pkt, *altid++);
2311 return pkt;
2312}
2313
2314
2315static char *
2316unpack_threadid (char *inbuf, threadref *id)
2317{
2318 char *altref;
2319 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2320 int x, y;
2321
2322 altref = (char *) id;
2323
2324 while (inbuf < limit)
2325 {
2326 x = stubhex (*inbuf++);
2327 y = stubhex (*inbuf++);
2328 *altref++ = (x << 4) | y;
2329 }
2330 return inbuf;
2331}
2332
2333/* Externally, threadrefs are 64 bits but internally, they are still
c50c785c 2334 ints. This is due to a mismatch of specifications. We would like
5796c8dc
SS
2335 to use 64bit thread references internally. This is an adapter
2336 function. */
2337
2338void
2339int_to_threadref (threadref *id, int value)
2340{
2341 unsigned char *scan;
2342
2343 scan = (unsigned char *) id;
2344 {
2345 int i = 4;
2346 while (i--)
2347 *scan++ = 0;
2348 }
2349 *scan++ = (value >> 24) & 0xff;
2350 *scan++ = (value >> 16) & 0xff;
2351 *scan++ = (value >> 8) & 0xff;
2352 *scan++ = (value & 0xff);
2353}
2354
2355static int
2356threadref_to_int (threadref *ref)
2357{
2358 int i, value = 0;
2359 unsigned char *scan;
2360
2361 scan = *ref;
2362 scan += 4;
2363 i = 4;
2364 while (i-- > 0)
2365 value = (value << 8) | ((*scan++) & 0xff);
2366 return value;
2367}
2368
2369static void
2370copy_threadref (threadref *dest, threadref *src)
2371{
2372 int i;
2373 unsigned char *csrc, *cdest;
2374
2375 csrc = (unsigned char *) src;
2376 cdest = (unsigned char *) dest;
2377 i = 8;
2378 while (i--)
2379 *cdest++ = *csrc++;
2380}
2381
2382static int
2383threadmatch (threadref *dest, threadref *src)
2384{
2385 /* Things are broken right now, so just assume we got a match. */
2386#if 0
2387 unsigned char *srcp, *destp;
2388 int i, result;
2389 srcp = (char *) src;
2390 destp = (char *) dest;
2391
2392 result = 1;
2393 while (i-- > 0)
2394 result &= (*srcp++ == *destp++) ? 1 : 0;
2395 return result;
2396#endif
2397 return 1;
2398}
2399
2400/*
2401 threadid:1, # always request threadid
2402 context_exists:2,
2403 display:4,
2404 unique_name:8,
2405 more_display:16
2406 */
2407
2408/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2409
2410static char *
2411pack_threadinfo_request (char *pkt, int mode, threadref *id)
2412{
2413 *pkt++ = 'q'; /* Info Query */
2414 *pkt++ = 'P'; /* process or thread info */
2415 pkt = pack_int (pkt, mode); /* mode */
2416 pkt = pack_threadid (pkt, id); /* threadid */
2417 *pkt = '\0'; /* terminate */
2418 return pkt;
2419}
2420
2421/* These values tag the fields in a thread info response packet. */
2422/* Tagging the fields allows us to request specific fields and to
2423 add more fields as time goes by. */
2424
2425#define TAG_THREADID 1 /* Echo the thread identifier. */
2426#define TAG_EXISTS 2 /* Is this process defined enough to
2427 fetch registers and its stack? */
2428#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2429#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2430#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2431 the process. */
2432
2433static int
2434remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2435 struct gdb_ext_thread_info *info)
2436{
2437 struct remote_state *rs = get_remote_state ();
2438 int mask, length;
2439 int tag;
2440 threadref ref;
2441 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2442 int retval = 1;
2443
2444 /* info->threadid = 0; FIXME: implement zero_threadref. */
2445 info->active = 0;
2446 info->display[0] = '\0';
2447 info->shortname[0] = '\0';
2448 info->more_display[0] = '\0';
2449
2450 /* Assume the characters indicating the packet type have been
2451 stripped. */
2452 pkt = unpack_int (pkt, &mask); /* arg mask */
2453 pkt = unpack_threadid (pkt, &ref);
2454
2455 if (mask == 0)
2456 warning (_("Incomplete response to threadinfo request."));
2457 if (!threadmatch (&ref, expectedref))
2458 { /* This is an answer to a different request. */
2459 warning (_("ERROR RMT Thread info mismatch."));
2460 return 0;
2461 }
2462 copy_threadref (&info->threadid, &ref);
2463
2464 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2465
2466 /* Packets are terminated with nulls. */
2467 while ((pkt < limit) && mask && *pkt)
2468 {
2469 pkt = unpack_int (pkt, &tag); /* tag */
2470 pkt = unpack_byte (pkt, &length); /* length */
2471 if (!(tag & mask)) /* Tags out of synch with mask. */
2472 {
2473 warning (_("ERROR RMT: threadinfo tag mismatch."));
2474 retval = 0;
2475 break;
2476 }
2477 if (tag == TAG_THREADID)
2478 {
2479 if (length != 16)
2480 {
2481 warning (_("ERROR RMT: length of threadid is not 16."));
2482 retval = 0;
2483 break;
2484 }
2485 pkt = unpack_threadid (pkt, &ref);
2486 mask = mask & ~TAG_THREADID;
2487 continue;
2488 }
2489 if (tag == TAG_EXISTS)
2490 {
2491 info->active = stub_unpack_int (pkt, length);
2492 pkt += length;
2493 mask = mask & ~(TAG_EXISTS);
2494 if (length > 8)
2495 {
2496 warning (_("ERROR RMT: 'exists' length too long."));
2497 retval = 0;
2498 break;
2499 }
2500 continue;
2501 }
2502 if (tag == TAG_THREADNAME)
2503 {
2504 pkt = unpack_string (pkt, &info->shortname[0], length);
2505 mask = mask & ~TAG_THREADNAME;
2506 continue;
2507 }
2508 if (tag == TAG_DISPLAY)
2509 {
2510 pkt = unpack_string (pkt, &info->display[0], length);
2511 mask = mask & ~TAG_DISPLAY;
2512 continue;
2513 }
2514 if (tag == TAG_MOREDISPLAY)
2515 {
2516 pkt = unpack_string (pkt, &info->more_display[0], length);
2517 mask = mask & ~TAG_MOREDISPLAY;
2518 continue;
2519 }
2520 warning (_("ERROR RMT: unknown thread info tag."));
2521 break; /* Not a tag we know about. */
2522 }
2523 return retval;
2524}
2525
2526static int
2527remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2528 struct gdb_ext_thread_info *info)
2529{
2530 struct remote_state *rs = get_remote_state ();
2531 int result;
2532
2533 pack_threadinfo_request (rs->buf, fieldset, threadid);
2534 putpkt (rs->buf);
2535 getpkt (&rs->buf, &rs->buf_size, 0);
2536
2537 if (rs->buf[0] == '\0')
2538 return 0;
2539
2540 result = remote_unpack_thread_info_response (rs->buf + 2,
2541 threadid, info);
2542 return result;
2543}
2544
2545/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2546
2547static char *
2548pack_threadlist_request (char *pkt, int startflag, int threadcount,
2549 threadref *nextthread)
2550{
2551 *pkt++ = 'q'; /* info query packet */
2552 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2553 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2554 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2555 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2556 *pkt = '\0';
2557 return pkt;
2558}
2559
2560/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2561
2562static int
2563parse_threadlist_response (char *pkt, int result_limit,
2564 threadref *original_echo, threadref *resultlist,
2565 int *doneflag)
2566{
2567 struct remote_state *rs = get_remote_state ();
2568 char *limit;
2569 int count, resultcount, done;
2570
2571 resultcount = 0;
2572 /* Assume the 'q' and 'M chars have been stripped. */
2573 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2574 /* done parse past here */
2575 pkt = unpack_byte (pkt, &count); /* count field */
2576 pkt = unpack_nibble (pkt, &done);
2577 /* The first threadid is the argument threadid. */
2578 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2579 while ((count-- > 0) && (pkt < limit))
2580 {
2581 pkt = unpack_threadid (pkt, resultlist++);
2582 if (resultcount++ >= result_limit)
2583 break;
2584 }
2585 if (doneflag)
2586 *doneflag = done;
2587 return resultcount;
2588}
2589
25e4902b
AHJ
2590/* Fetch the next batch of threads from the remote. Returns -1 if the
2591 qL packet is not supported, 0 on error and 1 on success. */
2592
5796c8dc
SS
2593static int
2594remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2595 int *done, int *result_count, threadref *threadlist)
2596{
2597 struct remote_state *rs = get_remote_state ();
5796c8dc
SS
2598 int result = 1;
2599
2600 /* Trancate result limit to be smaller than the packet size. */
c50c785c
JM
2601 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2602 >= get_remote_packet_size ())
5796c8dc
SS
2603 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2604
2605 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2606 putpkt (rs->buf);
2607 getpkt (&rs->buf, &rs->buf_size, 0);
5796c8dc 2608 if (*rs->buf == '\0')
25e4902b
AHJ
2609 {
2610 /* Packet not supported. */
2611 return -1;
2612 }
5796c8dc 2613
25e4902b
AHJ
2614 *result_count =
2615 parse_threadlist_response (rs->buf + 2, result_limit,
2616 &rs->echo_nextthread, threadlist, done);
2617
2618 if (!threadmatch (&rs->echo_nextthread, nextthread))
5796c8dc
SS
2619 {
2620 /* FIXME: This is a good reason to drop the packet. */
2621 /* Possably, there is a duplicate response. */
2622 /* Possabilities :
2623 retransmit immediatly - race conditions
2624 retransmit after timeout - yes
2625 exit
2626 wait for packet, then exit
2627 */
2628 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2629 return 0; /* I choose simply exiting. */
2630 }
2631 if (*result_count <= 0)
2632 {
2633 if (*done != 1)
2634 {
2635 warning (_("RMT ERROR : failed to get remote thread list."));
2636 result = 0;
2637 }
2638 return result; /* break; */
2639 }
2640 if (*result_count > result_limit)
2641 {
2642 *result_count = 0;
2643 warning (_("RMT ERROR: threadlist response longer than requested."));
2644 return 0;
2645 }
2646 return result;
2647}
2648
25e4902b
AHJ
2649/* Fetch the list of remote threads, with the qL packet, and call
2650 STEPFUNCTION for each thread found. Stops iterating and returns 1
2651 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2652 STEPFUNCTION returns false. If the packet is not supported,
2653 returns -1. */
5796c8dc
SS
2654
2655static int
2656remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2657 int looplimit)
2658{
25e4902b 2659 struct remote_state *rs = get_remote_state ();
5796c8dc
SS
2660 int done, i, result_count;
2661 int startflag = 1;
2662 int result = 1;
2663 int loopcount = 0;
5796c8dc
SS
2664
2665 done = 0;
2666 while (!done)
2667 {
2668 if (loopcount++ > looplimit)
2669 {
2670 result = 0;
2671 warning (_("Remote fetch threadlist -infinite loop-."));
2672 break;
2673 }
25e4902b
AHJ
2674 result = remote_get_threadlist (startflag, &rs->nextthread,
2675 MAXTHREADLISTRESULTS,
2676 &done, &result_count,
2677 rs->resultthreadlist);
2678 if (result <= 0)
2679 break;
5796c8dc
SS
2680 /* Clear for later iterations. */
2681 startflag = 0;
2682 /* Setup to resume next batch of thread references, set nextthread. */
2683 if (result_count >= 1)
25e4902b
AHJ
2684 copy_threadref (&rs->nextthread,
2685 &rs->resultthreadlist[result_count - 1]);
5796c8dc
SS
2686 i = 0;
2687 while (result_count--)
25e4902b
AHJ
2688 {
2689 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2690 {
2691 result = 0;
2692 break;
2693 }
2694 }
5796c8dc
SS
2695 }
2696 return result;
2697}
2698
25e4902b
AHJ
2699/* A thread found on the remote target. */
2700
2701typedef struct thread_item
2702{
2703 /* The thread's PTID. */
2704 ptid_t ptid;
2705
2706 /* The thread's extra info. May be NULL. */
2707 char *extra;
2708
2709 /* The core the thread was running on. -1 if not known. */
2710 int core;
2711} thread_item_t;
2712DEF_VEC_O(thread_item_t);
2713
2714/* Context passed around to the various methods listing remote
2715 threads. As new threads are found, they're added to the ITEMS
2716 vector. */
2717
2718struct threads_listing_context
2719{
2720 /* The threads found on the remote target. */
2721 VEC (thread_item_t) *items;
2722};
2723
2724/* Discard the contents of the constructed thread listing context. */
2725
2726static void
2727clear_threads_listing_context (void *p)
2728{
2729 struct threads_listing_context *context = p;
2730 int i;
2731 struct thread_item *item;
2732
2733 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2734 xfree (item->extra);
2735
2736 VEC_free (thread_item_t, context->items);
2737}
2738
2739/* Remove the thread specified as the related_pid field of WS
2740 from the CONTEXT list. */
2741
2742static void
2743threads_listing_context_remove (struct target_waitstatus *ws,
2744 struct threads_listing_context *context)
2745{
2746 struct thread_item *item;
2747 int i;
2748 ptid_t child_ptid = ws->value.related_pid;
2749
2750 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2751 {
2752 if (ptid_equal (item->ptid, child_ptid))
2753 {
2754 VEC_ordered_remove (thread_item_t, context->items, i);
2755 break;
2756 }
2757 }
2758}
2759
5796c8dc 2760static int
25e4902b 2761remote_newthread_step (threadref *ref, void *data)
5796c8dc 2762{
25e4902b
AHJ
2763 struct threads_listing_context *context = data;
2764 struct thread_item item;
5796c8dc 2765 int pid = ptid_get_pid (inferior_ptid);
5796c8dc 2766
25e4902b
AHJ
2767 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2768 item.core = -1;
2769 item.extra = NULL;
2770
2771 VEC_safe_push (thread_item_t, context->items, &item);
2772
5796c8dc
SS
2773 return 1; /* continue iterator */
2774}
2775
2776#define CRAZY_MAX_THREADS 1000
2777
2778static ptid_t
2779remote_current_thread (ptid_t oldpid)
2780{
2781 struct remote_state *rs = get_remote_state ();
2782
2783 putpkt ("qC");
2784 getpkt (&rs->buf, &rs->buf_size, 0);
2785 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2786 return read_ptid (&rs->buf[2], NULL);
2787 else
2788 return oldpid;
2789}
2790
25e4902b 2791/* List remote threads using the deprecated qL packet. */
5796c8dc 2792
25e4902b
AHJ
2793static int
2794remote_get_threads_with_ql (struct target_ops *ops,
2795 struct threads_listing_context *context)
5796c8dc 2796{
25e4902b
AHJ
2797 if (remote_threadlist_iterator (remote_newthread_step, context,
2798 CRAZY_MAX_THREADS) >= 0)
2799 return 1;
2800
2801 return 0;
5796c8dc
SS
2802}
2803
cf7f2e2d
JM
2804#if defined(HAVE_LIBEXPAT)
2805
cf7f2e2d
JM
2806static void
2807start_thread (struct gdb_xml_parser *parser,
2808 const struct gdb_xml_element *element,
2809 void *user_data, VEC(gdb_xml_value_s) *attributes)
2810{
25e4902b 2811 struct threads_listing_context *data = user_data;
cf7f2e2d
JM
2812
2813 struct thread_item item;
2814 char *id;
c50c785c 2815 struct gdb_xml_value *attr;
cf7f2e2d 2816
c50c785c 2817 id = xml_find_attribute (attributes, "id")->value;
cf7f2e2d
JM
2818 item.ptid = read_ptid (id, NULL);
2819
c50c785c
JM
2820 attr = xml_find_attribute (attributes, "core");
2821 if (attr != NULL)
2822 item.core = *(ULONGEST *) attr->value;
cf7f2e2d
JM
2823 else
2824 item.core = -1;
2825
2826 item.extra = 0;
2827
2828 VEC_safe_push (thread_item_t, data->items, &item);
2829}
2830
2831static void
2832end_thread (struct gdb_xml_parser *parser,
2833 const struct gdb_xml_element *element,
2834 void *user_data, const char *body_text)
2835{
25e4902b 2836 struct threads_listing_context *data = user_data;
cf7f2e2d
JM
2837
2838 if (body_text && *body_text)
2839 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2840}
2841
2842const struct gdb_xml_attribute thread_attributes[] = {
2843 { "id", GDB_XML_AF_NONE, NULL, NULL },
2844 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2845 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2846};
2847
2848const struct gdb_xml_element thread_children[] = {
2849 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2850};
2851
2852const struct gdb_xml_element threads_children[] = {
2853 { "thread", thread_attributes, thread_children,
2854 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2855 start_thread, end_thread },
2856 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2857};
2858
2859const struct gdb_xml_element threads_elements[] = {
2860 { "threads", NULL, threads_children,
2861 GDB_XML_EF_NONE, NULL, NULL },
2862 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2863};
2864
cf7f2e2d
JM
2865#endif
2866
25e4902b 2867/* List remote threads using qXfer:threads:read. */
5796c8dc 2868
25e4902b
AHJ
2869static int
2870remote_get_threads_with_qxfer (struct target_ops *ops,
2871 struct threads_listing_context *context)
5796c8dc 2872{
cf7f2e2d 2873#if defined(HAVE_LIBEXPAT)
25e4902b 2874 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
cf7f2e2d 2875 {
25e4902b 2876 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
cf7f2e2d 2877 struct cleanup *back_to = make_cleanup (xfree, xml);
c50c785c 2878
25e4902b 2879 if (xml != NULL && *xml != '\0')
cf7f2e2d 2880 {
25e4902b
AHJ
2881 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2882 threads_elements, xml, context);
cf7f2e2d
JM
2883 }
2884
2885 do_cleanups (back_to);
25e4902b 2886 return 1;
cf7f2e2d
JM
2887 }
2888#endif
2889
25e4902b
AHJ
2890 return 0;
2891}
2892
2893/* List remote threads using qfThreadInfo/qsThreadInfo. */
2894
2895static int
2896remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2897 struct threads_listing_context *context)
2898{
2899 struct remote_state *rs = get_remote_state ();
2900
2901 if (rs->use_threadinfo_query)
5796c8dc 2902 {
25e4902b
AHJ
2903 char *bufp;
2904
5796c8dc
SS
2905 putpkt ("qfThreadInfo");
2906 getpkt (&rs->buf, &rs->buf_size, 0);
2907 bufp = rs->buf;
2908 if (bufp[0] != '\0') /* q packet recognized */
2909 {
2910 while (*bufp++ == 'm') /* reply contains one or more TID */
2911 {
2912 do
2913 {
25e4902b 2914 struct thread_item item;
5796c8dc 2915
25e4902b
AHJ
2916 item.ptid = read_ptid (bufp, &bufp);
2917 item.core = -1;
2918 item.extra = NULL;
2919
2920 VEC_safe_push (thread_item_t, context->items, &item);
5796c8dc
SS
2921 }
2922 while (*bufp++ == ','); /* comma-separated list */
2923 putpkt ("qsThreadInfo");
2924 getpkt (&rs->buf, &rs->buf_size, 0);
25e4902b 2925 bufp = rs->buf;
5796c8dc 2926 }
25e4902b
AHJ
2927 return 1;
2928 }
2929 else
2930 {
2931 /* Packet not recognized. */
2932 rs->use_threadinfo_query = 0;
2933 }
2934 }
2935
2936 return 0;
2937}
2938
2939/* Implement the to_update_thread_list function for the remote
2940 targets. */
2941
2942static void
2943remote_update_thread_list (struct target_ops *ops)
2944{
2945 struct remote_state *rs = get_remote_state ();
2946 struct threads_listing_context context;
2947 struct cleanup *old_chain;
2948 int got_list = 0;
2949
2950 context.items = NULL;
2951 old_chain = make_cleanup (clear_threads_listing_context, &context);
2952
2953 /* We have a few different mechanisms to fetch the thread list. Try
2954 them all, starting with the most preferred one first, falling
2955 back to older methods. */
2956 if (remote_get_threads_with_qxfer (ops, &context)
2957 || remote_get_threads_with_qthreadinfo (ops, &context)
2958 || remote_get_threads_with_ql (ops, &context))
2959 {
2960 int i;
2961 struct thread_item *item;
2962 struct thread_info *tp, *tmp;
2963
2964 got_list = 1;
2965
2966 if (VEC_empty (thread_item_t, context.items)
2967 && remote_thread_always_alive (ops, inferior_ptid))
2968 {
2969 /* Some targets don't really support threads, but still
2970 reply an (empty) thread list in response to the thread
2971 listing packets, instead of replying "packet not
2972 supported". Exit early so we don't delete the main
2973 thread. */
ef5ccd6c 2974 do_cleanups (old_chain);
25e4902b
AHJ
2975 return;
2976 }
2977
2978 /* CONTEXT now holds the current thread list on the remote
2979 target end. Delete GDB-side threads no longer found on the
2980 target. */
2981 ALL_THREADS_SAFE (tp, tmp)
2982 {
2983 for (i = 0;
2984 VEC_iterate (thread_item_t, context.items, i, item);
2985 ++i)
2986 {
2987 if (ptid_equal (item->ptid, tp->ptid))
2988 break;
2989 }
2990
2991 if (i == VEC_length (thread_item_t, context.items))
2992 {
2993 /* Not found. */
2994 delete_thread (tp->ptid);
2995 }
2996 }
2997
2998 /* Remove any unreported fork child threads from CONTEXT so
2999 that we don't interfere with follow fork, which is where
3000 creation of such threads is handled. */
3001 remove_new_fork_children (&context);
3002
3003 /* And now add threads we don't know about yet to our list. */
3004 for (i = 0;
3005 VEC_iterate (thread_item_t, context.items, i, item);
3006 ++i)
3007 {
3008 if (!ptid_equal (item->ptid, null_ptid))
3009 {
3010 struct private_thread_info *info;
3011 /* In non-stop mode, we assume new found threads are
3012 running until proven otherwise with a stop reply. In
3013 all-stop, we can only get here if all threads are
3014 stopped. */
3015 int running = non_stop ? 1 : 0;
3016
3017 remote_notice_new_inferior (item->ptid, running);
3018
3019 info = demand_private_info (item->ptid);
3020 info->core = item->core;
3021 info->extra = item->extra;
3022 item->extra = NULL;
3023 }
5796c8dc
SS
3024 }
3025 }
3026
25e4902b
AHJ
3027 if (!got_list)
3028 {
3029 /* If no thread listing method is supported, then query whether
3030 each known thread is alive, one by one, with the T packet.
3031 If the target doesn't support threads at all, then this is a
3032 no-op. See remote_thread_alive. */
3033 prune_threads ();
3034 }
5796c8dc 3035
25e4902b 3036 do_cleanups (old_chain);
5796c8dc
SS
3037}
3038
3039/*
3040 * Collect a descriptive string about the given thread.
3041 * The target may say anything it wants to about the thread
3042 * (typically info about its blocked / runnable state, name, etc.).
3043 * This string will appear in the info threads display.
3044 *
3045 * Optional: targets are not required to implement this function.
3046 */
3047
3048static char *
25e4902b 3049remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
5796c8dc
SS
3050{
3051 struct remote_state *rs = get_remote_state ();
3052 int result;
3053 int set;
3054 threadref id;
3055 struct gdb_ext_thread_info threadinfo;
3056 static char display_buf[100]; /* arbitrary... */
3057 int n = 0; /* position in display_buf */
3058
25e4902b 3059 if (rs->remote_desc == 0) /* paranoia */
5796c8dc
SS
3060 internal_error (__FILE__, __LINE__,
3061 _("remote_threads_extra_info"));
3062
3063 if (ptid_equal (tp->ptid, magic_null_ptid)
25e4902b 3064 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
5796c8dc
SS
3065 /* This is the main thread which was added by GDB. The remote
3066 server doesn't know about it. */
3067 return NULL;
3068
25e4902b 3069 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
cf7f2e2d
JM
3070 {
3071 struct thread_info *info = find_thread_ptid (tp->ptid);
3072
25e4902b
AHJ
3073 if (info && info->priv)
3074 return info->priv->extra;
cf7f2e2d
JM
3075 else
3076 return NULL;
3077 }
3078
25e4902b 3079 if (rs->use_threadextra_query)
5796c8dc
SS
3080 {
3081 char *b = rs->buf;
3082 char *endb = rs->buf + get_remote_packet_size ();
3083
3084 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3085 b += strlen (b);
3086 write_ptid (b, endb, tp->ptid);
3087
3088 putpkt (rs->buf);
3089 getpkt (&rs->buf, &rs->buf_size, 0);
3090 if (rs->buf[0] != 0)
3091 {
3092 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3093 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3094 display_buf [result] = '\0';
3095 return display_buf;
3096 }
3097 }
3098
3099 /* If the above query fails, fall back to the old method. */
25e4902b 3100 rs->use_threadextra_query = 0;
5796c8dc
SS
3101 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3102 | TAG_MOREDISPLAY | TAG_DISPLAY;
25e4902b 3103 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
5796c8dc
SS
3104 if (remote_get_threadinfo (&id, set, &threadinfo))
3105 if (threadinfo.active)
3106 {
3107 if (*threadinfo.shortname)
3108 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3109 " Name: %s,", threadinfo.shortname);
3110 if (*threadinfo.display)
3111 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3112 " State: %s,", threadinfo.display);
3113 if (*threadinfo.more_display)
3114 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3115 " Priority: %s", threadinfo.more_display);
3116
3117 if (n > 0)
3118 {
3119 /* For purely cosmetic reasons, clear up trailing commas. */
3120 if (',' == display_buf[n-1])
3121 display_buf[n-1] = ' ';
3122 return display_buf;
3123 }
3124 }
3125 return NULL;
3126}
3127\f
3128
cf7f2e2d 3129static int
25e4902b 3130remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
cf7f2e2d
JM
3131 struct static_tracepoint_marker *marker)
3132{
3133 struct remote_state *rs = get_remote_state ();
3134 char *p = rs->buf;
3135
ef5ccd6c 3136 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
cf7f2e2d
JM
3137 p += strlen (p);
3138 p += hexnumstr (p, addr);
3139 putpkt (rs->buf);
3140 getpkt (&rs->buf, &rs->buf_size, 0);
3141 p = rs->buf;
3142
3143 if (*p == 'E')
3144 error (_("Remote failure reply: %s"), p);
3145
3146 if (*p++ == 'm')
3147 {
3148 parse_static_tracepoint_marker_definition (p, &p, marker);
3149 return 1;
3150 }
3151
3152 return 0;
3153}
3154
cf7f2e2d 3155static VEC(static_tracepoint_marker_p) *
25e4902b
AHJ
3156remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3157 const char *strid)
cf7f2e2d
JM
3158{
3159 struct remote_state *rs = get_remote_state ();
3160 VEC(static_tracepoint_marker_p) *markers = NULL;
3161 struct static_tracepoint_marker *marker = NULL;
3162 struct cleanup *old_chain;
3163 char *p;
3164
3165 /* Ask for a first packet of static tracepoint marker
3166 definition. */
3167 putpkt ("qTfSTM");
3168 getpkt (&rs->buf, &rs->buf_size, 0);
3169 p = rs->buf;
3170 if (*p == 'E')
3171 error (_("Remote failure reply: %s"), p);
3172
3173 old_chain = make_cleanup (free_current_marker, &marker);
3174
3175 while (*p++ == 'm')
3176 {
3177 if (marker == NULL)
3178 marker = XCNEW (struct static_tracepoint_marker);
3179
3180 do
3181 {
3182 parse_static_tracepoint_marker_definition (p, &p, marker);
3183
3184 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3185 {
3186 VEC_safe_push (static_tracepoint_marker_p,
3187 markers, marker);
3188 marker = NULL;
3189 }
3190 else
3191 {
3192 release_static_tracepoint_marker (marker);
3193 memset (marker, 0, sizeof (*marker));
3194 }
3195 }
3196 while (*p++ == ','); /* comma-separated list */
3197 /* Ask for another packet of static tracepoint definition. */
3198 putpkt ("qTsSTM");
3199 getpkt (&rs->buf, &rs->buf_size, 0);
3200 p = rs->buf;
3201 }
3202
3203 do_cleanups (old_chain);
3204 return markers;
3205}
3206
3207\f
3208/* Implement the to_get_ada_task_ptid function for the remote targets. */
3209
3210static ptid_t
25e4902b 3211remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
cf7f2e2d 3212{
25e4902b 3213 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
cf7f2e2d
JM
3214}
3215\f
3216
5796c8dc
SS
3217/* Restart the remote side; this is an extended protocol operation. */
3218
3219static void
3220extended_remote_restart (void)
3221{
3222 struct remote_state *rs = get_remote_state ();
3223
3224 /* Send the restart command; for reasons I don't understand the
3225 remote side really expects a number after the "R". */
3226 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3227 putpkt (rs->buf);
3228
3229 remote_fileio_reset ();
3230}
3231\f
3232/* Clean up connection to a remote debugger. */
3233
3234static void
25e4902b 3235remote_close (struct target_ops *self)
5796c8dc 3236{
25e4902b
AHJ
3237 struct remote_state *rs = get_remote_state ();
3238
3239 if (rs->remote_desc == NULL)
5796c8dc
SS
3240 return; /* already closed */
3241
3242 /* Make sure we leave stdin registered in the event loop, and we
3243 don't leave the async SIGINT signal handler installed. */
25e4902b 3244 remote_terminal_ours (self);
5796c8dc 3245
25e4902b
AHJ
3246 serial_close (rs->remote_desc);
3247 rs->remote_desc = NULL;
5796c8dc
SS
3248
3249 /* We don't have a connection to the remote stub anymore. Get rid
c50c785c
JM
3250 of all the inferiors and their threads we were controlling.
3251 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3252 will be unable to find the thread corresponding to (pid, 0, 0). */
cf7f2e2d 3253 inferior_ptid = null_ptid;
c50c785c 3254 discard_all_inferiors ();
5796c8dc 3255
25e4902b
AHJ
3256 /* We are closing the remote target, so we should discard
3257 everything of this target. */
3258 discard_pending_stop_replies_in_queue (rs);
5796c8dc
SS
3259
3260 if (remote_async_inferior_event_token)
3261 delete_async_event_handler (&remote_async_inferior_event_token);
ef5ccd6c 3262
25e4902b
AHJ
3263 remote_notif_state_xfree (rs->notif_state);
3264
3265 trace_reset_local_state ();
5796c8dc
SS
3266}
3267
3268/* Query the remote side for the text, data and bss offsets. */
3269
3270static void
3271get_offsets (void)
3272{
3273 struct remote_state *rs = get_remote_state ();
3274 char *buf;
3275 char *ptr;
3276 int lose, num_segments = 0, do_sections, do_segments;
3277 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3278 struct section_offsets *offs;
3279 struct symfile_segment_data *data;
3280
3281 if (symfile_objfile == NULL)
3282 return;
3283
3284 putpkt ("qOffsets");
3285 getpkt (&rs->buf, &rs->buf_size, 0);
3286 buf = rs->buf;
3287
3288 if (buf[0] == '\000')
3289 return; /* Return silently. Stub doesn't support
3290 this command. */
3291 if (buf[0] == 'E')
3292 {
3293 warning (_("Remote failure reply: %s"), buf);
3294 return;
3295 }
3296
3297 /* Pick up each field in turn. This used to be done with scanf, but
3298 scanf will make trouble if CORE_ADDR size doesn't match
3299 conversion directives correctly. The following code will work
3300 with any size of CORE_ADDR. */
3301 text_addr = data_addr = bss_addr = 0;
3302 ptr = buf;
3303 lose = 0;
3304
25e4902b 3305 if (startswith (ptr, "Text="))
5796c8dc
SS
3306 {
3307 ptr += 5;
3308 /* Don't use strtol, could lose on big values. */
3309 while (*ptr && *ptr != ';')
3310 text_addr = (text_addr << 4) + fromhex (*ptr++);
3311
25e4902b 3312 if (startswith (ptr, ";Data="))
5796c8dc
SS
3313 {
3314 ptr += 6;
3315 while (*ptr && *ptr != ';')
3316 data_addr = (data_addr << 4) + fromhex (*ptr++);
3317 }
3318 else
3319 lose = 1;
3320
25e4902b 3321 if (!lose && startswith (ptr, ";Bss="))
5796c8dc
SS
3322 {
3323 ptr += 5;
3324 while (*ptr && *ptr != ';')
3325 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3326
3327 if (bss_addr != data_addr)
3328 warning (_("Target reported unsupported offsets: %s"), buf);
3329 }
3330 else
3331 lose = 1;
3332 }
25e4902b 3333 else if (startswith (ptr, "TextSeg="))
5796c8dc
SS
3334 {
3335 ptr += 8;
3336 /* Don't use strtol, could lose on big values. */
3337 while (*ptr && *ptr != ';')
3338 text_addr = (text_addr << 4) + fromhex (*ptr++);
3339 num_segments = 1;
3340
25e4902b 3341 if (startswith (ptr, ";DataSeg="))
5796c8dc
SS
3342 {
3343 ptr += 9;
3344 while (*ptr && *ptr != ';')
3345 data_addr = (data_addr << 4) + fromhex (*ptr++);
3346 num_segments++;
3347 }
3348 }
3349 else
3350 lose = 1;
3351
3352 if (lose)
3353 error (_("Malformed response to offset query, %s"), buf);
3354 else if (*ptr != '\0')
3355 warning (_("Target reported unsupported offsets: %s"), buf);
3356
3357 offs = ((struct section_offsets *)
3358 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3359 memcpy (offs, symfile_objfile->section_offsets,
3360 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3361
3362 data = get_symfile_segment_data (symfile_objfile->obfd);
3363 do_segments = (data != NULL);
3364 do_sections = num_segments == 0;
3365
3366 if (num_segments > 0)
3367 {
3368 segments[0] = text_addr;
3369 segments[1] = data_addr;
3370 }
3371 /* If we have two segments, we can still try to relocate everything
3372 by assuming that the .text and .data offsets apply to the whole
3373 text and data segments. Convert the offsets given in the packet
3374 to base addresses for symfile_map_offsets_to_segments. */
3375 else if (data && data->num_segments == 2)
3376 {
3377 segments[0] = data->segment_bases[0] + text_addr;
3378 segments[1] = data->segment_bases[1] + data_addr;
3379 num_segments = 2;
3380 }
3381 /* If the object file has only one segment, assume that it is text
3382 rather than data; main programs with no writable data are rare,
3383 but programs with no code are useless. Of course the code might
3384 have ended up in the data segment... to detect that we would need
3385 the permissions here. */
3386 else if (data && data->num_segments == 1)
3387 {
3388 segments[0] = data->segment_bases[0] + text_addr;
3389 num_segments = 1;
3390 }
3391 /* There's no way to relocate by segment. */
3392 else
3393 do_segments = 0;
3394
3395 if (do_segments)
3396 {
3397 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3398 offs, num_segments, segments);
3399
3400 if (ret == 0 && !do_sections)
c50c785c
JM
3401 error (_("Can not handle qOffsets TextSeg "
3402 "response with this symbol file"));
5796c8dc
SS
3403
3404 if (ret > 0)
3405 do_sections = 0;
3406 }
3407
3408 if (data)
3409 free_symfile_segment_data (data);
3410
3411 if (do_sections)
3412 {
3413 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3414
c50c785c
JM
3415 /* This is a temporary kludge to force data and bss to use the
3416 same offsets because that's what nlmconv does now. The real
3417 solution requires changes to the stub and remote.c that I
3418 don't have time to do right now. */
5796c8dc
SS
3419
3420 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3421 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3422 }
3423
3424 objfile_relocate (symfile_objfile, offs);
3425}
3426
3427/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3428 threads we know are stopped already. This is used during the
3429 initial remote connection in non-stop mode --- threads that are
3430 reported as already being stopped are left stopped. */
3431
3432static int
3433set_stop_requested_callback (struct thread_info *thread, void *data)
3434{
3435 /* If we have a stop reply for this thread, it must be stopped. */
3436 if (peek_stop_reply (thread->ptid))
3437 set_stop_requested (thread->ptid, 1);
3438
3439 return 0;
3440}
3441
cf7f2e2d
JM
3442/* Send interrupt_sequence to remote target. */
3443static void
c50c785c 3444send_interrupt_sequence (void)
cf7f2e2d 3445{
25e4902b
AHJ
3446 struct remote_state *rs = get_remote_state ();
3447
cf7f2e2d 3448 if (interrupt_sequence_mode == interrupt_sequence_control_c)
ef5ccd6c 3449 remote_serial_write ("\x03", 1);
cf7f2e2d 3450 else if (interrupt_sequence_mode == interrupt_sequence_break)
25e4902b 3451 serial_send_break (rs->remote_desc);
cf7f2e2d
JM
3452 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3453 {
25e4902b 3454 serial_send_break (rs->remote_desc);
ef5ccd6c 3455 remote_serial_write ("g", 1);
cf7f2e2d
JM
3456 }
3457 else
3458 internal_error (__FILE__, __LINE__,
3459 _("Invalid value for interrupt_sequence_mode: %s."),
3460 interrupt_sequence_mode);
3461}
3462
ef5ccd6c
JM
3463
3464/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3465 and extract the PTID. Returns NULL_PTID if not found. */
3466
3467static ptid_t
3468stop_reply_extract_thread (char *stop_reply)
3469{
3470 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3471 {
3472 char *p;
3473
3474 /* Txx r:val ; r:val (...) */
3475 p = &stop_reply[3];
3476
3477 /* Look for "register" named "thread". */
3478 while (*p != '\0')
3479 {
3480 char *p1;
3481
3482 p1 = strchr (p, ':');
3483 if (p1 == NULL)
3484 return null_ptid;
3485
3486 if (strncmp (p, "thread", p1 - p) == 0)
3487 return read_ptid (++p1, &p);
3488
3489 p1 = strchr (p, ';');
3490 if (p1 == NULL)
3491 return null_ptid;
3492 p1++;
3493
3494 p = p1;
3495 }
3496 }
3497
3498 return null_ptid;
3499}
3500
25e4902b
AHJ
3501/* Determine the remote side's current thread. If we have a stop
3502 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3503 "thread" register we can extract the current thread from. If not,
3504 ask the remote which is the current thread with qC. The former
3505 method avoids a roundtrip. */
3506
3507static ptid_t
3508get_current_thread (char *wait_status)
3509{
3510 ptid_t ptid;
3511
3512 /* Note we don't use remote_parse_stop_reply as that makes use of
3513 the target architecture, which we haven't yet fully determined at
3514 this point. */
3515 if (wait_status != NULL)
3516 ptid = stop_reply_extract_thread (wait_status);
3517 if (ptid_equal (ptid, null_ptid))
3518 ptid = remote_current_thread (inferior_ptid);
3519
3520 return ptid;
3521}
3522
ef5ccd6c
JM
3523/* Query the remote target for which is the current thread/process,
3524 add it to our tables, and update INFERIOR_PTID. The caller is
3525 responsible for setting the state such that the remote end is ready
3526 to return the current thread.
3527
3528 This function is called after handling the '?' or 'vRun' packets,
3529 whose response is a stop reply from which we can also try
3530 extracting the thread. If the target doesn't support the explicit
3531 qC query, we infer the current thread from that stop reply, passed
3532 in in WAIT_STATUS, which may be NULL. */
3533
3534static void
3535add_current_inferior_and_thread (char *wait_status)
3536{
3537 struct remote_state *rs = get_remote_state ();
3538 int fake_pid_p = 0;
3539 ptid_t ptid = null_ptid;
3540
3541 inferior_ptid = null_ptid;
3542
25e4902b
AHJ
3543 /* Now, if we have thread information, update inferior_ptid. */
3544 ptid = get_current_thread (wait_status);
ef5ccd6c
JM
3545
3546 if (!ptid_equal (ptid, null_ptid))
3547 {
3548 if (!remote_multi_process_p (rs))
3549 fake_pid_p = 1;
3550
3551 inferior_ptid = ptid;
3552 }
3553 else
3554 {
3555 /* Without this, some commands which require an active target
3556 (such as kill) won't work. This variable serves (at least)
3557 double duty as both the pid of the target process (if it has
3558 such), and as a flag indicating that a target is active. */
3559 inferior_ptid = magic_null_ptid;
3560 fake_pid_p = 1;
3561 }
3562
25e4902b 3563 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
ef5ccd6c
JM
3564
3565 /* Add the main thread. */
3566 add_thread_silent (inferior_ptid);
3567}
3568
5796c8dc 3569static void
a45ae5f8 3570remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
5796c8dc 3571{
5796c8dc
SS
3572 struct remote_state *rs = get_remote_state ();
3573 struct packet_config *noack_config;
3574 char *wait_status = NULL;
3575
3576 immediate_quit++; /* Allow user to interrupt it. */
ef5ccd6c 3577 QUIT;
5796c8dc 3578
cf7f2e2d
JM
3579 if (interrupt_on_connect)
3580 send_interrupt_sequence ();
3581
c50c785c 3582 /* Ack any packet which the remote side has already sent. */
25e4902b 3583 serial_write (rs->remote_desc, "+", 1);
c50c785c 3584
a45ae5f8
JM
3585 /* Signal other parts that we're going through the initial setup,
3586 and so things may not be stable yet. */
3587 rs->starting_up = 1;
3588
5796c8dc
SS
3589 /* The first packet we send to the target is the optional "supported
3590 packets" request. If the target can answer this, it will tell us
3591 which later probes to skip. */
3592 remote_query_supported ();
3593
cf7f2e2d 3594 /* If the stub wants to get a QAllow, compose one and send it. */
25e4902b
AHJ
3595 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3596 remote_set_permissions (target);
cf7f2e2d 3597
5796c8dc
SS
3598 /* Next, we possibly activate noack mode.
3599
3600 If the QStartNoAckMode packet configuration is set to AUTO,
3601 enable noack mode if the stub reported a wish for it with
3602 qSupported.
3603
3604 If set to TRUE, then enable noack mode even if the stub didn't
3605 report it in qSupported. If the stub doesn't reply OK, the
3606 session ends with an error.
3607
3608 If FALSE, then don't activate noack mode, regardless of what the
3609 stub claimed should be the default with qSupported. */
3610
3611 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
25e4902b 3612 if (packet_config_support (noack_config) != PACKET_DISABLE)
5796c8dc
SS
3613 {
3614 putpkt ("QStartNoAckMode");
3615 getpkt (&rs->buf, &rs->buf_size, 0);
3616 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3617 rs->noack_mode = 1;
3618 }
3619
a45ae5f8 3620 if (extended_p)
5796c8dc
SS
3621 {
3622 /* Tell the remote that we are using the extended protocol. */
3623 putpkt ("!");
3624 getpkt (&rs->buf, &rs->buf_size, 0);
3625 }
3626
ef5ccd6c
JM
3627 /* Let the target know which signals it is allowed to pass down to
3628 the program. */
3629 update_signals_program_target ();
3630
5796c8dc
SS
3631 /* Next, if the target can specify a description, read it. We do
3632 this before anything involving memory or registers. */
3633 target_find_description ();
3634
cf7f2e2d
JM
3635 /* Next, now that we know something about the target, update the
3636 address spaces in the program spaces. */
3637 update_address_spaces ();
3638
5796c8dc
SS
3639 /* On OSs where the list of libraries is global to all
3640 processes, we fetch them early. */
ef5ccd6c 3641 if (gdbarch_has_global_solist (target_gdbarch ()))
a45ae5f8 3642 solib_add (NULL, from_tty, target, auto_solib_add);
5796c8dc
SS
3643
3644 if (non_stop)
3645 {
25e4902b 3646 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
c50c785c
JM
3647 error (_("Non-stop mode requested, but remote "
3648 "does not support non-stop"));
5796c8dc
SS
3649
3650 putpkt ("QNonStop:1");
3651 getpkt (&rs->buf, &rs->buf_size, 0);
3652
3653 if (strcmp (rs->buf, "OK") != 0)
c50c785c 3654 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
5796c8dc
SS
3655
3656 /* Find about threads and processes the stub is already
3657 controlling. We default to adding them in the running state.
3658 The '?' query below will then tell us about which threads are
3659 stopped. */
25e4902b 3660 remote_update_thread_list (target);
5796c8dc 3661 }
25e4902b 3662 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5796c8dc
SS
3663 {
3664 /* Don't assume that the stub can operate in all-stop mode.
ef5ccd6c 3665 Request it explicitly. */
5796c8dc
SS
3666 putpkt ("QNonStop:0");
3667 getpkt (&rs->buf, &rs->buf_size, 0);
3668
3669 if (strcmp (rs->buf, "OK") != 0)
c50c785c 3670 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
5796c8dc
SS
3671 }
3672
25e4902b
AHJ
3673 /* Upload TSVs regardless of whether the target is running or not. The
3674 remote stub, such as GDBserver, may have some predefined or builtin
3675 TSVs, even if the target is not running. */
3676 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3677 {
3678 struct uploaded_tsv *uploaded_tsvs = NULL;
3679
3680 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3681 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3682 }
3683
5796c8dc
SS
3684 /* Check whether the target is running now. */
3685 putpkt ("?");
3686 getpkt (&rs->buf, &rs->buf_size, 0);
3687
3688 if (!non_stop)
3689 {
ef5ccd6c
JM
3690 ptid_t ptid;
3691 int fake_pid_p = 0;
3692 struct inferior *inf;
3693
5796c8dc
SS
3694 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3695 {
a45ae5f8 3696 if (!extended_p)
5796c8dc
SS
3697 error (_("The target is not running (try extended-remote?)"));
3698
3699 /* We're connected, but not running. Drop out before we
3700 call start_remote. */
a45ae5f8 3701 rs->starting_up = 0;
5796c8dc
SS
3702 return;
3703 }
3704 else
3705 {
3706 /* Save the reply for later. */
3707 wait_status = alloca (strlen (rs->buf) + 1);
3708 strcpy (wait_status, rs->buf);
3709 }
3710
25e4902b
AHJ
3711 /* Fetch thread list. */
3712 target_update_thread_list ();
3713
5796c8dc
SS
3714 /* Let the stub know that we want it to return the thread. */
3715 set_continue_thread (minus_one_ptid);
3716
25e4902b
AHJ
3717 if (thread_count () == 0)
3718 {
3719 /* Target has no concept of threads at all. GDB treats
3720 non-threaded target as single-threaded; add a main
3721 thread. */
3722 add_current_inferior_and_thread (wait_status);
3723 }
3724 else
3725 {
3726 /* We have thread information; select the thread the target
3727 says should be current. If we're reconnecting to a
3728 multi-threaded program, this will ideally be the thread
3729 that last reported an event before GDB disconnected. */
3730 inferior_ptid = get_current_thread (wait_status);
3731 if (ptid_equal (inferior_ptid, null_ptid))
3732 {
3733 /* Odd... The target was able to list threads, but not
3734 tell us which thread was current (no "thread"
3735 register in T stop reply?). Just pick the first
3736 thread in the thread list then. */
3737 inferior_ptid = thread_list->ptid;
3738 }
3739 }
5796c8dc 3740
a45ae5f8
JM
3741 /* init_wait_for_inferior should be called before get_offsets in order
3742 to manage `inserted' flag in bp loc in a correct state.
3743 breakpoint_init_inferior, called from init_wait_for_inferior, set
3744 `inserted' flag to 0, while before breakpoint_re_set, called from
3745 start_remote, set `inserted' flag to 1. In the initialization of
3746 inferior, breakpoint_init_inferior should be called first, and then
3747 breakpoint_re_set can be called. If this order is broken, state of
3748 `inserted' flag is wrong, and cause some problems on breakpoint
3749 manipulation. */
3750 init_wait_for_inferior ();
3751
5796c8dc
SS
3752 get_offsets (); /* Get text, data & bss offsets. */
3753
3754 /* If we could not find a description using qXfer, and we know
3755 how to do it some other way, try again. This is not
3756 supported for non-stop; it could be, but it is tricky if
3757 there are no stopped threads when we connect. */
a45ae5f8 3758 if (remote_read_description_p (target)
ef5ccd6c 3759 && gdbarch_target_desc (target_gdbarch ()) == NULL)
5796c8dc
SS
3760 {
3761 target_clear_description ();
3762 target_find_description ();
3763 }
3764
3765 /* Use the previously fetched status. */
3766 gdb_assert (wait_status != NULL);
3767 strcpy (rs->buf, wait_status);
3768 rs->cached_wait_status = 1;
3769
3770 immediate_quit--;
a45ae5f8 3771 start_remote (from_tty); /* Initialize gdb process mechanisms. */
5796c8dc
SS
3772 }
3773 else
3774 {
3775 /* Clear WFI global state. Do this before finding about new
3776 threads and inferiors, and setting the current inferior.
3777 Otherwise we would clear the proceed status of the current
3778 inferior when we want its stop_soon state to be preserved
3779 (see notice_new_inferior). */
3780 init_wait_for_inferior ();
3781
3782 /* In non-stop, we will either get an "OK", meaning that there
3783 are no stopped threads at this time; or, a regular stop
3784 reply. In the latter case, there may be more than one thread
3785 stopped --- we pull them all out using the vStopped
3786 mechanism. */
3787 if (strcmp (rs->buf, "OK") != 0)
3788 {
ef5ccd6c 3789 struct notif_client *notif = &notif_client_stop;
5796c8dc 3790
ef5ccd6c
JM
3791 /* remote_notif_get_pending_replies acks this one, and gets
3792 the rest out. */
25e4902b 3793 rs->notif_state->pending_event[notif_client_stop.id]
ef5ccd6c
JM
3794 = remote_notif_parse (notif, rs->buf);
3795 remote_notif_get_pending_events (notif);
5796c8dc
SS
3796
3797 /* Make sure that threads that were stopped remain
3798 stopped. */
3799 iterate_over_threads (set_stop_requested_callback, NULL);
3800 }
3801
3802 if (target_can_async_p ())
25e4902b 3803 target_async (1);
5796c8dc
SS
3804
3805 if (thread_count () == 0)
3806 {
a45ae5f8 3807 if (!extended_p)
5796c8dc
SS
3808 error (_("The target is not running (try extended-remote?)"));
3809
3810 /* We're connected, but not running. Drop out before we
3811 call start_remote. */
a45ae5f8 3812 rs->starting_up = 0;
5796c8dc
SS
3813 return;
3814 }
3815
3816 /* Let the stub know that we want it to return the thread. */
3817
3818 /* Force the stub to choose a thread. */
3819 set_general_thread (null_ptid);
3820
3821 /* Query it. */
3822 inferior_ptid = remote_current_thread (minus_one_ptid);
3823 if (ptid_equal (inferior_ptid, minus_one_ptid))
3824 error (_("remote didn't report the current thread in non-stop mode"));
3825
3826 get_offsets (); /* Get text, data & bss offsets. */
3827
3828 /* In non-stop mode, any cached wait status will be stored in
3829 the stop reply queue. */
3830 gdb_assert (wait_status == NULL);
cf7f2e2d 3831
a45ae5f8 3832 /* Report all signals during attach/startup. */
25e4902b 3833 remote_pass_signals (target, 0, NULL);
5796c8dc
SS
3834 }
3835
3836 /* If we connected to a live target, do some additional setup. */
3837 if (target_has_execution)
3838 {
25e4902b
AHJ
3839 if (symfile_objfile) /* No use without a symbol-file. */
3840 remote_check_symbols ();
5796c8dc
SS
3841 }
3842
cf7f2e2d
JM
3843 /* Possibly the target has been engaged in a trace run started
3844 previously; find out where things are at. */
25e4902b 3845 if (remote_get_trace_status (target, current_trace_status ()) != -1)
cf7f2e2d
JM
3846 {
3847 struct uploaded_tp *uploaded_tps = NULL;
5796c8dc 3848
cf7f2e2d
JM
3849 if (current_trace_status ()->running)
3850 printf_filtered (_("Trace is already running on the target.\n"));
3851
25e4902b 3852 remote_upload_tracepoints (target, &uploaded_tps);
cf7f2e2d
JM
3853
3854 merge_uploaded_tracepoints (&uploaded_tps);
3855 }
3856
a45ae5f8
JM
3857 /* The thread and inferior lists are now synchronized with the
3858 target, our symbols have been relocated, and we're merged the
3859 target's tracepoints with ours. We're done with basic start
3860 up. */
3861 rs->starting_up = 0;
3862
25e4902b
AHJ
3863 /* Maybe breakpoints are global and need to be inserted now. */
3864 if (breakpoints_should_be_inserted_now ())
cf7f2e2d
JM
3865 insert_breakpoints ();
3866}
3867
3868/* Open a connection to a remote debugger.
5796c8dc
SS
3869 NAME is the filename used for communication. */
3870
3871static void
25e4902b 3872remote_open (const char *name, int from_tty)
5796c8dc
SS
3873{
3874 remote_open_1 (name, from_tty, &remote_ops, 0);
3875}
3876
3877/* Open a connection to a remote debugger using the extended
3878 remote gdb protocol. NAME is the filename used for communication. */
3879
3880static void
25e4902b 3881extended_remote_open (const char *name, int from_tty)
5796c8dc
SS
3882{
3883 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3884}
3885
25e4902b
AHJ
3886/* Reset all packets back to "unknown support". Called when opening a
3887 new connection to a remote target. */
5796c8dc
SS
3888
3889static void
25e4902b 3890reset_all_packet_configs_support (void)
5796c8dc
SS
3891{
3892 int i;
cf7f2e2d 3893
5796c8dc 3894 for (i = 0; i < PACKET_MAX; i++)
25e4902b 3895 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5796c8dc
SS
3896}
3897
25e4902b 3898/* Initialize all packet configs. */
5796c8dc
SS
3899
3900static void
25e4902b
AHJ
3901init_all_packet_configs (void)
3902{
3903 int i;
3904
3905 for (i = 0; i < PACKET_MAX; i++)
3906 {
3907 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3908 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3909 }
3910}
3911
3912/* Symbol look-up. */
3913
3914static void
3915remote_check_symbols (void)
5796c8dc
SS
3916{
3917 struct remote_state *rs = get_remote_state ();
3918 char *msg, *reply, *tmp;
25e4902b 3919 struct bound_minimal_symbol sym;
5796c8dc
SS
3920 int end;
3921
c50c785c
JM
3922 /* The remote side has no concept of inferiors that aren't running
3923 yet, it only knows about running processes. If we're connected
3924 but our current inferior is not running, we should not invite the
3925 remote target to request symbol lookups related to its
3926 (unrelated) current process. */
3927 if (!target_has_execution)
3928 return;
3929
25e4902b 3930 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5796c8dc
SS
3931 return;
3932
c50c785c
JM
3933 /* Make sure the remote is pointing at the right process. Note
3934 there's no way to select "no process". */
5796c8dc
SS
3935 set_general_process ();
3936
3937 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3938 because we need both at the same time. */
3939 msg = alloca (get_remote_packet_size ());
3940
3941 /* Invite target to request symbol lookups. */
3942
3943 putpkt ("qSymbol::");
3944 getpkt (&rs->buf, &rs->buf_size, 0);
3945 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3946 reply = rs->buf;
3947
25e4902b 3948 while (startswith (reply, "qSymbol:"))
5796c8dc 3949 {
25e4902b
AHJ
3950 struct bound_minimal_symbol sym;
3951
5796c8dc
SS
3952 tmp = &reply[8];
3953 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3954 msg[end] = '\0';
3955 sym = lookup_minimal_symbol (msg, NULL, NULL);
25e4902b 3956 if (sym.minsym == NULL)
5796c8dc
SS
3957 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3958 else
3959 {
ef5ccd6c 3960 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
25e4902b 3961 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
5796c8dc
SS
3962
3963 /* If this is a function address, return the start of code
3964 instead of any data function descriptor. */
ef5ccd6c 3965 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
5796c8dc
SS
3966 sym_addr,
3967 &current_target);
3968
3969 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3970 phex_nz (sym_addr, addr_size), &reply[8]);
3971 }
3972
3973 putpkt (msg);
3974 getpkt (&rs->buf, &rs->buf_size, 0);
3975 reply = rs->buf;
3976 }
3977}
3978
3979static struct serial *
25e4902b 3980remote_serial_open (const char *name)
5796c8dc
SS
3981{
3982 static int udp_warning = 0;
3983
3984 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3985 of in ser-tcp.c, because it is the remote protocol assuming that the
3986 serial connection is reliable and not the serial connection promising
3987 to be. */
25e4902b 3988 if (!udp_warning && startswith (name, "udp:"))
5796c8dc 3989 {
c50c785c
JM
3990 warning (_("The remote protocol may be unreliable over UDP.\n"
3991 "Some events may be lost, rendering further debugging "
3992 "impossible."));
5796c8dc
SS
3993 udp_warning = 1;
3994 }
3995
3996 return serial_open (name);
3997}
3998
cf7f2e2d
JM
3999/* Inform the target of our permission settings. The permission flags
4000 work without this, but if the target knows the settings, it can do
4001 a couple things. First, it can add its own check, to catch cases
4002 that somehow manage to get by the permissions checks in target
4003 methods. Second, if the target is wired to disallow particular
4004 settings (for instance, a system in the field that is not set up to
4005 be able to stop at a breakpoint), it can object to any unavailable
4006 permissions. */
4007
4008void
25e4902b 4009remote_set_permissions (struct target_ops *self)
cf7f2e2d
JM
4010{
4011 struct remote_state *rs = get_remote_state ();
4012
ef5ccd6c
JM
4013 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4014 "WriteReg:%x;WriteMem:%x;"
4015 "InsertBreak:%x;InsertTrace:%x;"
4016 "InsertFastTrace:%x;Stop:%x",
4017 may_write_registers, may_write_memory,
4018 may_insert_breakpoints, may_insert_tracepoints,
4019 may_insert_fast_tracepoints, may_stop);
cf7f2e2d
JM
4020 putpkt (rs->buf);
4021 getpkt (&rs->buf, &rs->buf_size, 0);
4022
4023 /* If the target didn't like the packet, warn the user. Do not try
4024 to undo the user's settings, that would just be maddening. */
4025 if (strcmp (rs->buf, "OK") != 0)
c50c785c 4026 warning (_("Remote refused setting permissions with: %s"), rs->buf);
cf7f2e2d
JM
4027}
4028
5796c8dc
SS
4029/* This type describes each known response to the qSupported
4030 packet. */
4031struct protocol_feature
4032{
4033 /* The name of this protocol feature. */
4034 const char *name;
4035
4036 /* The default for this protocol feature. */
4037 enum packet_support default_support;
4038
4039 /* The function to call when this feature is reported, or after
4040 qSupported processing if the feature is not supported.
4041 The first argument points to this structure. The second
4042 argument indicates whether the packet requested support be
4043 enabled, disabled, or probed (or the default, if this function
4044 is being called at the end of processing and this feature was
4045 not reported). The third argument may be NULL; if not NULL, it
4046 is a NUL-terminated string taken from the packet following
4047 this feature's name and an equals sign. */
4048 void (*func) (const struct protocol_feature *, enum packet_support,
4049 const char *);
4050
4051 /* The corresponding packet for this feature. Only used if
4052 FUNC is remote_supported_packet. */
4053 int packet;
4054};
4055
4056static void
4057remote_supported_packet (const struct protocol_feature *feature,
4058 enum packet_support support,
4059 const char *argument)
4060{
4061 if (argument)
4062 {
4063 warning (_("Remote qSupported response supplied an unexpected value for"
4064 " \"%s\"."), feature->name);
4065 return;
4066 }
4067
25e4902b 4068 remote_protocol_packets[feature->packet].support = support;
5796c8dc
SS
4069}
4070
4071static void
4072remote_packet_size (const struct protocol_feature *feature,
4073 enum packet_support support, const char *value)
4074{
4075 struct remote_state *rs = get_remote_state ();
4076
4077 int packet_size;
4078 char *value_end;
4079
4080 if (support != PACKET_ENABLE)
4081 return;
4082
4083 if (value == NULL || *value == '\0')
4084 {
4085 warning (_("Remote target reported \"%s\" without a size."),
4086 feature->name);
4087 return;
4088 }
4089
4090 errno = 0;
4091 packet_size = strtol (value, &value_end, 16);
4092 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4093 {
4094 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4095 feature->name, value);
4096 return;
4097 }
4098
4099 if (packet_size > MAX_REMOTE_PACKET_SIZE)
4100 {
4101 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
4102 packet_size, MAX_REMOTE_PACKET_SIZE);
4103 packet_size = MAX_REMOTE_PACKET_SIZE;
4104 }
4105
4106 /* Record the new maximum packet size. */
4107 rs->explicit_packet_size = packet_size;
4108}
4109
25e4902b 4110static const struct protocol_feature remote_protocol_features[] = {
5796c8dc
SS
4111 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4112 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4113 PACKET_qXfer_auxv },
25e4902b
AHJ
4114 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4115 PACKET_qXfer_exec_file },
5796c8dc
SS
4116 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4117 PACKET_qXfer_features },
4118 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4119 PACKET_qXfer_libraries },
a45ae5f8
JM
4120 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4121 PACKET_qXfer_libraries_svr4 },
25e4902b
AHJ
4122 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4123 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5796c8dc
SS
4124 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4125 PACKET_qXfer_memory_map },
4126 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4127 PACKET_qXfer_spu_read },
4128 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4129 PACKET_qXfer_spu_write },
4130 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4131 PACKET_qXfer_osdata },
cf7f2e2d
JM
4132 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4133 PACKET_qXfer_threads },
c50c785c
JM
4134 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4135 PACKET_qXfer_traceframe_info },
5796c8dc
SS
4136 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4137 PACKET_QPassSignals },
ef5ccd6c
JM
4138 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4139 PACKET_QProgramSignals },
5796c8dc
SS
4140 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4141 PACKET_QStartNoAckMode },
25e4902b
AHJ
4142 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4143 PACKET_multiprocess_feature },
4144 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5796c8dc
SS
4145 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4146 PACKET_qXfer_siginfo_read },
4147 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4148 PACKET_qXfer_siginfo_write },
25e4902b 4149 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5796c8dc 4150 PACKET_ConditionalTracepoints },
25e4902b 4151 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
ef5ccd6c 4152 PACKET_ConditionalBreakpoints },
25e4902b 4153 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
ef5ccd6c 4154 PACKET_BreakpointCommands },
25e4902b 4155 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
cf7f2e2d 4156 PACKET_FastTracepoints },
25e4902b 4157 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
cf7f2e2d 4158 PACKET_StaticTracepoints },
25e4902b 4159 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
a45ae5f8 4160 PACKET_InstallInTrace},
25e4902b
AHJ
4161 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4162 PACKET_DisconnectedTracing_feature },
5796c8dc
SS
4163 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4164 PACKET_bc },
4165 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4166 PACKET_bs },
cf7f2e2d
JM
4167 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4168 PACKET_TracepointSource },
4169 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4170 PACKET_QAllow },
25e4902b
AHJ
4171 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4172 PACKET_EnableDisableTracepoints_feature },
a45ae5f8
JM
4173 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4174 PACKET_qXfer_fdpic },
ef5ccd6c
JM
4175 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4176 PACKET_qXfer_uib },
a45ae5f8
JM
4177 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4178 PACKET_QDisableRandomization },
ef5ccd6c
JM
4179 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4180 { "QTBuffer:size", PACKET_DISABLE,
4181 remote_supported_packet, PACKET_QTBuffer_size},
25e4902b 4182 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
ef5ccd6c
JM
4183 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4184 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
25e4902b 4185 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
ef5ccd6c 4186 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
25e4902b
AHJ
4187 PACKET_qXfer_btrace },
4188 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4189 PACKET_qXfer_btrace_conf },
4190 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4191 PACKET_Qbtrace_conf_bts_size },
4192 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4193 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4194 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4195 PACKET_fork_event_feature },
4196 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4197 PACKET_vfork_event_feature },
4198 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4199 PACKET_Qbtrace_conf_pt_size }
5796c8dc
SS
4200};
4201
cf7f2e2d
JM
4202static char *remote_support_xml;
4203
4204/* Register string appended to "xmlRegisters=" in qSupported query. */
4205
4206void
4207register_remote_support_xml (const char *xml)
4208{
4209#if defined(HAVE_LIBEXPAT)
4210 if (remote_support_xml == NULL)
4211 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4212 else
4213 {
4214 char *copy = xstrdup (remote_support_xml + 13);
4215 char *p = strtok (copy, ",");
4216
4217 do
4218 {
4219 if (strcmp (p, xml) == 0)
4220 {
4221 /* already there */
4222 xfree (copy);
4223 return;
4224 }
4225 }
4226 while ((p = strtok (NULL, ",")) != NULL);
4227 xfree (copy);
4228
4229 remote_support_xml = reconcat (remote_support_xml,
4230 remote_support_xml, ",", xml,
4231 (char *) NULL);
4232 }
4233#endif
4234}
4235
4236static char *
4237remote_query_supported_append (char *msg, const char *append)
4238{
4239 if (msg)
4240 return reconcat (msg, msg, ";", append, (char *) NULL);
4241 else
4242 return xstrdup (append);
4243}
4244
5796c8dc
SS
4245static void
4246remote_query_supported (void)
4247{
4248 struct remote_state *rs = get_remote_state ();
4249 char *next;
4250 int i;
4251 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4252
4253 /* The packet support flags are handled differently for this packet
4254 than for most others. We treat an error, a disabled packet, and
4255 an empty response identically: any features which must be reported
4256 to be used will be automatically disabled. An empty buffer
4257 accomplishes this, since that is also the representation for a list
4258 containing no features. */
4259
4260 rs->buf[0] = 0;
25e4902b 4261 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5796c8dc 4262 {
cf7f2e2d
JM
4263 char *q = NULL;
4264 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4265
ef5ccd6c 4266 q = remote_query_supported_append (q, "multiprocess+");
cf7f2e2d 4267
25e4902b
AHJ
4268 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4269 q = remote_query_supported_append (q, "swbreak+");
4270 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4271 q = remote_query_supported_append (q, "hwbreak+");
4272
cf7f2e2d
JM
4273 if (remote_support_xml)
4274 q = remote_query_supported_append (q, remote_support_xml);
4275
4276 q = remote_query_supported_append (q, "qRelocInsn+");
4277
25e4902b
AHJ
4278 if (rs->extended)
4279 {
4280 if (packet_set_cmd_state (PACKET_fork_event_feature)
4281 != AUTO_BOOLEAN_FALSE)
4282 q = remote_query_supported_append (q, "fork-events+");
4283 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4284 != AUTO_BOOLEAN_FALSE)
4285 q = remote_query_supported_append (q, "vfork-events+");
4286 }
4287
cf7f2e2d
JM
4288 q = reconcat (q, "qSupported:", q, (char *) NULL);
4289 putpkt (q);
4290
4291 do_cleanups (old_chain);
5796c8dc
SS
4292
4293 getpkt (&rs->buf, &rs->buf_size, 0);
4294
4295 /* If an error occured, warn, but do not return - just reset the
4296 buffer to empty and go on to disable features. */
4297 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4298 == PACKET_ERROR)
4299 {
4300 warning (_("Remote failure reply: %s"), rs->buf);
4301 rs->buf[0] = 0;
4302 }
4303 }
4304
4305 memset (seen, 0, sizeof (seen));
4306
4307 next = rs->buf;
4308 while (*next)
4309 {
4310 enum packet_support is_supported;
4311 char *p, *end, *name_end, *value;
4312
4313 /* First separate out this item from the rest of the packet. If
4314 there's another item after this, we overwrite the separator
4315 (terminated strings are much easier to work with). */
4316 p = next;
4317 end = strchr (p, ';');
4318 if (end == NULL)
4319 {
4320 end = p + strlen (p);
4321 next = end;
4322 }
4323 else
4324 {
4325 *end = '\0';
4326 next = end + 1;
4327
4328 if (end == p)
4329 {
4330 warning (_("empty item in \"qSupported\" response"));
4331 continue;
4332 }
4333 }
4334
4335 name_end = strchr (p, '=');
4336 if (name_end)
4337 {
4338 /* This is a name=value entry. */
4339 is_supported = PACKET_ENABLE;
4340 value = name_end + 1;
4341 *name_end = '\0';
4342 }
4343 else
4344 {
4345 value = NULL;
4346 switch (end[-1])
4347 {
4348 case '+':
4349 is_supported = PACKET_ENABLE;
4350 break;
4351
4352 case '-':
4353 is_supported = PACKET_DISABLE;
4354 break;
4355
4356 case '?':
4357 is_supported = PACKET_SUPPORT_UNKNOWN;
4358 break;
4359
4360 default:
c50c785c
JM
4361 warning (_("unrecognized item \"%s\" "
4362 "in \"qSupported\" response"), p);
5796c8dc
SS
4363 continue;
4364 }
4365 end[-1] = '\0';
4366 }
4367
4368 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4369 if (strcmp (remote_protocol_features[i].name, p) == 0)
4370 {
4371 const struct protocol_feature *feature;
4372
4373 seen[i] = 1;
4374 feature = &remote_protocol_features[i];
4375 feature->func (feature, is_supported, value);
4376 break;
4377 }
4378 }
4379
4380 /* If we increased the packet size, make sure to increase the global
4381 buffer size also. We delay this until after parsing the entire
4382 qSupported packet, because this is the same buffer we were
4383 parsing. */
4384 if (rs->buf_size < rs->explicit_packet_size)
4385 {
4386 rs->buf_size = rs->explicit_packet_size;
4387 rs->buf = xrealloc (rs->buf, rs->buf_size);
4388 }
4389
4390 /* Handle the defaults for unmentioned features. */
4391 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4392 if (!seen[i])
4393 {
4394 const struct protocol_feature *feature;
4395
4396 feature = &remote_protocol_features[i];
4397 feature->func (feature, feature->default_support, NULL);
4398 }
4399}
4400
ef5ccd6c
JM
4401/* Remove any of the remote.c targets from target stack. Upper targets depend
4402 on it so remove them first. */
4403
4404static void
4405remote_unpush_target (void)
4406{
25e4902b 4407 pop_all_targets_above (process_stratum - 1);
ef5ccd6c 4408}
5796c8dc
SS
4409
4410static void
25e4902b 4411remote_open_1 (const char *name, int from_tty,
c50c785c 4412 struct target_ops *target, int extended_p)
5796c8dc
SS
4413{
4414 struct remote_state *rs = get_remote_state ();
4415
4416 if (name == 0)
4417 error (_("To open a remote debug connection, you need to specify what\n"
4418 "serial device is attached to the remote system\n"
4419 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4420
4421 /* See FIXME above. */
4422 if (!target_async_permitted)
4423 wait_forever_enabled_p = 1;
4424
4425 /* If we're connected to a running target, target_preopen will kill it.
ef5ccd6c
JM
4426 Ask this question first, before target_preopen has a chance to kill
4427 anything. */
25e4902b 4428 if (rs->remote_desc != NULL && !have_inferiors ())
5796c8dc 4429 {
ef5ccd6c
JM
4430 if (from_tty
4431 && !query (_("Already connected to a remote target. Disconnect? ")))
5796c8dc
SS
4432 error (_("Still connected."));
4433 }
4434
ef5ccd6c 4435 /* Here the possibly existing remote target gets unpushed. */
5796c8dc
SS
4436 target_preopen (from_tty);
4437
5796c8dc 4438 /* Make sure we send the passed signals list the next time we resume. */
25e4902b
AHJ
4439 xfree (rs->last_pass_packet);
4440 rs->last_pass_packet = NULL;
5796c8dc 4441
ef5ccd6c
JM
4442 /* Make sure we send the program signals list the next time we
4443 resume. */
25e4902b
AHJ
4444 xfree (rs->last_program_signals_packet);
4445 rs->last_program_signals_packet = NULL;
ef5ccd6c 4446
5796c8dc
SS
4447 remote_fileio_reset ();
4448 reopen_exec_file ();
4449 reread_symbols ();
4450
25e4902b
AHJ
4451 rs->remote_desc = remote_serial_open (name);
4452 if (!rs->remote_desc)
5796c8dc
SS
4453 perror_with_name (name);
4454
4455 if (baud_rate != -1)
4456 {
25e4902b 4457 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5796c8dc
SS
4458 {
4459 /* The requested speed could not be set. Error out to
4460 top level after closing remote_desc. Take care to
4461 set remote_desc to NULL to avoid closing remote_desc
4462 more than once. */
25e4902b
AHJ
4463 serial_close (rs->remote_desc);
4464 rs->remote_desc = NULL;
5796c8dc
SS
4465 perror_with_name (name);
4466 }
4467 }
4468
25e4902b
AHJ
4469 serial_setparity (rs->remote_desc, serial_parity);
4470 serial_raw (rs->remote_desc);
5796c8dc
SS
4471
4472 /* If there is something sitting in the buffer we might take it as a
4473 response to a command, which would be bad. */
25e4902b 4474 serial_flush_input (rs->remote_desc);
5796c8dc
SS
4475
4476 if (from_tty)
4477 {
4478 puts_filtered ("Remote debugging using ");
4479 puts_filtered (name);
4480 puts_filtered ("\n");
4481 }
4482 push_target (target); /* Switch to using remote target now. */
4483
4484 /* Register extra event sources in the event loop. */
4485 remote_async_inferior_event_token
4486 = create_async_event_handler (remote_async_inferior_event_handler,
4487 NULL);
25e4902b 4488 rs->notif_state = remote_notif_state_allocate ();
5796c8dc
SS
4489
4490 /* Reset the target state; these things will be queried either by
4491 remote_query_supported or as they are needed. */
25e4902b 4492 reset_all_packet_configs_support ();
5796c8dc
SS
4493 rs->cached_wait_status = 0;
4494 rs->explicit_packet_size = 0;
4495 rs->noack_mode = 0;
5796c8dc 4496 rs->extended = extended_p;
5796c8dc 4497 rs->waiting_for_stop_reply = 0;
cf7f2e2d 4498 rs->ctrlc_pending_p = 0;
5796c8dc 4499
25e4902b
AHJ
4500 rs->general_thread = not_sent_ptid;
4501 rs->continue_thread = not_sent_ptid;
4502 rs->remote_traceframe_number = -1;
5796c8dc
SS
4503
4504 /* Probe for ability to use "ThreadInfo" query, as required. */
25e4902b
AHJ
4505 rs->use_threadinfo_query = 1;
4506 rs->use_threadextra_query = 1;
4507
4508 readahead_cache_invalidate ();
5796c8dc
SS
4509
4510 if (target_async_permitted)
4511 {
4512 /* With this target we start out by owning the terminal. */
4513 remote_async_terminal_ours_p = 1;
4514
4515 /* FIXME: cagney/1999-09-23: During the initial connection it is
4516 assumed that the target is already ready and able to respond to
c50c785c 4517 requests. Unfortunately remote_start_remote() eventually calls
5796c8dc 4518 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
c50c785c 4519 around this. Eventually a mechanism that allows
5796c8dc
SS
4520 wait_for_inferior() to expect/get timeouts will be
4521 implemented. */
4522 wait_forever_enabled_p = 0;
4523 }
4524
4525 /* First delete any symbols previously loaded from shared libraries. */
4526 no_shared_libraries (NULL, 0);
4527
4528 /* Start afresh. */
4529 init_thread_list ();
4530
4531 /* Start the remote connection. If error() or QUIT, discard this
4532 target (we'd otherwise be in an inconsistent state) and then
4533 propogate the error on up the exception chain. This ensures that
4534 the caller doesn't stumble along blindly assuming that the
4535 function succeeded. The CLI doesn't have this problem but other
4536 UI's, such as MI do.
4537
4538 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4539 this function should return an error indication letting the
4540 caller restore the previous state. Unfortunately the command
4541 ``target remote'' is directly wired to this function making that
4542 impossible. On a positive note, the CLI side of this problem has
4543 been fixed - the function set_cmd_context() makes it possible for
4544 all the ``target ....'' commands to share a common callback
4545 function. See cli-dump.c. */
4546 {
5796c8dc 4547
25e4902b 4548 TRY
a45ae5f8
JM
4549 {
4550 remote_start_remote (from_tty, target, extended_p);
4551 }
25e4902b 4552 CATCH (ex, RETURN_MASK_ALL)
5796c8dc
SS
4553 {
4554 /* Pop the partially set up target - unless something else did
4555 already before throwing the exception. */
25e4902b 4556 if (rs->remote_desc != NULL)
ef5ccd6c 4557 remote_unpush_target ();
5796c8dc
SS
4558 if (target_async_permitted)
4559 wait_forever_enabled_p = 1;
4560 throw_exception (ex);
4561 }
25e4902b 4562 END_CATCH
5796c8dc
SS
4563 }
4564
25e4902b
AHJ
4565 remote_btrace_reset ();
4566
5796c8dc
SS
4567 if (target_async_permitted)
4568 wait_forever_enabled_p = 1;
4569}
4570
25e4902b
AHJ
4571/* Detach the specified process. */
4572
4573static void
4574remote_detach_pid (int pid)
4575{
4576 struct remote_state *rs = get_remote_state ();
4577
4578 if (remote_multi_process_p (rs))
4579 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4580 else
4581 strcpy (rs->buf, "D");
4582
4583 putpkt (rs->buf);
4584 getpkt (&rs->buf, &rs->buf_size, 0);
4585
4586 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4587 ;
4588 else if (rs->buf[0] == '\0')
4589 error (_("Remote doesn't know how to detach"));
4590 else
4591 error (_("Can't detach process."));
4592}
4593
4594/* This detaches a program to which we previously attached, using
4595 inferior_ptid to identify the process. After this is done, GDB
4596 can be used to debug some other program. We better not have left
4597 any breakpoints in the target program or it'll die when it hits
4598 one. */
5796c8dc
SS
4599
4600static void
25e4902b 4601remote_detach_1 (const char *args, int from_tty)
5796c8dc
SS
4602{
4603 int pid = ptid_get_pid (inferior_ptid);
4604 struct remote_state *rs = get_remote_state ();
25e4902b
AHJ
4605 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4606 int is_fork_parent;
5796c8dc
SS
4607
4608 if (args)
4609 error (_("Argument given to \"detach\" when remotely debugging."));
4610
4611 if (!target_has_execution)
4612 error (_("No process to detach from."));
4613
ef5ccd6c
JM
4614 if (from_tty)
4615 {
4616 char *exec_file = get_exec_file (0);
4617 if (exec_file == NULL)
4618 exec_file = "";
4619 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4620 target_pid_to_str (pid_to_ptid (pid)));
4621 gdb_flush (gdb_stdout);
4622 }
4623
5796c8dc 4624 /* Tell the remote target to detach. */
25e4902b 4625 remote_detach_pid (pid);
5796c8dc 4626
25e4902b 4627 if (from_tty && !rs->extended)
ef5ccd6c 4628 puts_filtered (_("Ending remote debugging.\n"));
5796c8dc 4629
25e4902b
AHJ
4630 /* Check to see if we are detaching a fork parent. Note that if we
4631 are detaching a fork child, tp == NULL. */
4632 is_fork_parent = (tp != NULL
4633 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4634
4635 /* If doing detach-on-fork, we don't mourn, because that will delete
4636 breakpoints that should be available for the followed inferior. */
4637 if (!is_fork_parent)
4638 target_mourn_inferior ();
4639 else
4640 {
4641 inferior_ptid = null_ptid;
4642 detach_inferior (pid);
4643 }
5796c8dc
SS
4644}
4645
4646static void
25e4902b 4647remote_detach (struct target_ops *ops, const char *args, int from_tty)
5796c8dc 4648{
25e4902b 4649 remote_detach_1 (args, from_tty);
5796c8dc
SS
4650}
4651
4652static void
25e4902b
AHJ
4653extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4654{
4655 remote_detach_1 (args, from_tty);
4656}
4657
4658/* Target follow-fork function for remote targets. On entry, and
4659 at return, the current inferior is the fork parent.
4660
4661 Note that although this is currently only used for extended-remote,
4662 it is named remote_follow_fork in anticipation of using it for the
4663 remote target as well. */
4664
4665static int
4666remote_follow_fork (struct target_ops *ops, int follow_child,
4667 int detach_fork)
5796c8dc 4668{
25e4902b
AHJ
4669 struct remote_state *rs = get_remote_state ();
4670 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
4671
4672 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4673 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
4674 {
4675 /* When following the parent and detaching the child, we detach
4676 the child here. For the case of following the child and
4677 detaching the parent, the detach is done in the target-
4678 independent follow fork code in infrun.c. We can't use
4679 target_detach when detaching an unfollowed child because
4680 the client side doesn't know anything about the child. */
4681 if (detach_fork && !follow_child)
4682 {
4683 /* Detach the fork child. */
4684 ptid_t child_ptid;
4685 pid_t child_pid;
4686
4687 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4688 child_pid = ptid_get_pid (child_ptid);
4689
4690 remote_detach_pid (child_pid);
4691 detach_inferior (child_pid);
4692 }
4693 }
4694 return 0;
5796c8dc
SS
4695}
4696
4697/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4698
4699static void
25e4902b 4700remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5796c8dc
SS
4701{
4702 if (args)
4703 error (_("Argument given to \"disconnect\" when remotely debugging."));
4704
4705 /* Make sure we unpush even the extended remote targets; mourn
25e4902b 4706 won't do it. So call remote_mourn directly instead of
5796c8dc 4707 target_mourn_inferior. */
25e4902b 4708 remote_mourn (target);
5796c8dc
SS
4709
4710 if (from_tty)
4711 puts_filtered ("Ending remote debugging.\n");
4712}
4713
4714/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4715 be chatty about it. */
4716
4717static void
25e4902b
AHJ
4718extended_remote_attach (struct target_ops *target, const char *args,
4719 int from_tty)
5796c8dc
SS
4720{
4721 struct remote_state *rs = get_remote_state ();
4722 int pid;
5796c8dc
SS
4723 char *wait_status = NULL;
4724
cf7f2e2d 4725 pid = parse_pid_to_attach (args);
5796c8dc 4726
cf7f2e2d
JM
4727 /* Remote PID can be freely equal to getpid, do not check it here the same
4728 way as in other targets. */
5796c8dc 4729
25e4902b 4730 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5796c8dc
SS
4731 error (_("This target does not support attaching to a process"));
4732
ef5ccd6c
JM
4733 if (from_tty)
4734 {
4735 char *exec_file = get_exec_file (0);
4736
4737 if (exec_file)
4738 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4739 target_pid_to_str (pid_to_ptid (pid)));
4740 else
4741 printf_unfiltered (_("Attaching to %s\n"),
4742 target_pid_to_str (pid_to_ptid (pid)));
4743
4744 gdb_flush (gdb_stdout);
4745 }
4746
4747 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5796c8dc
SS
4748 putpkt (rs->buf);
4749 getpkt (&rs->buf, &rs->buf_size, 0);
4750
25e4902b
AHJ
4751 switch (packet_ok (rs->buf,
4752 &remote_protocol_packets[PACKET_vAttach]))
5796c8dc 4753 {
25e4902b 4754 case PACKET_OK:
5796c8dc
SS
4755 if (!non_stop)
4756 {
4757 /* Save the reply for later. */
4758 wait_status = alloca (strlen (rs->buf) + 1);
4759 strcpy (wait_status, rs->buf);
4760 }
4761 else if (strcmp (rs->buf, "OK") != 0)
4762 error (_("Attaching to %s failed with: %s"),
4763 target_pid_to_str (pid_to_ptid (pid)),
4764 rs->buf);
25e4902b
AHJ
4765 break;
4766 case PACKET_UNKNOWN:
4767 error (_("This target does not support attaching to a process"));
4768 default:
4769 error (_("Attaching to %s failed"),
4770 target_pid_to_str (pid_to_ptid (pid)));
5796c8dc 4771 }
5796c8dc 4772
25e4902b 4773 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5796c8dc
SS
4774
4775 inferior_ptid = pid_to_ptid (pid);
4776
4777 if (non_stop)
4778 {
4779 struct thread_info *thread;
4780
4781 /* Get list of threads. */
25e4902b 4782 remote_update_thread_list (target);
5796c8dc
SS
4783
4784 thread = first_thread_of_process (pid);
4785 if (thread)
4786 inferior_ptid = thread->ptid;
4787 else
4788 inferior_ptid = pid_to_ptid (pid);
4789
4790 /* Invalidate our notion of the remote current thread. */
25e4902b 4791 record_currthread (rs, minus_one_ptid);
5796c8dc
SS
4792 }
4793 else
4794 {
4795 /* Now, if we have thread information, update inferior_ptid. */
4796 inferior_ptid = remote_current_thread (inferior_ptid);
4797
4798 /* Add the main thread to the thread list. */
4799 add_thread_silent (inferior_ptid);
4800 }
4801
4802 /* Next, if the target can specify a description, read it. We do
4803 this before anything involving memory or registers. */
4804 target_find_description ();
4805
4806 if (!non_stop)
4807 {
4808 /* Use the previously fetched status. */
4809 gdb_assert (wait_status != NULL);
4810
4811 if (target_can_async_p ())
4812 {
ef5ccd6c
JM
4813 struct notif_event *reply
4814 = remote_notif_parse (&notif_client_stop, wait_status);
5796c8dc 4815
ef5ccd6c 4816 push_stop_reply ((struct stop_reply *) reply);
5796c8dc 4817
25e4902b 4818 target_async (1);
5796c8dc
SS
4819 }
4820 else
4821 {
4822 gdb_assert (wait_status != NULL);
4823 strcpy (rs->buf, wait_status);
4824 rs->cached_wait_status = 1;
4825 }
4826 }
4827 else
4828 gdb_assert (wait_status == NULL);
4829}
4830
25e4902b 4831/* Implementation of the to_post_attach method. */
5796c8dc 4832
25e4902b
AHJ
4833static void
4834extended_remote_post_attach (struct target_ops *ops, int pid)
5796c8dc 4835{
25e4902b
AHJ
4836 /* In certain cases GDB might not have had the chance to start
4837 symbol lookup up until now. This could happen if the debugged
4838 binary is not using shared libraries, the vsyscall page is not
4839 present (on Linux) and the binary itself hadn't changed since the
4840 debugging process was started. */
4841 if (symfile_objfile != NULL)
4842 remote_check_symbols();
5796c8dc
SS
4843}
4844
5796c8dc
SS
4845\f
4846/* Check for the availability of vCont. This function should also check
4847 the response. */
4848
4849static void
4850remote_vcont_probe (struct remote_state *rs)
4851{
4852 char *buf;
4853
4854 strcpy (rs->buf, "vCont?");
4855 putpkt (rs->buf);
4856 getpkt (&rs->buf, &rs->buf_size, 0);
4857 buf = rs->buf;
4858
4859 /* Make sure that the features we assume are supported. */
25e4902b 4860 if (startswith (buf, "vCont"))
5796c8dc
SS
4861 {
4862 char *p = &buf[5];
4863 int support_s, support_S, support_c, support_C;
4864
4865 support_s = 0;
4866 support_S = 0;
4867 support_c = 0;
4868 support_C = 0;
25e4902b
AHJ
4869 rs->supports_vCont.t = 0;
4870 rs->supports_vCont.r = 0;
5796c8dc
SS
4871 while (p && *p == ';')
4872 {
4873 p++;
4874 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4875 support_s = 1;
4876 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4877 support_S = 1;
4878 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4879 support_c = 1;
4880 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4881 support_C = 1;
4882 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
25e4902b
AHJ
4883 rs->supports_vCont.t = 1;
4884 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4885 rs->supports_vCont.r = 1;
5796c8dc
SS
4886
4887 p = strchr (p, ';');
4888 }
4889
4890 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4891 BUF will make packet_ok disable the packet. */
4892 if (!support_s || !support_S || !support_c || !support_C)
4893 buf[0] = 0;
4894 }
4895
4896 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4897}
4898
4899/* Helper function for building "vCont" resumptions. Write a
4900 resumption to P. ENDP points to one-passed-the-end of the buffer
4901 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4902 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4903 resumed thread should be single-stepped and/or signalled. If PTID
4904 equals minus_one_ptid, then all threads are resumed; if PTID
4905 represents a process, then all threads of the process are resumed;
4906 the thread to be stepped and/or signalled is given in the global
4907 INFERIOR_PTID. */
4908
4909static char *
4910append_resumption (char *p, char *endp,
ef5ccd6c 4911 ptid_t ptid, int step, enum gdb_signal siggnal)
5796c8dc
SS
4912{
4913 struct remote_state *rs = get_remote_state ();
4914
ef5ccd6c 4915 if (step && siggnal != GDB_SIGNAL_0)
5796c8dc 4916 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
25e4902b
AHJ
4917 else if (step
4918 /* GDB is willing to range step. */
4919 && use_range_stepping
4920 /* Target supports range stepping. */
4921 && rs->supports_vCont.r
4922 /* We don't currently support range stepping multiple
4923 threads with a wildcard (though the protocol allows it,
4924 so stubs shouldn't make an active effort to forbid
4925 it). */
4926 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4927 {
4928 struct thread_info *tp;
4929
4930 if (ptid_equal (ptid, minus_one_ptid))
4931 {
4932 /* If we don't know about the target thread's tid, then
4933 we're resuming magic_null_ptid (see caller). */
4934 tp = find_thread_ptid (magic_null_ptid);
4935 }
4936 else
4937 tp = find_thread_ptid (ptid);
4938 gdb_assert (tp != NULL);
4939
4940 if (tp->control.may_range_step)
4941 {
4942 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4943
4944 p += xsnprintf (p, endp - p, ";r%s,%s",
4945 phex_nz (tp->control.step_range_start,
4946 addr_size),
4947 phex_nz (tp->control.step_range_end,
4948 addr_size));
4949 }
4950 else
4951 p += xsnprintf (p, endp - p, ";s");
4952 }
5796c8dc
SS
4953 else if (step)
4954 p += xsnprintf (p, endp - p, ";s");
ef5ccd6c 4955 else if (siggnal != GDB_SIGNAL_0)
5796c8dc
SS
4956 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4957 else
4958 p += xsnprintf (p, endp - p, ";c");
4959
4960 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4961 {
4962 ptid_t nptid;
4963
4964 /* All (-1) threads of process. */
25e4902b 4965 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5796c8dc
SS
4966
4967 p += xsnprintf (p, endp - p, ":");
4968 p = write_ptid (p, endp, nptid);
4969 }
4970 else if (!ptid_equal (ptid, minus_one_ptid))
4971 {
4972 p += xsnprintf (p, endp - p, ":");
4973 p = write_ptid (p, endp, ptid);
4974 }
4975
4976 return p;
4977}
4978
ef5ccd6c
JM
4979/* Append a vCont continue-with-signal action for threads that have a
4980 non-zero stop signal. */
4981
4982static char *
4983append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4984{
4985 struct thread_info *thread;
4986
25e4902b 4987 ALL_NON_EXITED_THREADS (thread)
ef5ccd6c
JM
4988 if (ptid_match (thread->ptid, ptid)
4989 && !ptid_equal (inferior_ptid, thread->ptid)
25e4902b 4990 && thread->suspend.stop_signal != GDB_SIGNAL_0)
ef5ccd6c
JM
4991 {
4992 p = append_resumption (p, endp, thread->ptid,
4993 0, thread->suspend.stop_signal);
4994 thread->suspend.stop_signal = GDB_SIGNAL_0;
4995 }
4996
4997 return p;
4998}
4999
5796c8dc
SS
5000/* Resume the remote inferior by using a "vCont" packet. The thread
5001 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5002 resumed thread should be single-stepped and/or signalled. If PTID
5003 equals minus_one_ptid, then all threads are resumed; the thread to
5004 be stepped and/or signalled is given in the global INFERIOR_PTID.
5005 This function returns non-zero iff it resumes the inferior.
5006
5007 This function issues a strict subset of all possible vCont commands at the
5008 moment. */
5009
5010static int
ef5ccd6c 5011remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5796c8dc
SS
5012{
5013 struct remote_state *rs = get_remote_state ();
5014 char *p;
5015 char *endp;
5016
25e4902b 5017 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5796c8dc
SS
5018 remote_vcont_probe (rs);
5019
25e4902b 5020 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5796c8dc
SS
5021 return 0;
5022
5023 p = rs->buf;
5024 endp = rs->buf + get_remote_packet_size ();
5025
5026 /* If we could generate a wider range of packets, we'd have to worry
5027 about overflowing BUF. Should there be a generic
5028 "multi-part-packet" packet? */
5029
5030 p += xsnprintf (p, endp - p, "vCont");
5031
5032 if (ptid_equal (ptid, magic_null_ptid))
5033 {
5034 /* MAGIC_NULL_PTID means that we don't have any active threads,
5035 so we don't have any TID numbers the inferior will
5036 understand. Make sure to only send forms that do not specify
5037 a TID. */
c50c785c 5038 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5796c8dc
SS
5039 }
5040 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5041 {
5042 /* Resume all threads (of all processes, or of a single
5043 process), with preference for INFERIOR_PTID. This assumes
5044 inferior_ptid belongs to the set of all threads we are about
5045 to resume. */
ef5ccd6c 5046 if (step || siggnal != GDB_SIGNAL_0)
5796c8dc
SS
5047 {
5048 /* Step inferior_ptid, with or without signal. */
5049 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5050 }
5051
ef5ccd6c
JM
5052 /* Also pass down any pending signaled resumption for other
5053 threads not the current. */
5054 p = append_pending_thread_resumptions (p, endp, ptid);
5055
5796c8dc 5056 /* And continue others without a signal. */
ef5ccd6c 5057 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5796c8dc
SS
5058 }
5059 else
5060 {
5061 /* Scheduler locking; resume only PTID. */
c50c785c 5062 append_resumption (p, endp, ptid, step, siggnal);
5796c8dc
SS
5063 }
5064
5065 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5066 putpkt (rs->buf);
5067
5068 if (non_stop)
5069 {
5070 /* In non-stop, the stub replies to vCont with "OK". The stop
5071 reply will be reported asynchronously by means of a `%Stop'
5072 notification. */
5073 getpkt (&rs->buf, &rs->buf_size, 0);
5074 if (strcmp (rs->buf, "OK") != 0)
5075 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5076 }
5077
5078 return 1;
5079}
5080
5081/* Tell the remote machine to resume. */
5082
5796c8dc
SS
5083static void
5084remote_resume (struct target_ops *ops,
ef5ccd6c 5085 ptid_t ptid, int step, enum gdb_signal siggnal)
5796c8dc
SS
5086{
5087 struct remote_state *rs = get_remote_state ();
5088 char *buf;
5089
ef5ccd6c
JM
5090 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5091 (explained in remote-notif.c:handle_notification) so
5092 remote_notif_process is not called. We need find a place where
5093 it is safe to start a 'vNotif' sequence. It is good to do it
5094 before resuming inferior, because inferior was stopped and no RSP
5095 traffic at that moment. */
5096 if (!non_stop)
25e4902b 5097 remote_notif_process (rs->notif_state, &notif_client_stop);
ef5ccd6c 5098
25e4902b
AHJ
5099 rs->last_sent_signal = siggnal;
5100 rs->last_sent_step = step;
5796c8dc 5101
5796c8dc
SS
5102 /* The vCont packet doesn't need to specify threads via Hc. */
5103 /* No reverse support (yet) for vCont. */
5104 if (execution_direction != EXEC_REVERSE)
5105 if (remote_vcont_resume (ptid, step, siggnal))
5106 goto done;
5107
5108 /* All other supported resume packets do use Hc, so set the continue
5109 thread. */
5110 if (ptid_equal (ptid, minus_one_ptid))
5111 set_continue_thread (any_thread_ptid);
5112 else
5113 set_continue_thread (ptid);
5114
5115 buf = rs->buf;
5116 if (execution_direction == EXEC_REVERSE)
5117 {
5118 /* We don't pass signals to the target in reverse exec mode. */
ef5ccd6c 5119 if (info_verbose && siggnal != GDB_SIGNAL_0)
c50c785c 5120 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5796c8dc
SS
5121 siggnal);
5122
25e4902b 5123 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5796c8dc 5124 error (_("Remote reverse-step not supported."));
25e4902b 5125 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5796c8dc
SS
5126 error (_("Remote reverse-continue not supported."));
5127
5128 strcpy (buf, step ? "bs" : "bc");
5129 }
ef5ccd6c 5130 else if (siggnal != GDB_SIGNAL_0)
5796c8dc
SS
5131 {
5132 buf[0] = step ? 'S' : 'C';
5133 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5134 buf[2] = tohex (((int) siggnal) & 0xf);
5135 buf[3] = '\0';
5136 }
5137 else
5138 strcpy (buf, step ? "s" : "c");
5139
5140 putpkt (buf);
5141
5142 done:
5143 /* We are about to start executing the inferior, let's register it
c50c785c
JM
5144 with the event loop. NOTE: this is the one place where all the
5145 execution commands end up. We could alternatively do this in each
5796c8dc
SS
5146 of the execution commands in infcmd.c. */
5147 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5148 into infcmd.c in order to allow inferior function calls to work
5149 NOT asynchronously. */
5150 if (target_can_async_p ())
25e4902b 5151 target_async (1);
5796c8dc
SS
5152
5153 /* We've just told the target to resume. The remote server will
5154 wait for the inferior to stop, and then send a stop reply. In
5155 the mean time, we can't start another command/query ourselves
5156 because the stub wouldn't be ready to process it. This applies
5157 only to the base all-stop protocol, however. In non-stop (which
5158 only supports vCont), the stub replies with an "OK", and is
5159 immediate able to process further serial input. */
5160 if (!non_stop)
5161 rs->waiting_for_stop_reply = 1;
5162}
5163\f
5164
5165/* Set up the signal handler for SIGINT, while the target is
5166 executing, ovewriting the 'regular' SIGINT signal handler. */
5167static void
25e4902b 5168async_initialize_sigint_signal_handler (void)
5796c8dc 5169{
25e4902b 5170 signal (SIGINT, async_handle_remote_sigint);
5796c8dc
SS
5171}
5172
5173/* Signal handler for SIGINT, while the target is executing. */
5174static void
25e4902b 5175async_handle_remote_sigint (int sig)
5796c8dc 5176{
25e4902b
AHJ
5177 signal (sig, async_handle_remote_sigint_twice);
5178 /* Note we need to go through gdb_call_async_signal_handler in order
5179 to wake up the event loop on Windows. */
5180 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5796c8dc
SS
5181}
5182
5183/* Signal handler for SIGINT, installed after SIGINT has already been
5184 sent once. It will take effect the second time that the user sends
5185 a ^C. */
5186static void
25e4902b
AHJ
5187async_handle_remote_sigint_twice (int sig)
5188{
5189 signal (sig, async_handle_remote_sigint);
5190 /* See note in async_handle_remote_sigint. */
5191 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5192}
5193
5194/* Implementation of to_check_pending_interrupt. */
5195
5196static void
5197remote_check_pending_interrupt (struct target_ops *self)
5796c8dc 5198{
25e4902b
AHJ
5199 struct async_signal_handler *token = async_sigint_remote_twice_token;
5200
5201 if (async_signal_handler_is_marked (token))
5202 {
5203 clear_async_signal_handler (token);
5204 call_async_signal_handler (token);
5205 }
5796c8dc
SS
5206}
5207
5208/* Perform the real interruption of the target execution, in response
5209 to a ^C. */
5210static void
5211async_remote_interrupt (gdb_client_data arg)
5212{
5213 if (remote_debug)
ef5ccd6c 5214 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5796c8dc
SS
5215
5216 target_stop (inferior_ptid);
5217}
5218
c50c785c 5219/* Perform interrupt, if the first attempt did not succeed. Just give
5796c8dc 5220 up on the target alltogether. */
25e4902b 5221static void
5796c8dc
SS
5222async_remote_interrupt_twice (gdb_client_data arg)
5223{
5224 if (remote_debug)
ef5ccd6c 5225 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5796c8dc
SS
5226
5227 interrupt_query ();
5228}
5229
5230/* Reinstall the usual SIGINT handlers, after the target has
5231 stopped. */
5232static void
25e4902b 5233async_cleanup_sigint_signal_handler (void *dummy)
5796c8dc
SS
5234{
5235 signal (SIGINT, handle_sigint);
5236}
5237
5238/* Send ^C to target to halt it. Target will respond, and send us a
5239 packet. */
5240static void (*ofunc) (int);
5241
c50c785c
JM
5242/* The command line interface's stop routine. This function is installed
5243 as a signal handler for SIGINT. The first time a user requests a
5244 stop, we call remote_stop to send a break or ^C. If there is no
5796c8dc
SS
5245 response from the target (it didn't stop when the user requested it),
5246 we ask the user if he'd like to detach from the target. */
5247static void
25e4902b 5248sync_remote_interrupt (int signo)
5796c8dc
SS
5249{
5250 /* If this doesn't work, try more severe steps. */
25e4902b 5251 signal (signo, sync_remote_interrupt_twice);
5796c8dc 5252
25e4902b 5253 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5796c8dc
SS
5254}
5255
5256/* The user typed ^C twice. */
5257
5258static void
25e4902b 5259sync_remote_interrupt_twice (int signo)
5796c8dc
SS
5260{
5261 signal (signo, ofunc);
25e4902b
AHJ
5262 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5263 signal (signo, sync_remote_interrupt);
5796c8dc
SS
5264}
5265
5266/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5267 thread, all threads of a remote process, or all threads of all
5268 processes. */
5269
5270static void
5271remote_stop_ns (ptid_t ptid)
5272{
5273 struct remote_state *rs = get_remote_state ();
5274 char *p = rs->buf;
5275 char *endp = rs->buf + get_remote_packet_size ();
5276
25e4902b 5277 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5796c8dc
SS
5278 remote_vcont_probe (rs);
5279
25e4902b 5280 if (!rs->supports_vCont.t)
5796c8dc
SS
5281 error (_("Remote server does not support stopping threads"));
5282
5283 if (ptid_equal (ptid, minus_one_ptid)
5284 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5285 p += xsnprintf (p, endp - p, "vCont;t");
5286 else
5287 {
5288 ptid_t nptid;
5289
5290 p += xsnprintf (p, endp - p, "vCont;t:");
5291
5292 if (ptid_is_pid (ptid))
5293 /* All (-1) threads of process. */
25e4902b 5294 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5796c8dc
SS
5295 else
5296 {
5297 /* Small optimization: if we already have a stop reply for
5298 this thread, no use in telling the stub we want this
5299 stopped. */
5300 if (peek_stop_reply (ptid))
5301 return;
5302
5303 nptid = ptid;
5304 }
5305
c50c785c 5306 write_ptid (p, endp, nptid);
5796c8dc
SS
5307 }
5308
5309 /* In non-stop, we get an immediate OK reply. The stop reply will
5310 come in asynchronously by notification. */
5311 putpkt (rs->buf);
5312 getpkt (&rs->buf, &rs->buf_size, 0);
5313 if (strcmp (rs->buf, "OK") != 0)
5314 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5315}
5316
5317/* All-stop version of target_stop. Sends a break or a ^C to stop the
5318 remote target. It is undefined which thread of which process
5319 reports the stop. */
5320
5321static void
5322remote_stop_as (ptid_t ptid)
5323{
5324 struct remote_state *rs = get_remote_state ();
5325
cf7f2e2d
JM
5326 rs->ctrlc_pending_p = 1;
5327
5796c8dc
SS
5328 /* If the inferior is stopped already, but the core didn't know
5329 about it yet, just ignore the request. The cached wait status
5330 will be collected in remote_wait. */
5331 if (rs->cached_wait_status)
5332 return;
5333
cf7f2e2d
JM
5334 /* Send interrupt_sequence to remote target. */
5335 send_interrupt_sequence ();
5796c8dc
SS
5336}
5337
c50c785c 5338/* This is the generic stop called via the target vector. When a target
5796c8dc
SS
5339 interrupt is requested, either by the command line or the GUI, we
5340 will eventually end up here. */
5341
5342static void
25e4902b 5343remote_stop (struct target_ops *self, ptid_t ptid)
5796c8dc
SS
5344{
5345 if (remote_debug)
5346 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5347
5348 if (non_stop)
5349 remote_stop_ns (ptid);
5350 else
5351 remote_stop_as (ptid);
5352}
5353
5354/* Ask the user what to do when an interrupt is received. */
5355
5356static void
5357interrupt_query (void)
5358{
25e4902b
AHJ
5359 struct remote_state *rs = get_remote_state ();
5360 struct cleanup *old_chain;
5361
5362 old_chain = make_cleanup_restore_target_terminal ();
5796c8dc
SS
5363 target_terminal_ours ();
5364
25e4902b 5365 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5796c8dc 5366 {
25e4902b
AHJ
5367 if (query (_("The target is not responding to interrupt requests.\n"
5368 "Stop debugging it? ")))
5796c8dc 5369 {
ef5ccd6c 5370 remote_unpush_target ();
25e4902b 5371 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5796c8dc
SS
5372 }
5373 }
25e4902b
AHJ
5374 else
5375 {
5376 if (query (_("Interrupted while waiting for the program.\n"
5377 "Give up waiting? ")))
5378 quit ();
5379 }
5796c8dc 5380
25e4902b 5381 do_cleanups (old_chain);
5796c8dc
SS
5382}
5383
5384/* Enable/disable target terminal ownership. Most targets can use
5385 terminal groups to control terminal ownership. Remote targets are
5386 different in that explicit transfer of ownership to/from GDB/target
5387 is required. */
5388
5389static void
25e4902b 5390remote_terminal_inferior (struct target_ops *self)
5796c8dc
SS
5391{
5392 if (!target_async_permitted)
5393 /* Nothing to do. */
5394 return;
5395
5396 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5397 idempotent. The event-loop GDB talking to an asynchronous target
5398 with a synchronous command calls this function from both
5399 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5400 transfer the terminal to the target when it shouldn't this guard
5401 can go away. */
5402 if (!remote_async_terminal_ours_p)
5403 return;
5404 delete_file_handler (input_fd);
5405 remote_async_terminal_ours_p = 0;
25e4902b 5406 async_initialize_sigint_signal_handler ();
5796c8dc
SS
5407 /* NOTE: At this point we could also register our selves as the
5408 recipient of all input. Any characters typed could then be
5409 passed on down to the target. */
5410}
5411
5412static void
25e4902b 5413remote_terminal_ours (struct target_ops *self)
5796c8dc
SS
5414{
5415 if (!target_async_permitted)
5416 /* Nothing to do. */
5417 return;
5418
5419 /* See FIXME in remote_terminal_inferior. */
5420 if (remote_async_terminal_ours_p)
5421 return;
25e4902b 5422 async_cleanup_sigint_signal_handler (NULL);
5796c8dc
SS
5423 add_file_handler (input_fd, stdin_event_handler, 0);
5424 remote_async_terminal_ours_p = 1;
5425}
5426
cf7f2e2d 5427static void
5796c8dc
SS
5428remote_console_output (char *msg)
5429{
5430 char *p;
5431
5432 for (p = msg; p[0] && p[1]; p += 2)
5433 {
5434 char tb[2];
5435 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
cf7f2e2d 5436
5796c8dc
SS
5437 tb[0] = c;
5438 tb[1] = 0;
5439 fputs_unfiltered (tb, gdb_stdtarg);
5440 }
a45ae5f8
JM
5441 gdb_flush (gdb_stdtarg);
5442}
5796c8dc
SS
5443
5444typedef struct cached_reg
5445{
5446 int num;
5447 gdb_byte data[MAX_REGISTER_SIZE];
5448} cached_reg_t;
5449
5450DEF_VEC_O(cached_reg_t);
5451
ef5ccd6c 5452typedef struct stop_reply
5796c8dc 5453{
ef5ccd6c 5454 struct notif_event base;
5796c8dc 5455
ef5ccd6c 5456 /* The identifier of the thread about this event */
5796c8dc
SS
5457 ptid_t ptid;
5458
25e4902b
AHJ
5459 /* The remote state this event is associated with. When the remote
5460 connection, represented by a remote_state object, is closed,
5461 all the associated stop_reply events should be released. */
5462 struct remote_state *rs;
5463
5796c8dc
SS
5464 struct target_waitstatus ws;
5465
a45ae5f8
JM
5466 /* Expedited registers. This makes remote debugging a bit more
5467 efficient for those targets that provide critical registers as
5468 part of their normal status mechanism (as another roundtrip to
5469 fetch them is avoided). */
5796c8dc
SS
5470 VEC(cached_reg_t) *regcache;
5471
25e4902b 5472 enum target_stop_reason stop_reason;
5796c8dc 5473
25e4902b 5474 CORE_ADDR watch_data_address;
cf7f2e2d
JM
5475
5476 int core;
ef5ccd6c 5477} *stop_reply_p;
5796c8dc 5478
ef5ccd6c
JM
5479DECLARE_QUEUE_P (stop_reply_p);
5480DEFINE_QUEUE_P (stop_reply_p);
5481/* The list of already fetched and acknowledged stop events. This
5482 queue is used for notification Stop, and other notifications
5483 don't need queue for their events, because the notification events
5484 of Stop can't be consumed immediately, so that events should be
5485 queued first, and be consumed by remote_wait_{ns,as} one per
5486 time. Other notifications can consume their events immediately,
5487 so queue is not needed for them. */
5488static QUEUE (stop_reply_p) *stop_reply_queue;
5796c8dc
SS
5489
5490static void
5491stop_reply_xfree (struct stop_reply *r)
5492{
25e4902b 5493 notif_event_xfree ((struct notif_event *) r);
5796c8dc
SS
5494}
5495
ef5ccd6c
JM
5496static void
5497remote_notif_stop_parse (struct notif_client *self, char *buf,
5498 struct notif_event *event)
5499{
5500 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5501}
5796c8dc
SS
5502
5503static void
ef5ccd6c
JM
5504remote_notif_stop_ack (struct notif_client *self, char *buf,
5505 struct notif_event *event)
5796c8dc 5506{
ef5ccd6c 5507 struct stop_reply *stop_reply = (struct stop_reply *) event;
5796c8dc 5508
ef5ccd6c
JM
5509 /* acknowledge */
5510 putpkt ((char *) self->ack_command);
5796c8dc 5511
ef5ccd6c
JM
5512 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5513 /* We got an unknown stop reply. */
5514 error (_("Unknown stop reply"));
5796c8dc 5515
ef5ccd6c 5516 push_stop_reply (stop_reply);
5796c8dc
SS
5517}
5518
ef5ccd6c
JM
5519static int
5520remote_notif_stop_can_get_pending_events (struct notif_client *self)
5521{
5522 /* We can't get pending events in remote_notif_process for
5523 notification stop, and we have to do this in remote_wait_ns
5524 instead. If we fetch all queued events from stub, remote stub
5525 may exit and we have no chance to process them back in
5526 remote_wait_ns. */
5527 mark_async_event_handler (remote_async_inferior_event_token);
5528 return 0;
5529}
5796c8dc
SS
5530
5531static void
ef5ccd6c 5532stop_reply_dtr (struct notif_event *event)
5796c8dc 5533{
ef5ccd6c 5534 struct stop_reply *r = (struct stop_reply *) event;
cf7f2e2d 5535
ef5ccd6c 5536 VEC_free (cached_reg_t, r->regcache);
5796c8dc
SS
5537}
5538
ef5ccd6c
JM
5539static struct notif_event *
5540remote_notif_stop_alloc_reply (void)
5541{
5542 struct notif_event *r
25e4902b 5543 = (struct notif_event *) XNEW (struct stop_reply);
5796c8dc 5544
ef5ccd6c
JM
5545 r->dtr = stop_reply_dtr;
5546
5547 return r;
5548}
5549
5550/* A client of notification Stop. */
5551
5552struct notif_client notif_client_stop =
5796c8dc 5553{
ef5ccd6c
JM
5554 "Stop",
5555 "vStopped",
5556 remote_notif_stop_parse,
5557 remote_notif_stop_ack,
5558 remote_notif_stop_can_get_pending_events,
5559 remote_notif_stop_alloc_reply,
25e4902b 5560 REMOTE_NOTIF_STOP,
ef5ccd6c 5561};
5796c8dc 5562
ef5ccd6c 5563/* A parameter to pass data in and out. */
5796c8dc 5564
ef5ccd6c
JM
5565struct queue_iter_param
5566{
5567 void *input;
5568 struct stop_reply *output;
5569};
5796c8dc 5570
25e4902b
AHJ
5571/* Determine if THREAD is a pending fork parent thread. ARG contains
5572 the pid of the process that owns the threads we want to check, or
5573 -1 if we want to check all threads. */
5574
5575static int
5576is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5577 ptid_t thread_ptid)
5578{
5579 if (ws->kind == TARGET_WAITKIND_FORKED
5580 || ws->kind == TARGET_WAITKIND_VFORKED)
5581 {
5582 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5583 return 1;
5584 }
5585
5586 return 0;
5587}
5588
5589/* Check whether EVENT is a fork event, and if it is, remove the
5590 fork child from the context list passed in DATA. */
5591
5592static int
5593remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5594 QUEUE_ITER (stop_reply_p) *iter,
5595 stop_reply_p event,
5596 void *data)
5597{
5598 struct queue_iter_param *param = data;
5599 struct threads_listing_context *context = param->input;
5600
5601 if (event->ws.kind == TARGET_WAITKIND_FORKED
5602 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5603 {
5604 threads_listing_context_remove (&event->ws, context);
5605 }
5606
5607 return 1;
5608}
5609
5610/* If CONTEXT contains any fork child threads that have not been
5611 reported yet, remove them from the CONTEXT list. If such a
5612 thread exists it is because we are stopped at a fork catchpoint
5613 and have not yet called follow_fork, which will set up the
5614 host-side data structures for the new process. */
5615
5616static void
5617remove_new_fork_children (struct threads_listing_context *context)
5618{
5619 struct thread_info * thread;
5620 int pid = -1;
5621 struct notif_client *notif = &notif_client_stop;
5622 struct queue_iter_param param;
5623
5624 /* For any threads stopped at a fork event, remove the corresponding
5625 fork child threads from the CONTEXT list. */
5626 ALL_NON_EXITED_THREADS (thread)
5627 {
5628 struct target_waitstatus *ws = &thread->pending_follow;
5629
5630 if (is_pending_fork_parent (ws, pid, thread->ptid))
5631 {
5632 threads_listing_context_remove (ws, context);
5633 }
5634 }
5635
5636 /* Check for any pending fork events (not reported or processed yet)
5637 in process PID and remove those fork child threads from the
5638 CONTEXT list as well. */
5639 remote_notif_get_pending_events (notif);
5640 param.input = context;
5641 param.output = NULL;
5642 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5643 remove_child_of_pending_fork, &param);
5644}
5645
5646/* Remove stop replies in the queue if its pid is equal to the given
5647 inferior's pid. */
5796c8dc 5648
ef5ccd6c 5649static int
25e4902b
AHJ
5650remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5651 QUEUE_ITER (stop_reply_p) *iter,
5652 stop_reply_p event,
5653 void *data)
ef5ccd6c
JM
5654{
5655 struct queue_iter_param *param = data;
5656 struct inferior *inf = param->input;
5657
25e4902b 5658 if (ptid_get_pid (event->ptid) == inf->pid)
ef5ccd6c
JM
5659 {
5660 stop_reply_xfree (event);
5661 QUEUE_remove_elem (stop_reply_p, q, iter);
5662 }
5663
5664 return 1;
5796c8dc
SS
5665}
5666
25e4902b 5667/* Discard all pending stop replies of inferior INF. */
5796c8dc
SS
5668
5669static void
ef5ccd6c 5670discard_pending_stop_replies (struct inferior *inf)
5796c8dc 5671{
ef5ccd6c
JM
5672 int i;
5673 struct queue_iter_param param;
25e4902b
AHJ
5674 struct stop_reply *reply;
5675 struct remote_state *rs = get_remote_state ();
5676 struct remote_notif_state *rns = rs->notif_state;
5677
5678 /* This function can be notified when an inferior exists. When the
5679 target is not remote, the notification state is NULL. */
5680 if (rs->remote_desc == NULL)
5681 return;
5682
5683 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5796c8dc 5684
ef5ccd6c 5685 /* Discard the in-flight notification. */
25e4902b 5686 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5796c8dc 5687 {
ef5ccd6c 5688 stop_reply_xfree (reply);
25e4902b 5689 rns->pending_event[notif_client_stop.id] = NULL;
5796c8dc 5690 }
5796c8dc 5691
ef5ccd6c
JM
5692 param.input = inf;
5693 param.output = NULL;
5694 /* Discard the stop replies we have already pulled with
5695 vStopped. */
5696 QUEUE_iterate (stop_reply_p, stop_reply_queue,
25e4902b
AHJ
5697 remove_stop_reply_for_inferior, &param);
5698}
5699
5700/* If its remote state is equal to the given remote state,
5701 remove EVENT from the stop reply queue. */
5702
5703static int
5704remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5705 QUEUE_ITER (stop_reply_p) *iter,
5706 stop_reply_p event,
5707 void *data)
5708{
5709 struct queue_iter_param *param = data;
5710 struct remote_state *rs = param->input;
5711
5712 if (event->rs == rs)
5713 {
5714 stop_reply_xfree (event);
5715 QUEUE_remove_elem (stop_reply_p, q, iter);
5716 }
5717
5718 return 1;
5719}
5720
5721/* Discard the stop replies for RS in stop_reply_queue. */
5722
5723static void
5724discard_pending_stop_replies_in_queue (struct remote_state *rs)
5725{
5726 struct queue_iter_param param;
5727
5728 param.input = rs;
5729 param.output = NULL;
5730 /* Discard the stop replies we have already pulled with
5731 vStopped. */
5732 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5733 remove_stop_reply_of_remote_state, &param);
5796c8dc
SS
5734}
5735
ef5ccd6c 5736/* A parameter to pass data in and out. */
5796c8dc
SS
5737
5738static int
ef5ccd6c
JM
5739remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5740 QUEUE_ITER (stop_reply_p) *iter,
5741 stop_reply_p event,
5742 void *data)
5796c8dc 5743{
ef5ccd6c
JM
5744 struct queue_iter_param *param = data;
5745 ptid_t *ptid = param->input;
5796c8dc 5746
ef5ccd6c
JM
5747 if (ptid_match (event->ptid, *ptid))
5748 {
5749 param->output = event;
5750 QUEUE_remove_elem (stop_reply_p, q, iter);
5751 return 0;
5752 }
5796c8dc 5753
ef5ccd6c
JM
5754 return 1;
5755}
5756
5757/* Remove the first reply in 'stop_reply_queue' which matches
5758 PTID. */
5759
5760static struct stop_reply *
5761remote_notif_remove_queued_reply (ptid_t ptid)
5762{
5763 struct queue_iter_param param;
5764
5765 param.input = &ptid;
5766 param.output = NULL;
5767
5768 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5769 remote_notif_remove_once_on_match, &param);
5770 if (notif_debug)
5771 fprintf_unfiltered (gdb_stdlog,
5772 "notif: discard queued event: 'Stop' in %s\n",
5773 target_pid_to_str (ptid));
5774
5775 return param.output;
5776}
5777
5778/* Look for a queued stop reply belonging to PTID. If one is found,
5779 remove it from the queue, and return it. Returns NULL if none is
5780 found. If there are still queued events left to process, tell the
5781 event loop to get back to target_wait soon. */
5782
5783static struct stop_reply *
5784queued_stop_reply (ptid_t ptid)
5785{
5786 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5787
5788 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5789 /* There's still at least an event left. */
5790 mark_async_event_handler (remote_async_inferior_event_token);
5791
5792 return r;
5793}
5794
5795/* Push a fully parsed stop reply in the stop reply queue. Since we
5796 know that we now have at least one queued event left to pass to the
5797 core side, tell the event loop to get back to target_wait soon. */
5798
5799static void
5800push_stop_reply (struct stop_reply *new_event)
5801{
5802 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5803
5804 if (notif_debug)
5805 fprintf_unfiltered (gdb_stdlog,
5806 "notif: push 'Stop' %s to queue %d\n",
5807 target_pid_to_str (new_event->ptid),
5808 QUEUE_length (stop_reply_p,
5809 stop_reply_queue));
5810
5811 mark_async_event_handler (remote_async_inferior_event_token);
5812}
5813
5814static int
5815stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5816 QUEUE_ITER (stop_reply_p) *iter,
5817 struct stop_reply *event,
5818 void *data)
5819{
5820 ptid_t *ptid = data;
5821
5822 return !(ptid_equal (*ptid, event->ptid)
5823 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5824}
5825
5826/* Returns true if we have a stop reply for PTID. */
5827
5828static int
5829peek_stop_reply (ptid_t ptid)
5830{
5831 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5832 stop_reply_match_ptid_and_ws, &ptid);
5796c8dc
SS
5833}
5834
25e4902b
AHJ
5835/* Skip PACKET until the next semi-colon (or end of string). */
5836
5837static char *
5838skip_to_semicolon (char *p)
5839{
5840 while (*p != '\0' && *p != ';')
5841 p++;
5842 return p;
5843}
5844
5845/* Helper for remote_parse_stop_reply. Return nonzero if the substring
5846 starting with P and ending with PEND matches PREFIX. */
5847
5848static int
5849strprefix (const char *p, const char *pend, const char *prefix)
5850{
5851 for ( ; p < pend; p++, prefix++)
5852 if (*p != *prefix)
5853 return 0;
5854 return *prefix == '\0';
5855}
5856
5796c8dc
SS
5857/* Parse the stop reply in BUF. Either the function succeeds, and the
5858 result is stored in EVENT, or throws an error. */
5859
5860static void
5861remote_parse_stop_reply (char *buf, struct stop_reply *event)
5862{
5863 struct remote_arch_state *rsa = get_remote_arch_state ();
5864 ULONGEST addr;
5865 char *p;
5866
5867 event->ptid = null_ptid;
25e4902b 5868 event->rs = get_remote_state ();
5796c8dc
SS
5869 event->ws.kind = TARGET_WAITKIND_IGNORE;
5870 event->ws.value.integer = 0;
25e4902b 5871 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5796c8dc 5872 event->regcache = NULL;
cf7f2e2d 5873 event->core = -1;
5796c8dc
SS
5874
5875 switch (buf[0])
5876 {
5877 case 'T': /* Status with PC, SP, FP, ... */
5878 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5879 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5880 ss = signal number
5881 n... = register number
5882 r... = register contents
5883 */
5884
5885 p = &buf[3]; /* after Txx */
5886 while (*p)
5887 {
5888 char *p1;
5796c8dc 5889 int fieldsize;
5796c8dc 5890
25e4902b
AHJ
5891 p1 = strchr (p, ':');
5892 if (p1 == NULL)
5893 error (_("Malformed packet(a) (missing colon): %s\n\
5894Packet: '%s'\n"),
5895 p, buf);
5896 if (p == p1)
5897 error (_("Malformed packet(a) (missing register number): %s\n\
5898Packet: '%s'\n"),
5899 p, buf);
5900
5901 /* Some "registers" are actually extended stop information.
5902 Note if you're adding a new entry here: GDB 7.9 and
5903 earlier assume that all register "numbers" that start
5904 with an hex digit are real register numbers. Make sure
5905 the server only sends such a packet if it knows the
5906 client understands it. */
5907
5908 if (strprefix (p, p1, "thread"))
5909 event->ptid = read_ptid (++p1, &p);
5910 else if (strprefix (p, p1, "watch")
5911 || strprefix (p, p1, "rwatch")
5912 || strprefix (p, p1, "awatch"))
5796c8dc 5913 {
25e4902b
AHJ
5914 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
5915 p = unpack_varlen_hex (++p1, &addr);
5916 event->watch_data_address = (CORE_ADDR) addr;
5796c8dc 5917 }
25e4902b
AHJ
5918 else if (strprefix (p, p1, "swbreak"))
5919 {
5920 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5921
5922 /* Make sure the stub doesn't forget to indicate support
5923 with qSupported. */
5924 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5925 error (_("Unexpected swbreak stop reason"));
5796c8dc 5926
25e4902b
AHJ
5927 /* The value part is documented as "must be empty",
5928 though we ignore it, in case we ever decide to make
5929 use of it in a backward compatible way. */
5930 p = skip_to_semicolon (p1 + 1);
5931 }
5932 else if (strprefix (p, p1, "hwbreak"))
5796c8dc 5933 {
25e4902b 5934 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5796c8dc 5935
25e4902b
AHJ
5936 /* Make sure the stub doesn't forget to indicate support
5937 with qSupported. */
5938 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5939 error (_("Unexpected hwbreak stop reason"));
5940
5941 /* See above. */
5942 p = skip_to_semicolon (p1 + 1);
5943 }
5944 else if (strprefix (p, p1, "library"))
5945 {
5946 event->ws.kind = TARGET_WAITKIND_LOADED;
5947 p = skip_to_semicolon (p1 + 1);
5948 }
5949 else if (strprefix (p, p1, "replaylog"))
5950 {
5951 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5952 /* p1 will indicate "begin" or "end", but it makes
5953 no difference for now, so ignore it. */
5954 p = skip_to_semicolon (p1 + 1);
5955 }
5956 else if (strprefix (p, p1, "core"))
5957 {
5958 ULONGEST c;
cf7f2e2d 5959
25e4902b
AHJ
5960 p = unpack_varlen_hex (++p1, &c);
5961 event->core = c;
5962 }
5963 else if (strprefix (p, p1, "fork"))
5964 {
5965 event->ws.value.related_pid = read_ptid (++p1, &p);
5966 event->ws.kind = TARGET_WAITKIND_FORKED;
5967 }
5968 else if (strprefix (p, p1, "vfork"))
5969 {
5970 event->ws.value.related_pid = read_ptid (++p1, &p);
5971 event->ws.kind = TARGET_WAITKIND_VFORKED;
5972 }
5973 else if (strprefix (p, p1, "vforkdone"))
5974 {
5975 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
5976 p = skip_to_semicolon (p1 + 1);
5796c8dc
SS
5977 }
5978 else
5979 {
25e4902b
AHJ
5980 ULONGEST pnum;
5981 char *p_temp;
5982
5983 /* Maybe a real ``P'' register number. */
5984 p_temp = unpack_varlen_hex (p, &pnum);
5985 /* If the first invalid character is the colon, we got a
5986 register number. Otherwise, it's an unknown stop
5987 reason. */
5988 if (p_temp == p1)
5989 {
5990 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5991 cached_reg_t cached_reg;
5796c8dc 5992
25e4902b
AHJ
5993 if (reg == NULL)
5994 error (_("Remote sent bad register number %s: %s\n\
5796c8dc 5995Packet: '%s'\n"),
25e4902b 5996 hex_string (pnum), p, buf);
5796c8dc 5997
25e4902b 5998 cached_reg.num = reg->regnum;
5796c8dc 5999
25e4902b
AHJ
6000 p = p1 + 1;
6001 fieldsize = hex2bin (p, cached_reg.data,
6002 register_size (target_gdbarch (),
6003 reg->regnum));
6004 p += 2 * fieldsize;
6005 if (fieldsize < register_size (target_gdbarch (),
6006 reg->regnum))
6007 warning (_("Remote reply is too short: %s"), buf);
5796c8dc 6008
25e4902b
AHJ
6009 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6010 }
6011 else
6012 {
6013 /* Not a number. Silently skip unknown optional
6014 info. */
6015 p = skip_to_semicolon (p1 + 1);
6016 }
5796c8dc
SS
6017 }
6018
6019 if (*p != ';')
6020 error (_("Remote register badly formatted: %s\nhere: %s"),
6021 buf, p);
6022 ++p;
6023 }
25e4902b
AHJ
6024
6025 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6026 break;
6027
5796c8dc
SS
6028 /* fall through */
6029 case 'S': /* Old style status, just signal only. */
25e4902b
AHJ
6030 {
6031 int sig;
6032
6033 event->ws.kind = TARGET_WAITKIND_STOPPED;
6034 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6035 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6036 event->ws.value.sig = (enum gdb_signal) sig;
6037 else
6038 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6039 }
5796c8dc
SS
6040 break;
6041 case 'W': /* Target exited. */
6042 case 'X':
6043 {
6044 char *p;
6045 int pid;
6046 ULONGEST value;
6047
6048 /* GDB used to accept only 2 hex chars here. Stubs should
6049 only send more if they detect GDB supports multi-process
6050 support. */
6051 p = unpack_varlen_hex (&buf[1], &value);
6052
6053 if (buf[0] == 'W')
6054 {
6055 /* The remote process exited. */
6056 event->ws.kind = TARGET_WAITKIND_EXITED;
6057 event->ws.value.integer = value;
6058 }
6059 else
6060 {
6061 /* The remote process exited with a signal. */
6062 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
25e4902b
AHJ
6063 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6064 event->ws.value.sig = (enum gdb_signal) value;
6065 else
6066 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5796c8dc
SS
6067 }
6068
6069 /* If no process is specified, assume inferior_ptid. */
6070 pid = ptid_get_pid (inferior_ptid);
6071 if (*p == '\0')
6072 ;
6073 else if (*p == ';')
6074 {
6075 p++;
6076
25e4902b 6077 if (*p == '\0')
5796c8dc 6078 ;
25e4902b 6079 else if (startswith (p, "process:"))
5796c8dc
SS
6080 {
6081 ULONGEST upid;
cf7f2e2d 6082
5796c8dc
SS
6083 p += sizeof ("process:") - 1;
6084 unpack_varlen_hex (p, &upid);
6085 pid = upid;
6086 }
6087 else
6088 error (_("unknown stop reply packet: %s"), buf);
6089 }
6090 else
6091 error (_("unknown stop reply packet: %s"), buf);
6092 event->ptid = pid_to_ptid (pid);
6093 }
6094 break;
6095 }
6096
6097 if (non_stop && ptid_equal (event->ptid, null_ptid))
6098 error (_("No process or thread specified in stop reply: %s"), buf);
6099}
6100
ef5ccd6c
JM
6101/* When the stub wants to tell GDB about a new notification reply, it
6102 sends a notification (%Stop, for example). Those can come it at
6103 any time, hence, we have to make sure that any pending
6104 putpkt/getpkt sequence we're making is finished, before querying
6105 the stub for more events with the corresponding ack command
6106 (vStopped, for example). E.g., if we started a vStopped sequence
6107 immediately upon receiving the notification, something like this
6108 could happen:
5796c8dc
SS
6109
6110 1.1) --> Hg 1
6111 1.2) <-- OK
6112 1.3) --> g
6113 1.4) <-- %Stop
6114 1.5) --> vStopped
6115 1.6) <-- (registers reply to step #1.3)
6116
6117 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6118 query.
6119
ef5ccd6c 6120 To solve this, whenever we parse a %Stop notification successfully,
5796c8dc
SS
6121 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6122 doing whatever we were doing:
6123
6124 2.1) --> Hg 1
6125 2.2) <-- OK
6126 2.3) --> g
6127 2.4) <-- %Stop
6128 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6129 2.5) <-- (registers reply to step #2.3)
6130
6131 Eventualy after step #2.5, we return to the event loop, which
6132 notices there's an event on the
6133 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6134 associated callback --- the function below. At this point, we're
6135 always safe to start a vStopped sequence. :
6136
6137 2.6) --> vStopped
6138 2.7) <-- T05 thread:2
6139 2.8) --> vStopped
6140 2.9) --> OK
6141*/
6142
ef5ccd6c
JM
6143void
6144remote_notif_get_pending_events (struct notif_client *nc)
5796c8dc
SS
6145{
6146 struct remote_state *rs = get_remote_state ();
6147
25e4902b 6148 if (rs->notif_state->pending_event[nc->id] != NULL)
5796c8dc 6149 {
ef5ccd6c
JM
6150 if (notif_debug)
6151 fprintf_unfiltered (gdb_stdlog,
6152 "notif: process: '%s' ack pending event\n",
6153 nc->name);
5796c8dc 6154
ef5ccd6c 6155 /* acknowledge */
25e4902b
AHJ
6156 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6157 rs->notif_state->pending_event[nc->id] = NULL;
5796c8dc
SS
6158
6159 while (1)
6160 {
6161 getpkt (&rs->buf, &rs->buf_size, 0);
6162 if (strcmp (rs->buf, "OK") == 0)
6163 break;
6164 else
ef5ccd6c 6165 remote_notif_ack (nc, rs->buf);
5796c8dc
SS
6166 }
6167 }
ef5ccd6c
JM
6168 else
6169 {
6170 if (notif_debug)
6171 fprintf_unfiltered (gdb_stdlog,
6172 "notif: process: '%s' no pending reply\n",
6173 nc->name);
6174 }
5796c8dc
SS
6175}
6176
5796c8dc
SS
6177/* Called when it is decided that STOP_REPLY holds the info of the
6178 event that is to be returned to the core. This function always
6179 destroys STOP_REPLY. */
6180
6181static ptid_t
6182process_stop_reply (struct stop_reply *stop_reply,
6183 struct target_waitstatus *status)
6184{
6185 ptid_t ptid;
6186
6187 *status = stop_reply->ws;
6188 ptid = stop_reply->ptid;
6189
6190 /* If no thread/process was reported by the stub, assume the current
6191 inferior. */
6192 if (ptid_equal (ptid, null_ptid))
6193 ptid = inferior_ptid;
6194
6195 if (status->kind != TARGET_WAITKIND_EXITED
6196 && status->kind != TARGET_WAITKIND_SIGNALLED)
6197 {
25e4902b
AHJ
6198 struct remote_state *rs = get_remote_state ();
6199
5796c8dc
SS
6200 /* Expedited registers. */
6201 if (stop_reply->regcache)
6202 {
6203 struct regcache *regcache
ef5ccd6c 6204 = get_thread_arch_regcache (ptid, target_gdbarch ());
5796c8dc
SS
6205 cached_reg_t *reg;
6206 int ix;
6207
6208 for (ix = 0;
6209 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6210 ix++)
6211 regcache_raw_supply (regcache, reg->num, reg->data);
6212 VEC_free (cached_reg_t, stop_reply->regcache);
6213 }
6214
25e4902b
AHJ
6215 rs->stop_reason = stop_reply->stop_reason;
6216 rs->remote_watch_data_address = stop_reply->watch_data_address;
5796c8dc
SS
6217
6218 remote_notice_new_inferior (ptid, 0);
cf7f2e2d 6219 demand_private_info (ptid)->core = stop_reply->core;
5796c8dc
SS
6220 }
6221
6222 stop_reply_xfree (stop_reply);
6223 return ptid;
6224}
6225
6226/* The non-stop mode version of target_wait. */
6227
6228static ptid_t
6229remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6230{
6231 struct remote_state *rs = get_remote_state ();
6232 struct stop_reply *stop_reply;
6233 int ret;
ef5ccd6c 6234 int is_notif = 0;
5796c8dc
SS
6235
6236 /* If in non-stop mode, get out of getpkt even if a
6237 notification is received. */
6238
6239 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
ef5ccd6c 6240 0 /* forever */, &is_notif);
5796c8dc
SS
6241 while (1)
6242 {
ef5ccd6c 6243 if (ret != -1 && !is_notif)
5796c8dc
SS
6244 switch (rs->buf[0])
6245 {
6246 case 'E': /* Error of some sort. */
6247 /* We're out of sync with the target now. Did it continue
6248 or not? We can't tell which thread it was in non-stop,
6249 so just ignore this. */
6250 warning (_("Remote failure reply: %s"), rs->buf);
6251 break;
6252 case 'O': /* Console output. */
6253 remote_console_output (rs->buf + 1);
6254 break;
6255 default:
6256 warning (_("Invalid remote reply: %s"), rs->buf);
6257 break;
6258 }
6259
6260 /* Acknowledge a pending stop reply that may have arrived in the
6261 mean time. */
25e4902b 6262 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
ef5ccd6c 6263 remote_notif_get_pending_events (&notif_client_stop);
5796c8dc
SS
6264
6265 /* If indeed we noticed a stop reply, we're done. */
6266 stop_reply = queued_stop_reply (ptid);
6267 if (stop_reply != NULL)
6268 return process_stop_reply (stop_reply, status);
6269
6270 /* Still no event. If we're just polling for an event, then
6271 return to the event loop. */
6272 if (options & TARGET_WNOHANG)
6273 {
6274 status->kind = TARGET_WAITKIND_IGNORE;
6275 return minus_one_ptid;
6276 }
6277
6278 /* Otherwise do a blocking wait. */
6279 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
ef5ccd6c 6280 1 /* forever */, &is_notif);
5796c8dc
SS
6281 }
6282}
6283
6284/* Wait until the remote machine stops, then return, storing status in
6285 STATUS just as `wait' would. */
6286
6287static ptid_t
6288remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6289{
6290 struct remote_state *rs = get_remote_state ();
6291 ptid_t event_ptid = null_ptid;
6292 char *buf;
6293 struct stop_reply *stop_reply;
6294
6295 again:
6296
6297 status->kind = TARGET_WAITKIND_IGNORE;
6298 status->value.integer = 0;
6299
6300 stop_reply = queued_stop_reply (ptid);
6301 if (stop_reply != NULL)
6302 return process_stop_reply (stop_reply, status);
6303
6304 if (rs->cached_wait_status)
6305 /* Use the cached wait status, but only once. */
6306 rs->cached_wait_status = 0;
6307 else
6308 {
6309 int ret;
ef5ccd6c 6310 int is_notif;
5796c8dc
SS
6311
6312 if (!target_is_async_p ())
6313 {
25e4902b 6314 ofunc = signal (SIGINT, sync_remote_interrupt);
5796c8dc
SS
6315 /* If the user hit C-c before this packet, or between packets,
6316 pretend that it was hit right here. */
ef5ccd6c 6317 if (check_quit_flag ())
5796c8dc 6318 {
ef5ccd6c 6319 clear_quit_flag ();
25e4902b 6320 sync_remote_interrupt (SIGINT);
5796c8dc
SS
6321 }
6322 }
6323
6324 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6325 _never_ wait for ever -> test on target_is_async_p().
6326 However, before we do that we need to ensure that the caller
6327 knows how to take the target into/out of async mode. */
ef5ccd6c
JM
6328 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6329 wait_forever_enabled_p, &is_notif);
6330
25e4902b
AHJ
6331 if (!target_is_async_p ())
6332 signal (SIGINT, ofunc);
6333
ef5ccd6c
JM
6334 /* GDB gets a notification. Return to core as this event is
6335 not interesting. */
6336 if (ret != -1 && is_notif)
6337 return minus_one_ptid;
5796c8dc
SS
6338 }
6339
6340 buf = rs->buf;
6341
25e4902b 6342 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5796c8dc
SS
6343
6344 /* We got something. */
6345 rs->waiting_for_stop_reply = 0;
6346
cf7f2e2d
JM
6347 /* Assume that the target has acknowledged Ctrl-C unless we receive
6348 an 'F' or 'O' packet. */
6349 if (buf[0] != 'F' && buf[0] != 'O')
6350 rs->ctrlc_pending_p = 0;
6351
5796c8dc
SS
6352 switch (buf[0])
6353 {
6354 case 'E': /* Error of some sort. */
6355 /* We're out of sync with the target now. Did it continue or
6356 not? Not is more likely, so report a stop. */
6357 warning (_("Remote failure reply: %s"), buf);
6358 status->kind = TARGET_WAITKIND_STOPPED;
ef5ccd6c 6359 status->value.sig = GDB_SIGNAL_0;
5796c8dc
SS
6360 break;
6361 case 'F': /* File-I/O request. */
cf7f2e2d
JM
6362 remote_fileio_request (buf, rs->ctrlc_pending_p);
6363 rs->ctrlc_pending_p = 0;
5796c8dc
SS
6364 break;
6365 case 'T': case 'S': case 'X': case 'W':
6366 {
ef5ccd6c
JM
6367 struct stop_reply *stop_reply
6368 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6369 rs->buf);
5796c8dc 6370
5796c8dc
SS
6371 event_ptid = process_stop_reply (stop_reply, status);
6372 break;
6373 }
6374 case 'O': /* Console output. */
6375 remote_console_output (buf + 1);
6376
6377 /* The target didn't really stop; keep waiting. */
6378 rs->waiting_for_stop_reply = 1;
6379
6380 break;
6381 case '\0':
25e4902b 6382 if (rs->last_sent_signal != GDB_SIGNAL_0)
5796c8dc
SS
6383 {
6384 /* Zero length reply means that we tried 'S' or 'C' and the
6385 remote system doesn't support it. */
6386 target_terminal_ours_for_output ();
6387 printf_filtered
6388 ("Can't send signals to this remote system. %s not sent.\n",
25e4902b
AHJ
6389 gdb_signal_to_name (rs->last_sent_signal));
6390 rs->last_sent_signal = GDB_SIGNAL_0;
5796c8dc
SS
6391 target_terminal_inferior ();
6392
25e4902b 6393 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
5796c8dc
SS
6394 putpkt ((char *) buf);
6395
6396 /* We just told the target to resume, so a stop reply is in
6397 order. */
6398 rs->waiting_for_stop_reply = 1;
6399 break;
6400 }
6401 /* else fallthrough */
6402 default:
6403 warning (_("Invalid remote reply: %s"), buf);
6404 /* Keep waiting. */
6405 rs->waiting_for_stop_reply = 1;
6406 break;
6407 }
6408
6409 if (status->kind == TARGET_WAITKIND_IGNORE)
6410 {
6411 /* Nothing interesting happened. If we're doing a non-blocking
6412 poll, we're done. Otherwise, go back to waiting. */
6413 if (options & TARGET_WNOHANG)
6414 return minus_one_ptid;
6415 else
6416 goto again;
6417 }
6418 else if (status->kind != TARGET_WAITKIND_EXITED
6419 && status->kind != TARGET_WAITKIND_SIGNALLED)
6420 {
6421 if (!ptid_equal (event_ptid, null_ptid))
25e4902b 6422 record_currthread (rs, event_ptid);
5796c8dc
SS
6423 else
6424 event_ptid = inferior_ptid;
6425 }
6426 else
6427 /* A process exit. Invalidate our notion of current thread. */
25e4902b 6428 record_currthread (rs, minus_one_ptid);
5796c8dc
SS
6429
6430 return event_ptid;
6431}
6432
6433/* Wait until the remote machine stops, then return, storing status in
6434 STATUS just as `wait' would. */
6435
6436static ptid_t
6437remote_wait (struct target_ops *ops,
6438 ptid_t ptid, struct target_waitstatus *status, int options)
6439{
6440 ptid_t event_ptid;
6441
6442 if (non_stop)
6443 event_ptid = remote_wait_ns (ptid, status, options);
6444 else
6445 event_ptid = remote_wait_as (ptid, status, options);
6446
25e4902b 6447 if (target_is_async_p ())
5796c8dc
SS
6448 {
6449 /* If there are are events left in the queue tell the event loop
6450 to return here. */
ef5ccd6c 6451 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5796c8dc
SS
6452 mark_async_event_handler (remote_async_inferior_event_token);
6453 }
6454
6455 return event_ptid;
6456}
6457
6458/* Fetch a single register using a 'p' packet. */
6459
6460static int
6461fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6462{
6463 struct remote_state *rs = get_remote_state ();
6464 char *buf, *p;
6465 char regp[MAX_REGISTER_SIZE];
6466 int i;
6467
25e4902b 6468 if (packet_support (PACKET_p) == PACKET_DISABLE)
5796c8dc
SS
6469 return 0;
6470
6471 if (reg->pnum == -1)
6472 return 0;
6473
6474 p = rs->buf;
6475 *p++ = 'p';
6476 p += hexnumstr (p, reg->pnum);
6477 *p++ = '\0';
6478 putpkt (rs->buf);
6479 getpkt (&rs->buf, &rs->buf_size, 0);
6480
6481 buf = rs->buf;
6482
6483 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6484 {
6485 case PACKET_OK:
6486 break;
6487 case PACKET_UNKNOWN:
6488 return 0;
6489 case PACKET_ERROR:
6490 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6491 gdbarch_register_name (get_regcache_arch (regcache),
6492 reg->regnum),
6493 buf);
6494 }
6495
6496 /* If this register is unfetchable, tell the regcache. */
6497 if (buf[0] == 'x')
6498 {
6499 regcache_raw_supply (regcache, reg->regnum, NULL);
6500 return 1;
6501 }
6502
6503 /* Otherwise, parse and supply the value. */
6504 p = buf;
6505 i = 0;
6506 while (p[0] != 0)
6507 {
6508 if (p[1] == 0)
6509 error (_("fetch_register_using_p: early buf termination"));
6510
6511 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6512 p += 2;
6513 }
6514 regcache_raw_supply (regcache, reg->regnum, regp);
6515 return 1;
6516}
6517
6518/* Fetch the registers included in the target's 'g' packet. */
6519
6520static int
6521send_g_packet (void)
6522{
6523 struct remote_state *rs = get_remote_state ();
6524 int buf_len;
6525
ef5ccd6c 6526 xsnprintf (rs->buf, get_remote_packet_size (), "g");
5796c8dc
SS
6527 remote_send (&rs->buf, &rs->buf_size);
6528
6529 /* We can get out of synch in various cases. If the first character
6530 in the buffer is not a hex character, assume that has happened
6531 and try to fetch another packet to read. */
6532 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6533 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6534 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6535 && rs->buf[0] != 'x') /* New: unavailable register value. */
6536 {
6537 if (remote_debug)
6538 fprintf_unfiltered (gdb_stdlog,
6539 "Bad register packet; fetching a new packet\n");
6540 getpkt (&rs->buf, &rs->buf_size, 0);
6541 }
6542
6543 buf_len = strlen (rs->buf);
6544
6545 /* Sanity check the received packet. */
6546 if (buf_len % 2 != 0)
6547 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6548
6549 return buf_len / 2;
6550}
6551
6552static void
6553process_g_packet (struct regcache *regcache)
6554{
6555 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6556 struct remote_state *rs = get_remote_state ();
6557 struct remote_arch_state *rsa = get_remote_arch_state ();
6558 int i, buf_len;
6559 char *p;
6560 char *regs;
6561
6562 buf_len = strlen (rs->buf);
6563
6564 /* Further sanity checks, with knowledge of the architecture. */
6565 if (buf_len > 2 * rsa->sizeof_g_packet)
6566 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6567
6568 /* Save the size of the packet sent to us by the target. It is used
6569 as a heuristic when determining the max size of packets that the
6570 target can safely receive. */
6571 if (rsa->actual_register_packet_size == 0)
6572 rsa->actual_register_packet_size = buf_len;
6573
6574 /* If this is smaller than we guessed the 'g' packet would be,
6575 update our records. A 'g' reply that doesn't include a register's
6576 value implies either that the register is not available, or that
6577 the 'p' packet must be used. */
6578 if (buf_len < 2 * rsa->sizeof_g_packet)
6579 {
6580 rsa->sizeof_g_packet = buf_len / 2;
6581
6582 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6583 {
6584 if (rsa->regs[i].pnum == -1)
6585 continue;
6586
6587 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6588 rsa->regs[i].in_g_packet = 0;
6589 else
6590 rsa->regs[i].in_g_packet = 1;
6591 }
6592 }
6593
6594 regs = alloca (rsa->sizeof_g_packet);
6595
6596 /* Unimplemented registers read as all bits zero. */
6597 memset (regs, 0, rsa->sizeof_g_packet);
6598
6599 /* Reply describes registers byte by byte, each byte encoded as two
6600 hex characters. Suck them all up, then supply them to the
6601 register cacheing/storage mechanism. */
6602
6603 p = rs->buf;
6604 for (i = 0; i < rsa->sizeof_g_packet; i++)
6605 {
6606 if (p[0] == 0 || p[1] == 0)
6607 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6608 internal_error (__FILE__, __LINE__,
c50c785c 6609 _("unexpected end of 'g' packet reply"));
5796c8dc
SS
6610
6611 if (p[0] == 'x' && p[1] == 'x')
6612 regs[i] = 0; /* 'x' */
6613 else
6614 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6615 p += 2;
6616 }
6617
cf7f2e2d
JM
6618 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6619 {
6620 struct packet_reg *r = &rsa->regs[i];
6621
6622 if (r->in_g_packet)
6623 {
6624 if (r->offset * 2 >= strlen (rs->buf))
6625 /* This shouldn't happen - we adjusted in_g_packet above. */
6626 internal_error (__FILE__, __LINE__,
c50c785c 6627 _("unexpected end of 'g' packet reply"));
cf7f2e2d
JM
6628 else if (rs->buf[r->offset * 2] == 'x')
6629 {
6630 gdb_assert (r->offset * 2 < strlen (rs->buf));
6631 /* The register isn't available, mark it as such (at
6632 the same time setting the value to zero). */
6633 regcache_raw_supply (regcache, r->regnum, NULL);
6634 }
6635 else
6636 regcache_raw_supply (regcache, r->regnum,
6637 regs + r->offset);
6638 }
6639 }
5796c8dc
SS
6640}
6641
6642static void
6643fetch_registers_using_g (struct regcache *regcache)
6644{
6645 send_g_packet ();
6646 process_g_packet (regcache);
6647}
6648
c50c785c
JM
6649/* Make the remote selected traceframe match GDB's selected
6650 traceframe. */
6651
6652static void
6653set_remote_traceframe (void)
6654{
6655 int newnum;
25e4902b 6656 struct remote_state *rs = get_remote_state ();
c50c785c 6657
25e4902b 6658 if (rs->remote_traceframe_number == get_traceframe_number ())
c50c785c
JM
6659 return;
6660
6661 /* Avoid recursion, remote_trace_find calls us again. */
25e4902b 6662 rs->remote_traceframe_number = get_traceframe_number ();
c50c785c
JM
6663
6664 newnum = target_trace_find (tfind_number,
6665 get_traceframe_number (), 0, 0, NULL);
6666
6667 /* Should not happen. If it does, all bets are off. */
6668 if (newnum != get_traceframe_number ())
6669 warning (_("could not set remote traceframe"));
6670}
6671
5796c8dc
SS
6672static void
6673remote_fetch_registers (struct target_ops *ops,
6674 struct regcache *regcache, int regnum)
6675{
6676 struct remote_arch_state *rsa = get_remote_arch_state ();
6677 int i;
6678
c50c785c 6679 set_remote_traceframe ();
5796c8dc
SS
6680 set_general_thread (inferior_ptid);
6681
6682 if (regnum >= 0)
6683 {
6684 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
cf7f2e2d 6685
5796c8dc
SS
6686 gdb_assert (reg != NULL);
6687
6688 /* If this register might be in the 'g' packet, try that first -
6689 we are likely to read more than one register. If this is the
6690 first 'g' packet, we might be overly optimistic about its
6691 contents, so fall back to 'p'. */
6692 if (reg->in_g_packet)
6693 {
6694 fetch_registers_using_g (regcache);
6695 if (reg->in_g_packet)
6696 return;
6697 }
6698
6699 if (fetch_register_using_p (regcache, reg))
6700 return;
6701
6702 /* This register is not available. */
6703 regcache_raw_supply (regcache, reg->regnum, NULL);
6704
6705 return;
6706 }
6707
6708 fetch_registers_using_g (regcache);
6709
6710 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6711 if (!rsa->regs[i].in_g_packet)
6712 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6713 {
6714 /* This register is not available. */
6715 regcache_raw_supply (regcache, i, NULL);
6716 }
6717}
6718
6719/* Prepare to store registers. Since we may send them all (using a
6720 'G' request), we have to read out the ones we don't want to change
6721 first. */
6722
6723static void
25e4902b 6724remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
5796c8dc
SS
6725{
6726 struct remote_arch_state *rsa = get_remote_arch_state ();
6727 int i;
6728 gdb_byte buf[MAX_REGISTER_SIZE];
6729
6730 /* Make sure the entire registers array is valid. */
25e4902b 6731 switch (packet_support (PACKET_P))
5796c8dc
SS
6732 {
6733 case PACKET_DISABLE:
6734 case PACKET_SUPPORT_UNKNOWN:
6735 /* Make sure all the necessary registers are cached. */
6736 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6737 if (rsa->regs[i].in_g_packet)
6738 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6739 break;
6740 case PACKET_ENABLE:
6741 break;
6742 }
6743}
6744
6745/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6746 packet was not recognized. */
6747
6748static int
6749store_register_using_P (const struct regcache *regcache,
6750 struct packet_reg *reg)
6751{
6752 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6753 struct remote_state *rs = get_remote_state ();
6754 /* Try storing a single register. */
6755 char *buf = rs->buf;
6756 gdb_byte regp[MAX_REGISTER_SIZE];
6757 char *p;
6758
25e4902b 6759 if (packet_support (PACKET_P) == PACKET_DISABLE)
5796c8dc
SS
6760 return 0;
6761
6762 if (reg->pnum == -1)
6763 return 0;
6764
6765 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6766 p = buf + strlen (buf);
6767 regcache_raw_collect (regcache, reg->regnum, regp);
6768 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6769 putpkt (rs->buf);
6770 getpkt (&rs->buf, &rs->buf_size, 0);
6771
6772 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6773 {
6774 case PACKET_OK:
6775 return 1;
6776 case PACKET_ERROR:
6777 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6778 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6779 case PACKET_UNKNOWN:
6780 return 0;
6781 default:
6782 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6783 }
6784}
6785
6786/* Store register REGNUM, or all registers if REGNUM == -1, from the
6787 contents of the register cache buffer. FIXME: ignores errors. */
6788
6789static void
6790store_registers_using_G (const struct regcache *regcache)
6791{
6792 struct remote_state *rs = get_remote_state ();
6793 struct remote_arch_state *rsa = get_remote_arch_state ();
6794 gdb_byte *regs;
6795 char *p;
6796
6797 /* Extract all the registers in the regcache copying them into a
6798 local buffer. */
6799 {
6800 int i;
cf7f2e2d 6801
5796c8dc
SS
6802 regs = alloca (rsa->sizeof_g_packet);
6803 memset (regs, 0, rsa->sizeof_g_packet);
6804 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6805 {
6806 struct packet_reg *r = &rsa->regs[i];
cf7f2e2d 6807
5796c8dc
SS
6808 if (r->in_g_packet)
6809 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6810 }
6811 }
6812
6813 /* Command describes registers byte by byte,
6814 each byte encoded as two hex characters. */
6815 p = rs->buf;
6816 *p++ = 'G';
6817 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6818 updated. */
6819 bin2hex (regs, p, rsa->sizeof_g_packet);
6820 putpkt (rs->buf);
6821 getpkt (&rs->buf, &rs->buf_size, 0);
6822 if (packet_check_result (rs->buf) == PACKET_ERROR)
6823 error (_("Could not write registers; remote failure reply '%s'"),
6824 rs->buf);
6825}
6826
6827/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6828 of the register cache buffer. FIXME: ignores errors. */
6829
6830static void
6831remote_store_registers (struct target_ops *ops,
6832 struct regcache *regcache, int regnum)
6833{
6834 struct remote_arch_state *rsa = get_remote_arch_state ();
6835 int i;
6836
c50c785c 6837 set_remote_traceframe ();
5796c8dc
SS
6838 set_general_thread (inferior_ptid);
6839
6840 if (regnum >= 0)
6841 {
6842 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
cf7f2e2d 6843
5796c8dc
SS
6844 gdb_assert (reg != NULL);
6845
6846 /* Always prefer to store registers using the 'P' packet if
6847 possible; we often change only a small number of registers.
6848 Sometimes we change a larger number; we'd need help from a
6849 higher layer to know to use 'G'. */
6850 if (store_register_using_P (regcache, reg))
6851 return;
6852
6853 /* For now, don't complain if we have no way to write the
6854 register. GDB loses track of unavailable registers too
6855 easily. Some day, this may be an error. We don't have
c50c785c 6856 any way to read the register, either... */
5796c8dc
SS
6857 if (!reg->in_g_packet)
6858 return;
6859
6860 store_registers_using_G (regcache);
6861 return;
6862 }
6863
6864 store_registers_using_G (regcache);
6865
6866 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6867 if (!rsa->regs[i].in_g_packet)
6868 if (!store_register_using_P (regcache, &rsa->regs[i]))
6869 /* See above for why we do not issue an error here. */
6870 continue;
6871}
6872\f
6873
6874/* Return the number of hex digits in num. */
6875
6876static int
6877hexnumlen (ULONGEST num)
6878{
6879 int i;
6880
6881 for (i = 0; num != 0; i++)
6882 num >>= 4;
6883
6884 return max (i, 1);
6885}
6886
6887/* Set BUF to the minimum number of hex digits representing NUM. */
6888
6889static int
6890hexnumstr (char *buf, ULONGEST num)
6891{
6892 int len = hexnumlen (num);
cf7f2e2d 6893
5796c8dc
SS
6894 return hexnumnstr (buf, num, len);
6895}
6896
6897
6898/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6899
6900static int
6901hexnumnstr (char *buf, ULONGEST num, int width)
6902{
6903 int i;
6904
6905 buf[width] = '\0';
6906
6907 for (i = width - 1; i >= 0; i--)
6908 {
6909 buf[i] = "0123456789abcdef"[(num & 0xf)];
6910 num >>= 4;
6911 }
6912
6913 return width;
6914}
6915
6916/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6917
6918static CORE_ADDR
6919remote_address_masked (CORE_ADDR addr)
6920{
ef5ccd6c 6921 unsigned int address_size = remote_address_size;
cf7f2e2d 6922
5796c8dc
SS
6923 /* If "remoteaddresssize" was not set, default to target address size. */
6924 if (!address_size)
ef5ccd6c 6925 address_size = gdbarch_addr_bit (target_gdbarch ());
5796c8dc
SS
6926
6927 if (address_size > 0
6928 && address_size < (sizeof (ULONGEST) * 8))
6929 {
6930 /* Only create a mask when that mask can safely be constructed
6931 in a ULONGEST variable. */
6932 ULONGEST mask = 1;
cf7f2e2d 6933
5796c8dc
SS
6934 mask = (mask << address_size) - 1;
6935 addr &= mask;
6936 }
6937 return addr;
6938}
6939
5796c8dc
SS
6940/* Determine whether the remote target supports binary downloading.
6941 This is accomplished by sending a no-op memory write of zero length
6942 to the target at the specified address. It does not suffice to send
6943 the whole packet, since many stubs strip the eighth bit and
6944 subsequently compute a wrong checksum, which causes real havoc with
6945 remote_write_bytes.
6946
6947 NOTE: This can still lose if the serial line is not eight-bit
c50c785c 6948 clean. In cases like this, the user should clear "remote
5796c8dc
SS
6949 X-packet". */
6950
6951static void
6952check_binary_download (CORE_ADDR addr)
6953{
6954 struct remote_state *rs = get_remote_state ();
6955
25e4902b 6956 switch (packet_support (PACKET_X))
5796c8dc
SS
6957 {
6958 case PACKET_DISABLE:
6959 break;
6960 case PACKET_ENABLE:
6961 break;
6962 case PACKET_SUPPORT_UNKNOWN:
6963 {
6964 char *p;
6965
6966 p = rs->buf;
6967 *p++ = 'X';
6968 p += hexnumstr (p, (ULONGEST) addr);
6969 *p++ = ',';
6970 p += hexnumstr (p, (ULONGEST) 0);
6971 *p++ = ':';
6972 *p = '\0';
6973
6974 putpkt_binary (rs->buf, (int) (p - rs->buf));
6975 getpkt (&rs->buf, &rs->buf_size, 0);
6976
6977 if (rs->buf[0] == '\0')
6978 {
6979 if (remote_debug)
6980 fprintf_unfiltered (gdb_stdlog,
c50c785c
JM
6981 "binary downloading NOT "
6982 "supported by target\n");
5796c8dc
SS
6983 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6984 }
6985 else
6986 {
6987 if (remote_debug)
6988 fprintf_unfiltered (gdb_stdlog,
a45ae5f8 6989 "binary downloading supported by target\n");
5796c8dc
SS
6990 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6991 }
6992 break;
6993 }
6994 }
6995}
6996
25e4902b
AHJ
6997/* Helper function to resize the payload in order to try to get a good
6998 alignment. We try to write an amount of data such that the next write will
6999 start on an address aligned on REMOTE_ALIGN_WRITES. */
7000
7001static int
7002align_for_efficient_write (int todo, CORE_ADDR memaddr)
7003{
7004 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7005}
7006
5796c8dc
SS
7007/* Write memory data directly to the remote machine.
7008 This does not inform the data cache; the data cache uses this.
7009 HEADER is the starting part of the packet.
7010 MEMADDR is the address in the remote memory space.
7011 MYADDR is the address of the buffer in our space.
25e4902b
AHJ
7012 LEN_UNITS is the number of addressable units to write.
7013 UNIT_SIZE is the length in bytes of an addressable unit.
5796c8dc
SS
7014 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7015 should send data as binary ('X'), or hex-encoded ('M').
7016
7017 The function creates packet of the form
7018 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7019
25e4902b 7020 where encoding of <DATA> is terminated by PACKET_FORMAT.
5796c8dc
SS
7021
7022 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7023 are omitted.
7024
25e4902b
AHJ
7025 Return the transferred status, error or OK (an
7026 'enum target_xfer_status' value). Save the number of addressable units
7027 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
5796c8dc 7028
25e4902b
AHJ
7029 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7030 exchange between gdb and the stub could look like (?? in place of the
7031 checksum):
7032
7033 -> $m1000,4#??
7034 <- aaaabbbbccccdddd
7035
7036 -> $M1000,3:eeeeffffeeee#??
7037 <- OK
7038
7039 -> $m1000,4#??
7040 <- eeeeffffeeeedddd */
7041
7042static enum target_xfer_status
5796c8dc 7043remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
25e4902b
AHJ
7044 const gdb_byte *myaddr, ULONGEST len_units,
7045 int unit_size, ULONGEST *xfered_len_units,
5796c8dc
SS
7046 char packet_format, int use_length)
7047{
7048 struct remote_state *rs = get_remote_state ();
7049 char *p;
7050 char *plen = NULL;
7051 int plenlen = 0;
25e4902b
AHJ
7052 int todo_units;
7053 int units_written;
7054 int payload_capacity_bytes;
7055 int payload_length_bytes;
5796c8dc
SS
7056
7057 if (packet_format != 'X' && packet_format != 'M')
7058 internal_error (__FILE__, __LINE__,
c50c785c 7059 _("remote_write_bytes_aux: bad packet format"));
5796c8dc 7060
25e4902b
AHJ
7061 if (len_units == 0)
7062 return TARGET_XFER_EOF;
5796c8dc 7063
25e4902b 7064 payload_capacity_bytes = get_memory_write_packet_size ();
5796c8dc
SS
7065
7066 /* The packet buffer will be large enough for the payload;
7067 get_memory_packet_size ensures this. */
7068 rs->buf[0] = '\0';
7069
7070 /* Compute the size of the actual payload by subtracting out the
c50c785c
JM
7071 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7072
25e4902b 7073 payload_capacity_bytes -= strlen ("$,:#NN");
5796c8dc 7074 if (!use_length)
c50c785c 7075 /* The comma won't be used. */
25e4902b
AHJ
7076 payload_capacity_bytes += 1;
7077 payload_capacity_bytes -= strlen (header);
7078 payload_capacity_bytes -= hexnumlen (memaddr);
5796c8dc
SS
7079
7080 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7081
7082 strcat (rs->buf, header);
7083 p = rs->buf + strlen (header);
7084
7085 /* Compute a best guess of the number of bytes actually transfered. */
7086 if (packet_format == 'X')
7087 {
7088 /* Best guess at number of bytes that will fit. */
25e4902b 7089 todo_units = min (len_units, payload_capacity_bytes / unit_size);
5796c8dc 7090 if (use_length)
25e4902b
AHJ
7091 payload_capacity_bytes -= hexnumlen (todo_units);
7092 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
5796c8dc
SS
7093 }
7094 else
7095 {
25e4902b
AHJ
7096 /* Number of bytes that will fit. */
7097 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
5796c8dc 7098 if (use_length)
25e4902b
AHJ
7099 payload_capacity_bytes -= hexnumlen (todo_units);
7100 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
5796c8dc
SS
7101 }
7102
25e4902b 7103 if (todo_units <= 0)
5796c8dc 7104 internal_error (__FILE__, __LINE__,
a45ae5f8 7105 _("minimum packet size too small to write data"));
5796c8dc
SS
7106
7107 /* If we already need another packet, then try to align the end
7108 of this packet to a useful boundary. */
25e4902b
AHJ
7109 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7110 todo_units = align_for_efficient_write (todo_units, memaddr);
5796c8dc
SS
7111
7112 /* Append "<memaddr>". */
7113 memaddr = remote_address_masked (memaddr);
7114 p += hexnumstr (p, (ULONGEST) memaddr);
7115
7116 if (use_length)
7117 {
7118 /* Append ",". */
7119 *p++ = ',';
7120
25e4902b
AHJ
7121 /* Append the length and retain its location and size. It may need to be
7122 adjusted once the packet body has been created. */
5796c8dc 7123 plen = p;
25e4902b 7124 plenlen = hexnumstr (p, (ULONGEST) todo_units);
5796c8dc
SS
7125 p += plenlen;
7126 }
7127
7128 /* Append ":". */
7129 *p++ = ':';
7130 *p = '\0';
7131
7132 /* Append the packet body. */
7133 if (packet_format == 'X')
7134 {
7135 /* Binary mode. Send target system values byte by byte, in
7136 increasing byte addresses. Only escape certain critical
7137 characters. */
25e4902b
AHJ
7138 payload_length_bytes =
7139 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7140 &units_written, payload_capacity_bytes);
5796c8dc 7141
25e4902b 7142 /* If not all TODO units fit, then we'll need another packet. Make
5796c8dc
SS
7143 a second try to keep the end of the packet aligned. Don't do
7144 this if the packet is tiny. */
25e4902b 7145 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
5796c8dc 7146 {
25e4902b
AHJ
7147 int new_todo_units;
7148
7149 new_todo_units = align_for_efficient_write (units_written, memaddr);
7150
7151 if (new_todo_units != units_written)
7152 payload_length_bytes =
7153 remote_escape_output (myaddr, new_todo_units, unit_size,
7154 (gdb_byte *) p, &units_written,
7155 payload_capacity_bytes);
5796c8dc
SS
7156 }
7157
25e4902b
AHJ
7158 p += payload_length_bytes;
7159 if (use_length && units_written < todo_units)
5796c8dc
SS
7160 {
7161 /* Escape chars have filled up the buffer prematurely,
25e4902b 7162 and we have actually sent fewer units than planned.
5796c8dc
SS
7163 Fix-up the length field of the packet. Use the same
7164 number of characters as before. */
25e4902b
AHJ
7165 plen += hexnumnstr (plen, (ULONGEST) units_written,
7166 plenlen);
5796c8dc
SS
7167 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7168 }
7169 }
7170 else
7171 {
7172 /* Normal mode: Send target system values byte by byte, in
7173 increasing byte addresses. Each byte is encoded as a two hex
7174 value. */
25e4902b
AHJ
7175 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7176 units_written = todo_units;
5796c8dc
SS
7177 }
7178
7179 putpkt_binary (rs->buf, (int) (p - rs->buf));
7180 getpkt (&rs->buf, &rs->buf_size, 0);
7181
7182 if (rs->buf[0] == 'E')
25e4902b 7183 return TARGET_XFER_E_IO;
5796c8dc 7184
25e4902b
AHJ
7185 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7186 send fewer units than we'd planned. */
7187 *xfered_len_units = (ULONGEST) units_written;
7188 return TARGET_XFER_OK;
5796c8dc
SS
7189}
7190
7191/* Write memory data directly to the remote machine.
7192 This does not inform the data cache; the data cache uses this.
7193 MEMADDR is the address in the remote memory space.
7194 MYADDR is the address of the buffer in our space.
7195 LEN is the number of bytes.
7196
25e4902b
AHJ
7197 Return the transferred status, error or OK (an
7198 'enum target_xfer_status' value). Save the number of bytes
7199 transferred in *XFERED_LEN. Only transfer a single packet. */
5796c8dc 7200
25e4902b
AHJ
7201static enum target_xfer_status
7202remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7203 int unit_size, ULONGEST *xfered_len)
5796c8dc
SS
7204{
7205 char *packet_format = 0;
7206
7207 /* Check whether the target supports binary download. */
7208 check_binary_download (memaddr);
7209
25e4902b 7210 switch (packet_support (PACKET_X))
5796c8dc
SS
7211 {
7212 case PACKET_ENABLE:
7213 packet_format = "X";
7214 break;
7215 case PACKET_DISABLE:
7216 packet_format = "M";
7217 break;
7218 case PACKET_SUPPORT_UNKNOWN:
7219 internal_error (__FILE__, __LINE__,
7220 _("remote_write_bytes: bad internal state"));
7221 default:
7222 internal_error (__FILE__, __LINE__, _("bad switch"));
7223 }
7224
7225 return remote_write_bytes_aux (packet_format,
25e4902b
AHJ
7226 memaddr, myaddr, len, unit_size, xfered_len,
7227 packet_format[0], 1);
5796c8dc
SS
7228}
7229
7230/* Read memory data directly from the remote machine.
7231 This does not use the data cache; the data cache uses this.
7232 MEMADDR is the address in the remote memory space.
7233 MYADDR is the address of the buffer in our space.
25e4902b
AHJ
7234 LEN_UNITS is the number of addressable memory units to read..
7235 UNIT_SIZE is the length in bytes of an addressable unit.
5796c8dc 7236
25e4902b
AHJ
7237 Return the transferred status, error or OK (an
7238 'enum target_xfer_status' value). Save the number of bytes
7239 transferred in *XFERED_LEN_UNITS.
5796c8dc 7240
25e4902b
AHJ
7241 See the comment of remote_write_bytes_aux for an example of
7242 memory read/write exchange between gdb and the stub. */
7243
7244static enum target_xfer_status
7245remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7246 int unit_size, ULONGEST *xfered_len_units)
5796c8dc
SS
7247{
7248 struct remote_state *rs = get_remote_state ();
25e4902b 7249 int buf_size_bytes; /* Max size of packet output buffer. */
c50c785c 7250 char *p;
25e4902b
AHJ
7251 int todo_units;
7252 int decoded_bytes;
5796c8dc 7253
25e4902b 7254 buf_size_bytes = get_memory_read_packet_size ();
5796c8dc
SS
7255 /* The packet buffer will be large enough for the payload;
7256 get_memory_packet_size ensures this. */
7257
25e4902b
AHJ
7258 /* Number of units that will fit. */
7259 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
5796c8dc 7260
c50c785c
JM
7261 /* Construct "m"<memaddr>","<len>". */
7262 memaddr = remote_address_masked (memaddr);
7263 p = rs->buf;
7264 *p++ = 'm';
7265 p += hexnumstr (p, (ULONGEST) memaddr);
7266 *p++ = ',';
25e4902b 7267 p += hexnumstr (p, (ULONGEST) todo_units);
c50c785c
JM
7268 *p = '\0';
7269 putpkt (rs->buf);
7270 getpkt (&rs->buf, &rs->buf_size, 0);
7271 if (rs->buf[0] == 'E'
7272 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7273 && rs->buf[3] == '\0')
25e4902b 7274 return TARGET_XFER_E_IO;
c50c785c
JM
7275 /* Reply describes memory byte by byte, each byte encoded as two hex
7276 characters. */
7277 p = rs->buf;
25e4902b 7278 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
c50c785c 7279 /* Return what we have. Let higher layers handle partial reads. */
25e4902b
AHJ
7280 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7281 return TARGET_XFER_OK;
5796c8dc 7282}
5796c8dc 7283
25e4902b
AHJ
7284/* Using the set of read-only target sections of remote, read live
7285 read-only memory.
5796c8dc 7286
25e4902b
AHJ
7287 For interface/parameters/return description see target.h,
7288 to_xfer_partial. */
7289
7290static enum target_xfer_status
7291remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7292 ULONGEST memaddr, ULONGEST len,
7293 int unit_size, ULONGEST *xfered_len)
5796c8dc 7294{
25e4902b
AHJ
7295 struct target_section *secp;
7296 struct target_section_table *table;
5796c8dc 7297
25e4902b
AHJ
7298 secp = target_section_by_addr (ops, memaddr);
7299 if (secp != NULL
7300 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7301 secp->the_bfd_section)
7302 & SEC_READONLY))
7303 {
7304 struct target_section *p;
7305 ULONGEST memend = memaddr + len;
5796c8dc 7306
25e4902b
AHJ
7307 table = target_get_section_table (ops);
7308
7309 for (p = table->sections; p < table->sections_end; p++)
7310 {
7311 if (memaddr >= p->addr)
7312 {
7313 if (memend <= p->endaddr)
7314 {
7315 /* Entire transfer is within this section. */
7316 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7317 xfered_len);
7318 }
7319 else if (memaddr >= p->endaddr)
7320 {
7321 /* This section ends before the transfer starts. */
7322 continue;
7323 }
7324 else
7325 {
7326 /* This section overlaps the transfer. Just do half. */
7327 len = p->endaddr - memaddr;
7328 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7329 xfered_len);
7330 }
7331 }
7332 }
7333 }
7334
7335 return TARGET_XFER_EOF;
7336}
7337
7338/* Similar to remote_read_bytes_1, but it reads from the remote stub
7339 first if the requested memory is unavailable in traceframe.
7340 Otherwise, fall back to remote_read_bytes_1. */
7341
7342static enum target_xfer_status
7343remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7344 gdb_byte *myaddr, ULONGEST len, int unit_size,
7345 ULONGEST *xfered_len)
7346{
7347 if (len == 0)
7348 return TARGET_XFER_EOF;
5796c8dc 7349
25e4902b
AHJ
7350 if (get_traceframe_number () != -1)
7351 {
7352 VEC(mem_range_s) *available;
7353
7354 /* If we fail to get the set of available memory, then the
7355 target does not support querying traceframe info, and so we
7356 attempt reading from the traceframe anyway (assuming the
7357 target implements the old QTro packet then). */
7358 if (traceframe_available_memory (&available, memaddr, len))
7359 {
7360 struct cleanup *old_chain;
7361
7362 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7363
7364 if (VEC_empty (mem_range_s, available)
7365 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7366 {
7367 enum target_xfer_status res;
7368
7369 /* Don't read into the traceframe's available
7370 memory. */
7371 if (!VEC_empty (mem_range_s, available))
7372 {
7373 LONGEST oldlen = len;
7374
7375 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7376 gdb_assert (len <= oldlen);
7377 }
7378
7379 do_cleanups (old_chain);
7380
7381 /* This goes through the topmost target again. */
7382 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7383 len, unit_size, xfered_len);
7384 if (res == TARGET_XFER_OK)
7385 return TARGET_XFER_OK;
7386 else
7387 {
7388 /* No use trying further, we know some memory starting
7389 at MEMADDR isn't available. */
7390 *xfered_len = len;
7391 return TARGET_XFER_UNAVAILABLE;
7392 }
7393 }
7394
7395 /* Don't try to read more than how much is available, in
7396 case the target implements the deprecated QTro packet to
7397 cater for older GDBs (the target's knowledge of read-only
7398 sections may be outdated by now). */
7399 len = VEC_index (mem_range_s, available, 0)->length;
7400
7401 do_cleanups (old_chain);
7402 }
7403 }
7404
7405 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
5796c8dc
SS
7406}
7407
25e4902b
AHJ
7408\f
7409
5796c8dc
SS
7410/* Sends a packet with content determined by the printf format string
7411 FORMAT and the remaining arguments, then gets the reply. Returns
7412 whether the packet was a success, a failure, or unknown. */
7413
25e4902b
AHJ
7414static enum packet_result remote_send_printf (const char *format, ...)
7415 ATTRIBUTE_PRINTF (1, 2);
7416
5796c8dc
SS
7417static enum packet_result
7418remote_send_printf (const char *format, ...)
7419{
7420 struct remote_state *rs = get_remote_state ();
7421 int max_size = get_remote_packet_size ();
5796c8dc 7422 va_list ap;
cf7f2e2d 7423
5796c8dc
SS
7424 va_start (ap, format);
7425
7426 rs->buf[0] = '\0';
7427 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
c50c785c 7428 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
5796c8dc
SS
7429
7430 if (putpkt (rs->buf) < 0)
7431 error (_("Communication problem with target."));
7432
7433 rs->buf[0] = '\0';
7434 getpkt (&rs->buf, &rs->buf_size, 0);
7435
7436 return packet_check_result (rs->buf);
7437}
7438
7439static void
7440restore_remote_timeout (void *p)
7441{
7442 int value = *(int *)p;
cf7f2e2d 7443
5796c8dc
SS
7444 remote_timeout = value;
7445}
7446
7447/* Flash writing can take quite some time. We'll set
7448 effectively infinite timeout for flash operations.
7449 In future, we'll need to decide on a better approach. */
7450static const int remote_flash_timeout = 1000;
7451
7452static void
7453remote_flash_erase (struct target_ops *ops,
7454 ULONGEST address, LONGEST length)
7455{
ef5ccd6c 7456 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5796c8dc
SS
7457 int saved_remote_timeout = remote_timeout;
7458 enum packet_result ret;
5796c8dc
SS
7459 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7460 &saved_remote_timeout);
cf7f2e2d 7461
5796c8dc
SS
7462 remote_timeout = remote_flash_timeout;
7463
7464 ret = remote_send_printf ("vFlashErase:%s,%s",
7465 phex (address, addr_size),
7466 phex (length, 4));
7467 switch (ret)
7468 {
7469 case PACKET_UNKNOWN:
7470 error (_("Remote target does not support flash erase"));
7471 case PACKET_ERROR:
7472 error (_("Error erasing flash with vFlashErase packet"));
7473 default:
7474 break;
7475 }
7476
7477 do_cleanups (back_to);
7478}
7479
25e4902b
AHJ
7480static enum target_xfer_status
7481remote_flash_write (struct target_ops *ops, ULONGEST address,
7482 ULONGEST length, ULONGEST *xfered_len,
7483 const gdb_byte *data)
5796c8dc
SS
7484{
7485 int saved_remote_timeout = remote_timeout;
25e4902b 7486 enum target_xfer_status ret;
5796c8dc 7487 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
25e4902b 7488 &saved_remote_timeout);
5796c8dc
SS
7489
7490 remote_timeout = remote_flash_timeout;
25e4902b
AHJ
7491 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7492 xfered_len,'X', 0);
5796c8dc
SS
7493 do_cleanups (back_to);
7494
7495 return ret;
7496}
7497
7498static void
7499remote_flash_done (struct target_ops *ops)
7500{
7501 int saved_remote_timeout = remote_timeout;
7502 int ret;
7503 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7504 &saved_remote_timeout);
7505
7506 remote_timeout = remote_flash_timeout;
7507 ret = remote_send_printf ("vFlashDone");
7508 do_cleanups (back_to);
7509
7510 switch (ret)
7511 {
7512 case PACKET_UNKNOWN:
7513 error (_("Remote target does not support vFlashDone"));
7514 case PACKET_ERROR:
7515 error (_("Error finishing flash operation"));
7516 default:
7517 break;
7518 }
7519}
7520
7521static void
7522remote_files_info (struct target_ops *ignore)
7523{
7524 puts_filtered ("Debugging a target over a serial line.\n");
7525}
7526\f
7527/* Stuff for dealing with the packets which are part of this protocol.
7528 See comment at top of file for details. */
7529
25e4902b
AHJ
7530/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7531 error to higher layers. Called when a serial error is detected.
7532 The exception message is STRING, followed by a colon and a blank,
7533 the system error message for errno at function entry and final dot
7534 for output compatibility with throw_perror_with_name. */
7535
7536static void
7537unpush_and_perror (const char *string)
7538{
7539 int saved_errno = errno;
7540
7541 remote_unpush_target ();
7542 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7543 safe_strerror (saved_errno));
7544}
7545
5796c8dc
SS
7546/* Read a single character from the remote end. */
7547
7548static int
7549readchar (int timeout)
7550{
7551 int ch;
25e4902b 7552 struct remote_state *rs = get_remote_state ();
5796c8dc 7553
25e4902b 7554 ch = serial_readchar (rs->remote_desc, timeout);
5796c8dc
SS
7555
7556 if (ch >= 0)
7557 return ch;
7558
7559 switch ((enum serial_rc) ch)
7560 {
7561 case SERIAL_EOF:
ef5ccd6c
JM
7562 remote_unpush_target ();
7563 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
5796c8dc
SS
7564 /* no return */
7565 case SERIAL_ERROR:
25e4902b
AHJ
7566 unpush_and_perror (_("Remote communication error. "
7567 "Target disconnected."));
5796c8dc
SS
7568 /* no return */
7569 case SERIAL_TIMEOUT:
7570 break;
7571 }
7572 return ch;
7573}
7574
ef5ccd6c
JM
7575/* Wrapper for serial_write that closes the target and throws if
7576 writing fails. */
7577
7578static void
7579remote_serial_write (const char *str, int len)
7580{
25e4902b
AHJ
7581 struct remote_state *rs = get_remote_state ();
7582
7583 if (serial_write (rs->remote_desc, str, len))
ef5ccd6c 7584 {
25e4902b
AHJ
7585 unpush_and_perror (_("Remote communication error. "
7586 "Target disconnected."));
ef5ccd6c
JM
7587 }
7588}
7589
5796c8dc
SS
7590/* Send the command in *BUF to the remote machine, and read the reply
7591 into *BUF. Report an error if we get an error reply. Resize
7592 *BUF using xrealloc if necessary to hold the result, and update
7593 *SIZEOF_BUF. */
7594
7595static void
7596remote_send (char **buf,
7597 long *sizeof_buf)
7598{
7599 putpkt (*buf);
7600 getpkt (buf, sizeof_buf, 0);
7601
7602 if ((*buf)[0] == 'E')
7603 error (_("Remote failure reply: %s"), *buf);
7604}
7605
7606/* Return a pointer to an xmalloc'ed string representing an escaped
7607 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7608 etc. The caller is responsible for releasing the returned
7609 memory. */
7610
7611static char *
7612escape_buffer (const char *buf, int n)
7613{
7614 struct cleanup *old_chain;
7615 struct ui_file *stb;
7616 char *str;
7617
7618 stb = mem_fileopen ();
7619 old_chain = make_cleanup_ui_file_delete (stb);
7620
25e4902b 7621 fputstrn_unfiltered (buf, n, '\\', stb);
5796c8dc
SS
7622 str = ui_file_xstrdup (stb, NULL);
7623 do_cleanups (old_chain);
7624 return str;
7625}
7626
7627/* Display a null-terminated packet on stdout, for debugging, using C
7628 string notation. */
7629
7630static void
25e4902b 7631print_packet (const char *buf)
5796c8dc
SS
7632{
7633 puts_filtered ("\"");
7634 fputstr_filtered (buf, '"', gdb_stdout);
7635 puts_filtered ("\"");
7636}
7637
7638int
25e4902b 7639putpkt (const char *buf)
5796c8dc
SS
7640{
7641 return putpkt_binary (buf, strlen (buf));
7642}
7643
7644/* Send a packet to the remote machine, with error checking. The data
7645 of the packet is in BUF. The string in BUF can be at most
7646 get_remote_packet_size () - 5 to account for the $, # and checksum,
7647 and for a possible /0 if we are debugging (remote_debug) and want
7648 to print the sent packet as a string. */
7649
7650static int
25e4902b 7651putpkt_binary (const char *buf, int cnt)
5796c8dc
SS
7652{
7653 struct remote_state *rs = get_remote_state ();
7654 int i;
7655 unsigned char csum = 0;
7656 char *buf2 = alloca (cnt + 6);
7657
7658 int ch;
7659 int tcount = 0;
7660 char *p;
ef5ccd6c 7661 char *message;
5796c8dc
SS
7662
7663 /* Catch cases like trying to read memory or listing threads while
7664 we're waiting for a stop reply. The remote server wouldn't be
7665 ready to handle this request, so we'd hang and timeout. We don't
7666 have to worry about this in synchronous mode, because in that
7667 case it's not possible to issue a command while the target is
7668 running. This is not a problem in non-stop mode, because in that
7669 case, the stub is always ready to process serial input. */
25e4902b
AHJ
7670 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7671 {
7672 error (_("Cannot execute this command while the target is running.\n"
7673 "Use the \"interrupt\" command to stop the target\n"
7674 "and then try again."));
7675 }
5796c8dc
SS
7676
7677 /* We're sending out a new packet. Make sure we don't look at a
7678 stale cached response. */
7679 rs->cached_wait_status = 0;
7680
7681 /* Copy the packet into buffer BUF2, encapsulating it
7682 and giving it a checksum. */
7683
7684 p = buf2;
7685 *p++ = '$';
7686
7687 for (i = 0; i < cnt; i++)
7688 {
7689 csum += buf[i];
7690 *p++ = buf[i];
7691 }
7692 *p++ = '#';
7693 *p++ = tohex ((csum >> 4) & 0xf);
7694 *p++ = tohex (csum & 0xf);
7695
7696 /* Send it over and over until we get a positive ack. */
7697
7698 while (1)
7699 {
7700 int started_error_output = 0;
7701
7702 if (remote_debug)
7703 {
7704 struct cleanup *old_chain;
7705 char *str;
7706
7707 *p = '\0';
7708 str = escape_buffer (buf2, p - buf2);
7709 old_chain = make_cleanup (xfree, str);
7710 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7711 gdb_flush (gdb_stdlog);
7712 do_cleanups (old_chain);
7713 }
ef5ccd6c 7714 remote_serial_write (buf2, p - buf2);
5796c8dc
SS
7715
7716 /* If this is a no acks version of the remote protocol, send the
7717 packet and move on. */
7718 if (rs->noack_mode)
7719 break;
7720
7721 /* Read until either a timeout occurs (-2) or '+' is read.
7722 Handle any notification that arrives in the mean time. */
7723 while (1)
7724 {
7725 ch = readchar (remote_timeout);
7726
7727 if (remote_debug)
7728 {
7729 switch (ch)
7730 {
7731 case '+':
7732 case '-':
7733 case SERIAL_TIMEOUT:
7734 case '$':
7735 case '%':
7736 if (started_error_output)
7737 {
7738 putchar_unfiltered ('\n');
7739 started_error_output = 0;
7740 }
7741 }
7742 }
7743
7744 switch (ch)
7745 {
7746 case '+':
7747 if (remote_debug)
7748 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7749 return 1;
7750 case '-':
7751 if (remote_debug)
7752 fprintf_unfiltered (gdb_stdlog, "Nak\n");
c50c785c 7753 /* FALLTHROUGH */
5796c8dc
SS
7754 case SERIAL_TIMEOUT:
7755 tcount++;
7756 if (tcount > 3)
7757 return 0;
7758 break; /* Retransmit buffer. */
7759 case '$':
7760 {
7761 if (remote_debug)
7762 fprintf_unfiltered (gdb_stdlog,
7763 "Packet instead of Ack, ignoring it\n");
7764 /* It's probably an old response sent because an ACK
7765 was lost. Gobble up the packet and ack it so it
7766 doesn't get retransmitted when we resend this
7767 packet. */
7768 skip_frame ();
ef5ccd6c 7769 remote_serial_write ("+", 1);
5796c8dc
SS
7770 continue; /* Now, go look for +. */
7771 }
7772
7773 case '%':
7774 {
7775 int val;
7776
7777 /* If we got a notification, handle it, and go back to looking
7778 for an ack. */
7779 /* We've found the start of a notification. Now
7780 collect the data. */
7781 val = read_frame (&rs->buf, &rs->buf_size);
7782 if (val >= 0)
7783 {
7784 if (remote_debug)
7785 {
7786 struct cleanup *old_chain;
7787 char *str;
7788
7789 str = escape_buffer (rs->buf, val);
7790 old_chain = make_cleanup (xfree, str);
7791 fprintf_unfiltered (gdb_stdlog,
7792 " Notification received: %s\n",
7793 str);
7794 do_cleanups (old_chain);
7795 }
25e4902b 7796 handle_notification (rs->notif_state, rs->buf);
5796c8dc
SS
7797 /* We're in sync now, rewait for the ack. */
7798 tcount = 0;
7799 }
7800 else
7801 {
7802 if (remote_debug)
7803 {
7804 if (!started_error_output)
7805 {
7806 started_error_output = 1;
7807 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7808 }
7809 fputc_unfiltered (ch & 0177, gdb_stdlog);
7810 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7811 }
7812 }
7813 continue;
7814 }
7815 /* fall-through */
7816 default:
7817 if (remote_debug)
7818 {
7819 if (!started_error_output)
7820 {
7821 started_error_output = 1;
7822 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7823 }
7824 fputc_unfiltered (ch & 0177, gdb_stdlog);
7825 }
7826 continue;
7827 }
7828 break; /* Here to retransmit. */
7829 }
7830
7831#if 0
7832 /* This is wrong. If doing a long backtrace, the user should be
7833 able to get out next time we call QUIT, without anything as
7834 violent as interrupt_query. If we want to provide a way out of
7835 here without getting to the next QUIT, it should be based on
7836 hitting ^C twice as in remote_wait. */
7837 if (quit_flag)
7838 {
7839 quit_flag = 0;
7840 interrupt_query ();
7841 }
7842#endif
7843 }
7844 return 0;
7845}
7846
7847/* Come here after finding the start of a frame when we expected an
7848 ack. Do our best to discard the rest of this packet. */
7849
7850static void
7851skip_frame (void)
7852{
7853 int c;
7854
7855 while (1)
7856 {
7857 c = readchar (remote_timeout);
7858 switch (c)
7859 {
7860 case SERIAL_TIMEOUT:
7861 /* Nothing we can do. */
7862 return;
7863 case '#':
7864 /* Discard the two bytes of checksum and stop. */
7865 c = readchar (remote_timeout);
7866 if (c >= 0)
7867 c = readchar (remote_timeout);
7868
7869 return;
7870 case '*': /* Run length encoding. */
7871 /* Discard the repeat count. */
7872 c = readchar (remote_timeout);
7873 if (c < 0)
7874 return;
7875 break;
7876 default:
7877 /* A regular character. */
7878 break;
7879 }
7880 }
7881}
7882
7883/* Come here after finding the start of the frame. Collect the rest
7884 into *BUF, verifying the checksum, length, and handling run-length
7885 compression. NUL terminate the buffer. If there is not enough room,
7886 expand *BUF using xrealloc.
7887
7888 Returns -1 on error, number of characters in buffer (ignoring the
7889 trailing NULL) on success. (could be extended to return one of the
7890 SERIAL status indications). */
7891
7892static long
7893read_frame (char **buf_p,
7894 long *sizeof_buf)
7895{
7896 unsigned char csum;
7897 long bc;
7898 int c;
7899 char *buf = *buf_p;
7900 struct remote_state *rs = get_remote_state ();
7901
7902 csum = 0;
7903 bc = 0;
7904
7905 while (1)
7906 {
7907 c = readchar (remote_timeout);
7908 switch (c)
7909 {
7910 case SERIAL_TIMEOUT:
7911 if (remote_debug)
7912 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7913 return -1;
7914 case '$':
7915 if (remote_debug)
7916 fputs_filtered ("Saw new packet start in middle of old one\n",
7917 gdb_stdlog);
7918 return -1; /* Start a new packet, count retries. */
7919 case '#':
7920 {
7921 unsigned char pktcsum;
7922 int check_0 = 0;
7923 int check_1 = 0;
7924
7925 buf[bc] = '\0';
7926
7927 check_0 = readchar (remote_timeout);
7928 if (check_0 >= 0)
7929 check_1 = readchar (remote_timeout);
7930
7931 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7932 {
7933 if (remote_debug)
7934 fputs_filtered ("Timeout in checksum, retrying\n",
7935 gdb_stdlog);
7936 return -1;
7937 }
7938 else if (check_0 < 0 || check_1 < 0)
7939 {
7940 if (remote_debug)
7941 fputs_filtered ("Communication error in checksum\n",
7942 gdb_stdlog);
7943 return -1;
7944 }
7945
7946 /* Don't recompute the checksum; with no ack packets we
7947 don't have any way to indicate a packet retransmission
7948 is necessary. */
7949 if (rs->noack_mode)
7950 return bc;
7951
7952 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7953 if (csum == pktcsum)
7954 return bc;
7955
7956 if (remote_debug)
7957 {
7958 struct cleanup *old_chain;
7959 char *str;
7960
7961 str = escape_buffer (buf, bc);
7962 old_chain = make_cleanup (xfree, str);
7963 fprintf_unfiltered (gdb_stdlog,
c50c785c
JM
7964 "Bad checksum, sentsum=0x%x, "
7965 "csum=0x%x, buf=%s\n",
5796c8dc
SS
7966 pktcsum, csum, str);
7967 do_cleanups (old_chain);
7968 }
7969 /* Number of characters in buffer ignoring trailing
7970 NULL. */
7971 return -1;
7972 }
7973 case '*': /* Run length encoding. */
7974 {
7975 int repeat;
5796c8dc 7976
cf7f2e2d 7977 csum += c;
5796c8dc
SS
7978 c = readchar (remote_timeout);
7979 csum += c;
7980 repeat = c - ' ' + 3; /* Compute repeat count. */
7981
7982 /* The character before ``*'' is repeated. */
7983
7984 if (repeat > 0 && repeat <= 255 && bc > 0)
7985 {
7986 if (bc + repeat - 1 >= *sizeof_buf - 1)
7987 {
7988 /* Make some more room in the buffer. */
7989 *sizeof_buf += repeat;
7990 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7991 buf = *buf_p;
7992 }
7993
7994 memset (&buf[bc], buf[bc - 1], repeat);
7995 bc += repeat;
7996 continue;
7997 }
7998
7999 buf[bc] = '\0';
8000 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8001 return -1;
8002 }
8003 default:
8004 if (bc >= *sizeof_buf - 1)
8005 {
8006 /* Make some more room in the buffer. */
8007 *sizeof_buf *= 2;
8008 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8009 buf = *buf_p;
8010 }
8011
8012 buf[bc++] = c;
8013 csum += c;
8014 continue;
8015 }
8016 }
8017}
8018
8019/* Read a packet from the remote machine, with error checking, and
8020 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8021 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8022 rather than timing out; this is used (in synchronous mode) to wait
8023 for a target that is is executing user code to stop. */
8024/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8025 don't have to change all the calls to getpkt to deal with the
8026 return value, because at the moment I don't know what the right
8027 thing to do it for those. */
8028void
8029getpkt (char **buf,
8030 long *sizeof_buf,
8031 int forever)
8032{
8033 int timed_out;
8034
8035 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8036}
8037
8038
8039/* Read a packet from the remote machine, with error checking, and
8040 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8041 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8042 rather than timing out; this is used (in synchronous mode) to wait
8043 for a target that is is executing user code to stop. If FOREVER ==
8044 0, this function is allowed to time out gracefully and return an
8045 indication of this to the caller. Otherwise return the number of
8046 bytes read. If EXPECTING_NOTIF, consider receiving a notification
ef5ccd6c
JM
8047 enough reason to return to the caller. *IS_NOTIF is an output
8048 boolean that indicates whether *BUF holds a notification or not
8049 (a regular packet). */
5796c8dc
SS
8050
8051static int
8052getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
ef5ccd6c 8053 int expecting_notif, int *is_notif)
5796c8dc
SS
8054{
8055 struct remote_state *rs = get_remote_state ();
8056 int c;
8057 int tries;
8058 int timeout;
8059 int val = -1;
8060
8061 /* We're reading a new response. Make sure we don't look at a
8062 previously cached response. */
8063 rs->cached_wait_status = 0;
8064
8065 strcpy (*buf, "timeout");
8066
8067 if (forever)
8068 timeout = watchdog > 0 ? watchdog : -1;
8069 else if (expecting_notif)
8070 timeout = 0; /* There should already be a char in the buffer. If
8071 not, bail out. */
8072 else
8073 timeout = remote_timeout;
8074
8075#define MAX_TRIES 3
8076
8077 /* Process any number of notifications, and then return when
8078 we get a packet. */
8079 for (;;)
8080 {
25e4902b 8081 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
5796c8dc
SS
8082 times. */
8083 for (tries = 1; tries <= MAX_TRIES; tries++)
8084 {
8085 /* This can loop forever if the remote side sends us
8086 characters continuously, but if it pauses, we'll get
8087 SERIAL_TIMEOUT from readchar because of timeout. Then
8088 we'll count that as a retry.
8089
8090 Note that even when forever is set, we will only wait
8091 forever prior to the start of a packet. After that, we
8092 expect characters to arrive at a brisk pace. They should
8093 show up within remote_timeout intervals. */
8094 do
8095 c = readchar (timeout);
8096 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8097
8098 if (c == SERIAL_TIMEOUT)
8099 {
8100 if (expecting_notif)
8101 return -1; /* Don't complain, it's normal to not get
8102 anything in this case. */
8103
8104 if (forever) /* Watchdog went off? Kill the target. */
8105 {
8106 QUIT;
ef5ccd6c
JM
8107 remote_unpush_target ();
8108 throw_error (TARGET_CLOSE_ERROR,
8109 _("Watchdog timeout has expired. "
8110 "Target detached."));
5796c8dc
SS
8111 }
8112 if (remote_debug)
8113 fputs_filtered ("Timed out.\n", gdb_stdlog);
8114 }
8115 else
8116 {
8117 /* We've found the start of a packet or notification.
8118 Now collect the data. */
8119 val = read_frame (buf, sizeof_buf);
8120 if (val >= 0)
8121 break;
8122 }
8123
ef5ccd6c 8124 remote_serial_write ("-", 1);
5796c8dc
SS
8125 }
8126
8127 if (tries > MAX_TRIES)
8128 {
8129 /* We have tried hard enough, and just can't receive the
8130 packet/notification. Give up. */
8131 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8132
8133 /* Skip the ack char if we're in no-ack mode. */
8134 if (!rs->noack_mode)
ef5ccd6c 8135 remote_serial_write ("+", 1);
5796c8dc
SS
8136 return -1;
8137 }
8138
8139 /* If we got an ordinary packet, return that to our caller. */
8140 if (c == '$')
8141 {
8142 if (remote_debug)
8143 {
8144 struct cleanup *old_chain;
8145 char *str;
8146
8147 str = escape_buffer (*buf, val);
8148 old_chain = make_cleanup (xfree, str);
8149 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8150 do_cleanups (old_chain);
8151 }
8152
8153 /* Skip the ack char if we're in no-ack mode. */
8154 if (!rs->noack_mode)
ef5ccd6c
JM
8155 remote_serial_write ("+", 1);
8156 if (is_notif != NULL)
8157 *is_notif = 0;
5796c8dc
SS
8158 return val;
8159 }
8160
8161 /* If we got a notification, handle it, and go back to looking
8162 for a packet. */
8163 else
8164 {
8165 gdb_assert (c == '%');
8166
8167 if (remote_debug)
8168 {
8169 struct cleanup *old_chain;
8170 char *str;
8171
8172 str = escape_buffer (*buf, val);
8173 old_chain = make_cleanup (xfree, str);
8174 fprintf_unfiltered (gdb_stdlog,
8175 " Notification received: %s\n",
8176 str);
8177 do_cleanups (old_chain);
8178 }
ef5ccd6c
JM
8179 if (is_notif != NULL)
8180 *is_notif = 1;
5796c8dc 8181
25e4902b 8182 handle_notification (rs->notif_state, *buf);
5796c8dc
SS
8183
8184 /* Notifications require no acknowledgement. */
8185
8186 if (expecting_notif)
ef5ccd6c 8187 return val;
5796c8dc
SS
8188 }
8189 }
8190}
8191
8192static int
8193getpkt_sane (char **buf, long *sizeof_buf, int forever)
8194{
ef5ccd6c 8195 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
5796c8dc
SS
8196}
8197
8198static int
ef5ccd6c
JM
8199getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8200 int *is_notif)
5796c8dc 8201{
ef5ccd6c
JM
8202 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8203 is_notif);
5796c8dc
SS
8204}
8205
25e4902b
AHJ
8206/* Check whether EVENT is a fork event for the process specified
8207 by the pid passed in DATA, and if it is, kill the fork child. */
a45ae5f8
JM
8208
8209static int
25e4902b
AHJ
8210kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8211 QUEUE_ITER (stop_reply_p) *iter,
8212 stop_reply_p event,
8213 void *data)
8214{
8215 struct queue_iter_param *param = data;
8216 int parent_pid = *(int *) param->input;
8217
8218 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8219 {
8220 struct remote_state *rs = get_remote_state ();
8221 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8222 int res;
8223
8224 res = remote_vkill (child_pid, rs);
8225 if (res != 0)
8226 error (_("Can't kill fork child process %d"), child_pid);
8227 }
8228
8229 return 1;
8230}
8231
8232/* Kill any new fork children of process PID that haven't been
8233 processed by follow_fork. */
8234
8235static void
8236kill_new_fork_children (int pid, struct remote_state *rs)
a45ae5f8 8237{
25e4902b
AHJ
8238 struct thread_info *thread;
8239 struct notif_client *notif = &notif_client_stop;
8240 struct queue_iter_param param;
8241
8242 /* Kill the fork child threads of any threads in process PID
8243 that are stopped at a fork event. */
8244 ALL_NON_EXITED_THREADS (thread)
8245 {
8246 struct target_waitstatus *ws = &thread->pending_follow;
8247
8248 if (is_pending_fork_parent (ws, pid, thread->ptid))
8249 {
8250 struct remote_state *rs = get_remote_state ();
8251 int child_pid = ptid_get_pid (ws->value.related_pid);
8252 int res;
8253
8254 res = remote_vkill (child_pid, rs);
8255 if (res != 0)
8256 error (_("Can't kill fork child process %d"), child_pid);
8257 }
8258 }
8259
8260 /* Check for any pending fork events (not reported or processed yet)
8261 in process PID and kill those fork child threads as well. */
8262 remote_notif_get_pending_events (notif);
8263 param.input = &pid;
8264 param.output = NULL;
8265 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8266 kill_child_of_pending_fork, &param);
a45ae5f8
JM
8267}
8268
25e4902b 8269\f
5796c8dc
SS
8270static void
8271remote_kill (struct target_ops *ops)
8272{
25e4902b
AHJ
8273
8274 /* Catch errors so the user can quit from gdb even when we
5796c8dc 8275 aren't on speaking terms with the remote system. */
25e4902b
AHJ
8276 TRY
8277 {
8278 putpkt ("k");
8279 }
8280 CATCH (ex, RETURN_MASK_ERROR)
8281 {
8282 if (ex.error == TARGET_CLOSE_ERROR)
8283 {
8284 /* If we got an (EOF) error that caused the target
8285 to go away, then we're done, that's what we wanted.
8286 "k" is susceptible to cause a premature EOF, given
8287 that the remote server isn't actually required to
8288 reply to "k", and it can happen that it doesn't
8289 even get to reply ACK to the "k". */
8290 return;
8291 }
8292
8293 /* Otherwise, something went wrong. We didn't actually kill
8294 the target. Just propagate the exception, and let the
8295 user or higher layers decide what to do. */
8296 throw_exception (ex);
8297 }
8298 END_CATCH
5796c8dc 8299
25e4902b
AHJ
8300 /* We've killed the remote end, we get to mourn it. Since this is
8301 target remote, single-process, mourning the inferior also
8302 unpushes remote_ops. */
5796c8dc
SS
8303 target_mourn_inferior ();
8304}
8305
8306static int
8307remote_vkill (int pid, struct remote_state *rs)
8308{
25e4902b 8309 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
5796c8dc
SS
8310 return -1;
8311
8312 /* Tell the remote target to detach. */
ef5ccd6c 8313 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
5796c8dc
SS
8314 putpkt (rs->buf);
8315 getpkt (&rs->buf, &rs->buf_size, 0);
8316
25e4902b
AHJ
8317 switch (packet_ok (rs->buf,
8318 &remote_protocol_packets[PACKET_vKill]))
8319 {
8320 case PACKET_OK:
8321 return 0;
8322 case PACKET_ERROR:
8323 return 1;
8324 case PACKET_UNKNOWN:
8325 return -1;
8326 default:
8327 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8328 }
5796c8dc
SS
8329}
8330
8331static void
8332extended_remote_kill (struct target_ops *ops)
8333{
8334 int res;
8335 int pid = ptid_get_pid (inferior_ptid);
8336 struct remote_state *rs = get_remote_state ();
8337
25e4902b
AHJ
8338 /* If we're stopped while forking and we haven't followed yet, kill the
8339 child task. We need to do this before killing the parent task
8340 because if this is a vfork then the parent will be sleeping. */
8341 kill_new_fork_children (pid, rs);
8342
5796c8dc 8343 res = remote_vkill (pid, rs);
ef5ccd6c 8344 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
5796c8dc
SS
8345 {
8346 /* Don't try 'k' on a multi-process aware stub -- it has no way
8347 to specify the pid. */
8348
8349 putpkt ("k");
8350#if 0
8351 getpkt (&rs->buf, &rs->buf_size, 0);
8352 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8353 res = 1;
8354#else
8355 /* Don't wait for it to die. I'm not really sure it matters whether
8356 we do or not. For the existing stubs, kill is a noop. */
8357 res = 0;
8358#endif
8359 }
8360
8361 if (res != 0)
8362 error (_("Can't kill process"));
8363
8364 target_mourn_inferior ();
8365}
8366
8367static void
25e4902b 8368remote_mourn (struct target_ops *target)
5796c8dc
SS
8369{
8370 unpush_target (target);
8371
8372 /* remote_close takes care of doing most of the clean up. */
8373 generic_mourn_inferior ();
8374}
8375
8376static void
25e4902b 8377extended_remote_mourn (struct target_ops *target)
5796c8dc
SS
8378{
8379 struct remote_state *rs = get_remote_state ();
8380
8381 /* In case we got here due to an error, but we're going to stay
8382 connected. */
8383 rs->waiting_for_stop_reply = 0;
8384
5796c8dc
SS
8385 /* If the current general thread belonged to the process we just
8386 detached from or has exited, the remote side current general
8387 thread becomes undefined. Considering a case like this:
8388
8389 - We just got here due to a detach.
8390 - The process that we're detaching from happens to immediately
8391 report a global breakpoint being hit in non-stop mode, in the
8392 same thread we had selected before.
8393 - GDB attaches to this process again.
8394 - This event happens to be the next event we handle.
8395
8396 GDB would consider that the current general thread didn't need to
8397 be set on the stub side (with Hg), since for all it knew,
8398 GENERAL_THREAD hadn't changed.
8399
8400 Notice that although in all-stop mode, the remote server always
8401 sets the current thread to the thread reporting the stop event,
8402 that doesn't happen in non-stop mode; in non-stop, the stub *must
8403 not* change the current thread when reporting a breakpoint hit,
8404 due to the decoupling of event reporting and event handling.
8405
8406 To keep things simple, we always invalidate our notion of the
8407 current thread. */
25e4902b 8408 record_currthread (rs, minus_one_ptid);
5796c8dc
SS
8409
8410 /* Unlike "target remote", we do not want to unpush the target; then
8411 the next time the user says "run", we won't be connected. */
8412
8413 /* Call common code to mark the inferior as not running. */
8414 generic_mourn_inferior ();
8415
8416 if (!have_inferiors ())
8417 {
8418 if (!remote_multi_process_p (rs))
8419 {
8420 /* Check whether the target is running now - some remote stubs
8421 automatically restart after kill. */
8422 putpkt ("?");
8423 getpkt (&rs->buf, &rs->buf_size, 0);
8424
8425 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8426 {
c50c785c
JM
8427 /* Assume that the target has been restarted. Set
8428 inferior_ptid so that bits of core GDB realizes
8429 there's something here, e.g., so that the user can
8430 say "kill" again. */
5796c8dc
SS
8431 inferior_ptid = magic_null_ptid;
8432 }
8433 }
8434 }
8435}
8436
a45ae5f8 8437static int
25e4902b 8438extended_remote_supports_disable_randomization (struct target_ops *self)
a45ae5f8 8439{
25e4902b 8440 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
a45ae5f8
JM
8441}
8442
8443static void
8444extended_remote_disable_randomization (int val)
8445{
8446 struct remote_state *rs = get_remote_state ();
8447 char *reply;
8448
ef5ccd6c
JM
8449 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8450 val);
a45ae5f8
JM
8451 putpkt (rs->buf);
8452 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8453 if (*reply == '\0')
8454 error (_("Target does not support QDisableRandomization."));
8455 if (strcmp (reply, "OK") != 0)
8456 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8457}
8458
5796c8dc
SS
8459static int
8460extended_remote_run (char *args)
8461{
8462 struct remote_state *rs = get_remote_state ();
8463 int len;
8464
8465 /* If the user has disabled vRun support, or we have detected that
8466 support is not available, do not try it. */
25e4902b 8467 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
5796c8dc
SS
8468 return -1;
8469
8470 strcpy (rs->buf, "vRun;");
8471 len = strlen (rs->buf);
8472
8473 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8474 error (_("Remote file name too long for run packet"));
25e4902b
AHJ
8475 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8476 strlen (remote_exec_file));
5796c8dc
SS
8477
8478 gdb_assert (args != NULL);
8479 if (*args)
8480 {
8481 struct cleanup *back_to;
8482 int i;
8483 char **argv;
8484
8485 argv = gdb_buildargv (args);
25e4902b 8486 back_to = make_cleanup_freeargv (argv);
5796c8dc
SS
8487 for (i = 0; argv[i] != NULL; i++)
8488 {
8489 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8490 error (_("Argument list too long for run packet"));
8491 rs->buf[len++] = ';';
25e4902b
AHJ
8492 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8493 strlen (argv[i]));
5796c8dc
SS
8494 }
8495 do_cleanups (back_to);
8496 }
8497
8498 rs->buf[len++] = '\0';
8499
8500 putpkt (rs->buf);
8501 getpkt (&rs->buf, &rs->buf_size, 0);
8502
25e4902b 8503 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
5796c8dc 8504 {
25e4902b 8505 case PACKET_OK:
ef5ccd6c 8506 /* We have a wait response. All is well. */
5796c8dc 8507 return 0;
25e4902b
AHJ
8508 case PACKET_UNKNOWN:
8509 return -1;
8510 case PACKET_ERROR:
5796c8dc
SS
8511 if (remote_exec_file[0] == '\0')
8512 error (_("Running the default executable on the remote target failed; "
8513 "try \"set remote exec-file\"?"));
8514 else
8515 error (_("Running \"%s\" on the remote target failed"),
8516 remote_exec_file);
25e4902b
AHJ
8517 default:
8518 gdb_assert_not_reached (_("bad switch"));
5796c8dc
SS
8519 }
8520}
8521
8522/* In the extended protocol we want to be able to do things like
8523 "run" and have them basically work as expected. So we need
8524 a special create_inferior function. We support changing the
8525 executable file and the command line arguments, but not the
8526 environment. */
8527
8528static void
25e4902b
AHJ
8529extended_remote_create_inferior (struct target_ops *ops,
8530 char *exec_file, char *args,
8531 char **env, int from_tty)
5796c8dc 8532{
ef5ccd6c
JM
8533 int run_worked;
8534 char *stop_reply;
8535 struct remote_state *rs = get_remote_state ();
8536
5796c8dc
SS
8537 /* If running asynchronously, register the target file descriptor
8538 with the event loop. */
8539 if (target_can_async_p ())
25e4902b 8540 target_async (1);
5796c8dc 8541
a45ae5f8 8542 /* Disable address space randomization if requested (and supported). */
25e4902b 8543 if (extended_remote_supports_disable_randomization (ops))
a45ae5f8
JM
8544 extended_remote_disable_randomization (disable_randomization);
8545
5796c8dc 8546 /* Now restart the remote server. */
ef5ccd6c
JM
8547 run_worked = extended_remote_run (args) != -1;
8548 if (!run_worked)
5796c8dc
SS
8549 {
8550 /* vRun was not supported. Fail if we need it to do what the
8551 user requested. */
8552 if (remote_exec_file[0])
8553 error (_("Remote target does not support \"set remote exec-file\""));
8554 if (args[0])
8555 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8556
8557 /* Fall back to "R". */
8558 extended_remote_restart ();
8559 }
8560
cf7f2e2d
JM
8561 if (!have_inferiors ())
8562 {
8563 /* Clean up from the last time we ran, before we mark the target
8564 running again. This will mark breakpoints uninserted, and
8565 get_offsets may insert breakpoints. */
8566 init_thread_list ();
8567 init_wait_for_inferior ();
8568 }
5796c8dc 8569
ef5ccd6c
JM
8570 /* vRun's success return is a stop reply. */
8571 stop_reply = run_worked ? rs->buf : NULL;
8572 add_current_inferior_and_thread (stop_reply);
5796c8dc
SS
8573
8574 /* Get updated offsets, if the stub uses qOffsets. */
8575 get_offsets ();
8576}
5796c8dc
SS
8577\f
8578
ef5ccd6c
JM
8579/* Given a location's target info BP_TGT and the packet buffer BUF, output
8580 the list of conditions (in agent expression bytecode format), if any, the
8581 target needs to evaluate. The output is placed into the packet buffer
8582 started from BUF and ended at BUF_END. */
8583
8584static int
8585remote_add_target_side_condition (struct gdbarch *gdbarch,
8586 struct bp_target_info *bp_tgt, char *buf,
8587 char *buf_end)
8588{
8589 struct agent_expr *aexpr = NULL;
8590 int i, ix;
8591 char *pkt;
8592 char *buf_start = buf;
8593
8594 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8595 return 0;
8596
8597 buf += strlen (buf);
8598 xsnprintf (buf, buf_end - buf, "%s", ";");
8599 buf++;
8600
8601 /* Send conditions to the target and free the vector. */
8602 for (ix = 0;
8603 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8604 ix++)
8605 {
8606 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8607 buf += strlen (buf);
8608 for (i = 0; i < aexpr->len; ++i)
8609 buf = pack_hex_byte (buf, aexpr->buf[i]);
8610 *buf = '\0';
8611 }
ef5ccd6c
JM
8612 return 0;
8613}
8614
8615static void
8616remote_add_target_side_commands (struct gdbarch *gdbarch,
8617 struct bp_target_info *bp_tgt, char *buf)
8618{
8619 struct agent_expr *aexpr = NULL;
8620 int i, ix;
8621
8622 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8623 return;
8624
8625 buf += strlen (buf);
8626
8627 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8628 buf += strlen (buf);
8629
8630 /* Concatenate all the agent expressions that are commands into the
8631 cmds parameter. */
8632 for (ix = 0;
8633 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8634 ix++)
8635 {
8636 sprintf (buf, "X%x,", aexpr->len);
8637 buf += strlen (buf);
8638 for (i = 0; i < aexpr->len; ++i)
8639 buf = pack_hex_byte (buf, aexpr->buf[i]);
8640 *buf = '\0';
8641 }
ef5ccd6c
JM
8642}
8643
5796c8dc
SS
8644/* Insert a breakpoint. On targets that have software breakpoint
8645 support, we ask the remote target to do the work; on targets
8646 which don't, we insert a traditional memory breakpoint. */
8647
8648static int
25e4902b
AHJ
8649remote_insert_breakpoint (struct target_ops *ops,
8650 struct gdbarch *gdbarch,
5796c8dc
SS
8651 struct bp_target_info *bp_tgt)
8652{
8653 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8654 If it succeeds, then set the support to PACKET_ENABLE. If it
8655 fails, and the user has explicitly requested the Z support then
8656 report an error, otherwise, mark it disabled and go on. */
8657
25e4902b 8658 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
5796c8dc 8659 {
25e4902b 8660 CORE_ADDR addr = bp_tgt->reqstd_address;
5796c8dc 8661 struct remote_state *rs;
ef5ccd6c 8662 char *p, *endbuf;
5796c8dc 8663 int bpsize;
ef5ccd6c 8664 struct condition_list *cond = NULL;
5796c8dc 8665
25e4902b
AHJ
8666 /* Make sure the remote is pointing at the right process, if
8667 necessary. */
8668 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8669 set_general_process ();
8670
cf7f2e2d 8671 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
5796c8dc
SS
8672
8673 rs = get_remote_state ();
8674 p = rs->buf;
ef5ccd6c 8675 endbuf = rs->buf + get_remote_packet_size ();
5796c8dc
SS
8676
8677 *(p++) = 'Z';
8678 *(p++) = '0';
8679 *(p++) = ',';
8680 addr = (ULONGEST) remote_address_masked (addr);
8681 p += hexnumstr (p, addr);
ef5ccd6c
JM
8682 xsnprintf (p, endbuf - p, ",%d", bpsize);
8683
25e4902b 8684 if (remote_supports_cond_breakpoints (ops))
ef5ccd6c
JM
8685 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8686
25e4902b 8687 if (remote_can_run_breakpoint_commands (ops))
ef5ccd6c 8688 remote_add_target_side_commands (gdbarch, bp_tgt, p);
5796c8dc
SS
8689
8690 putpkt (rs->buf);
8691 getpkt (&rs->buf, &rs->buf_size, 0);
8692
8693 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8694 {
8695 case PACKET_ERROR:
8696 return -1;
8697 case PACKET_OK:
8698 bp_tgt->placed_address = addr;
8699 bp_tgt->placed_size = bpsize;
8700 return 0;
8701 case PACKET_UNKNOWN:
8702 break;
8703 }
8704 }
8705
25e4902b
AHJ
8706 /* If this breakpoint has target-side commands but this stub doesn't
8707 support Z0 packets, throw error. */
8708 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8709 throw_error (NOT_SUPPORTED_ERROR, _("\
8710Target doesn't support breakpoints that have target side commands."));
8711
8712 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
5796c8dc
SS
8713}
8714
8715static int
25e4902b
AHJ
8716remote_remove_breakpoint (struct target_ops *ops,
8717 struct gdbarch *gdbarch,
5796c8dc
SS
8718 struct bp_target_info *bp_tgt)
8719{
8720 CORE_ADDR addr = bp_tgt->placed_address;
8721 struct remote_state *rs = get_remote_state ();
8722
25e4902b 8723 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
5796c8dc
SS
8724 {
8725 char *p = rs->buf;
ef5ccd6c 8726 char *endbuf = rs->buf + get_remote_packet_size ();
5796c8dc 8727
25e4902b
AHJ
8728 /* Make sure the remote is pointing at the right process, if
8729 necessary. */
8730 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8731 set_general_process ();
8732
5796c8dc
SS
8733 *(p++) = 'z';
8734 *(p++) = '0';
8735 *(p++) = ',';
8736
8737 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8738 p += hexnumstr (p, addr);
ef5ccd6c 8739 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
5796c8dc
SS
8740
8741 putpkt (rs->buf);
8742 getpkt (&rs->buf, &rs->buf_size, 0);
8743
8744 return (rs->buf[0] == 'E');
8745 }
8746
25e4902b 8747 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
5796c8dc
SS
8748}
8749
8750static int
8751watchpoint_to_Z_packet (int type)
8752{
8753 switch (type)
8754 {
8755 case hw_write:
8756 return Z_PACKET_WRITE_WP;
8757 break;
8758 case hw_read:
8759 return Z_PACKET_READ_WP;
8760 break;
8761 case hw_access:
8762 return Z_PACKET_ACCESS_WP;
8763 break;
8764 default:
8765 internal_error (__FILE__, __LINE__,
8766 _("hw_bp_to_z: bad watchpoint type %d"), type);
8767 }
8768}
8769
8770static int
25e4902b
AHJ
8771remote_insert_watchpoint (struct target_ops *self,
8772 CORE_ADDR addr, int len, int type,
cf7f2e2d 8773 struct expression *cond)
5796c8dc
SS
8774{
8775 struct remote_state *rs = get_remote_state ();
ef5ccd6c 8776 char *endbuf = rs->buf + get_remote_packet_size ();
5796c8dc
SS
8777 char *p;
8778 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8779
25e4902b 8780 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
cf7f2e2d 8781 return 1;
5796c8dc 8782
25e4902b
AHJ
8783 /* Make sure the remote is pointing at the right process, if
8784 necessary. */
8785 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8786 set_general_process ();
8787
ef5ccd6c 8788 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
5796c8dc
SS
8789 p = strchr (rs->buf, '\0');
8790 addr = remote_address_masked (addr);
8791 p += hexnumstr (p, (ULONGEST) addr);
ef5ccd6c 8792 xsnprintf (p, endbuf - p, ",%x", len);
5796c8dc
SS
8793
8794 putpkt (rs->buf);
8795 getpkt (&rs->buf, &rs->buf_size, 0);
8796
8797 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8798 {
8799 case PACKET_ERROR:
5796c8dc 8800 return -1;
cf7f2e2d
JM
8801 case PACKET_UNKNOWN:
8802 return 1;
5796c8dc
SS
8803 case PACKET_OK:
8804 return 0;
8805 }
8806 internal_error (__FILE__, __LINE__,
8807 _("remote_insert_watchpoint: reached end of function"));
8808}
8809
ef5ccd6c
JM
8810static int
8811remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8812 CORE_ADDR start, int length)
8813{
8814 CORE_ADDR diff = remote_address_masked (addr - start);
8815
8816 return diff < length;
8817}
8818
5796c8dc
SS
8819
8820static int
25e4902b
AHJ
8821remote_remove_watchpoint (struct target_ops *self,
8822 CORE_ADDR addr, int len, int type,
cf7f2e2d 8823 struct expression *cond)
5796c8dc
SS
8824{
8825 struct remote_state *rs = get_remote_state ();
ef5ccd6c 8826 char *endbuf = rs->buf + get_remote_packet_size ();
5796c8dc
SS
8827 char *p;
8828 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8829
25e4902b 8830 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5796c8dc
SS
8831 return -1;
8832
25e4902b
AHJ
8833 /* Make sure the remote is pointing at the right process, if
8834 necessary. */
8835 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8836 set_general_process ();
8837
ef5ccd6c 8838 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
5796c8dc
SS
8839 p = strchr (rs->buf, '\0');
8840 addr = remote_address_masked (addr);
8841 p += hexnumstr (p, (ULONGEST) addr);
ef5ccd6c 8842 xsnprintf (p, endbuf - p, ",%x", len);
5796c8dc
SS
8843 putpkt (rs->buf);
8844 getpkt (&rs->buf, &rs->buf_size, 0);
8845
8846 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8847 {
8848 case PACKET_ERROR:
8849 case PACKET_UNKNOWN:
8850 return -1;
8851 case PACKET_OK:
8852 return 0;
8853 }
8854 internal_error (__FILE__, __LINE__,
8855 _("remote_remove_watchpoint: reached end of function"));
8856}
8857
8858
8859int remote_hw_watchpoint_limit = -1;
a45ae5f8 8860int remote_hw_watchpoint_length_limit = -1;
5796c8dc
SS
8861int remote_hw_breakpoint_limit = -1;
8862
a45ae5f8 8863static int
25e4902b
AHJ
8864remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8865 CORE_ADDR addr, int len)
a45ae5f8
JM
8866{
8867 if (remote_hw_watchpoint_length_limit == 0)
8868 return 0;
8869 else if (remote_hw_watchpoint_length_limit < 0)
8870 return 1;
8871 else if (len <= remote_hw_watchpoint_length_limit)
8872 return 1;
8873 else
8874 return 0;
8875}
8876
5796c8dc 8877static int
25e4902b
AHJ
8878remote_check_watch_resources (struct target_ops *self,
8879 int type, int cnt, int ot)
5796c8dc
SS
8880{
8881 if (type == bp_hardware_breakpoint)
8882 {
8883 if (remote_hw_breakpoint_limit == 0)
8884 return 0;
8885 else if (remote_hw_breakpoint_limit < 0)
8886 return 1;
8887 else if (cnt <= remote_hw_breakpoint_limit)
8888 return 1;
8889 }
8890 else
8891 {
8892 if (remote_hw_watchpoint_limit == 0)
8893 return 0;
8894 else if (remote_hw_watchpoint_limit < 0)
8895 return 1;
8896 else if (ot)
8897 return -1;
8898 else if (cnt <= remote_hw_watchpoint_limit)
8899 return 1;
8900 }
8901 return -1;
8902}
8903
25e4902b
AHJ
8904/* The to_stopped_by_sw_breakpoint method of target remote. */
8905
8906static int
8907remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8908{
8909 struct remote_state *rs = get_remote_state ();
8910
8911 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8912}
8913
8914/* The to_supports_stopped_by_sw_breakpoint method of target
8915 remote. */
8916
8917static int
8918remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8919{
8920 struct remote_state *rs = get_remote_state ();
8921
8922 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8923}
8924
8925/* The to_stopped_by_hw_breakpoint method of target remote. */
8926
8927static int
8928remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8929{
8930 struct remote_state *rs = get_remote_state ();
8931
8932 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8933}
8934
8935/* The to_supports_stopped_by_hw_breakpoint method of target
8936 remote. */
8937
8938static int
8939remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8940{
8941 struct remote_state *rs = get_remote_state ();
8942
8943 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8944}
8945
5796c8dc 8946static int
25e4902b 8947remote_stopped_by_watchpoint (struct target_ops *ops)
5796c8dc 8948{
25e4902b
AHJ
8949 struct remote_state *rs = get_remote_state ();
8950
8951 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
5796c8dc
SS
8952}
8953
8954static int
8955remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8956{
25e4902b 8957 struct remote_state *rs = get_remote_state ();
5796c8dc 8958 int rc = 0;
cf7f2e2d 8959
25e4902b 8960 if (remote_stopped_by_watchpoint (target))
5796c8dc 8961 {
25e4902b 8962 *addr_p = rs->remote_watch_data_address;
5796c8dc
SS
8963 rc = 1;
8964 }
8965
8966 return rc;
8967}
8968
8969
8970static int
25e4902b 8971remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
5796c8dc
SS
8972 struct bp_target_info *bp_tgt)
8973{
25e4902b 8974 CORE_ADDR addr = bp_tgt->reqstd_address;
5796c8dc 8975 struct remote_state *rs;
ef5ccd6c
JM
8976 char *p, *endbuf;
8977 char *message;
25e4902b 8978 int bpsize;
5796c8dc
SS
8979
8980 /* The length field should be set to the size of a breakpoint
8981 instruction, even though we aren't inserting one ourselves. */
8982
25e4902b 8983 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
5796c8dc 8984
25e4902b 8985 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5796c8dc
SS
8986 return -1;
8987
25e4902b
AHJ
8988 /* Make sure the remote is pointing at the right process, if
8989 necessary. */
8990 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8991 set_general_process ();
8992
5796c8dc
SS
8993 rs = get_remote_state ();
8994 p = rs->buf;
ef5ccd6c 8995 endbuf = rs->buf + get_remote_packet_size ();
5796c8dc
SS
8996
8997 *(p++) = 'Z';
8998 *(p++) = '1';
8999 *(p++) = ',';
9000
25e4902b 9001 addr = remote_address_masked (addr);
5796c8dc 9002 p += hexnumstr (p, (ULONGEST) addr);
25e4902b 9003 xsnprintf (p, endbuf - p, ",%x", bpsize);
ef5ccd6c 9004
25e4902b 9005 if (remote_supports_cond_breakpoints (self))
ef5ccd6c
JM
9006 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9007
25e4902b 9008 if (remote_can_run_breakpoint_commands (self))
ef5ccd6c 9009 remote_add_target_side_commands (gdbarch, bp_tgt, p);
5796c8dc
SS
9010
9011 putpkt (rs->buf);
9012 getpkt (&rs->buf, &rs->buf_size, 0);
9013
9014 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9015 {
9016 case PACKET_ERROR:
ef5ccd6c
JM
9017 if (rs->buf[1] == '.')
9018 {
9019 message = strchr (rs->buf + 2, '.');
9020 if (message)
9021 error (_("Remote failure reply: %s"), message + 1);
9022 }
9023 return -1;
5796c8dc
SS
9024 case PACKET_UNKNOWN:
9025 return -1;
9026 case PACKET_OK:
25e4902b
AHJ
9027 bp_tgt->placed_address = addr;
9028 bp_tgt->placed_size = bpsize;
5796c8dc
SS
9029 return 0;
9030 }
9031 internal_error (__FILE__, __LINE__,
9032 _("remote_insert_hw_breakpoint: reached end of function"));
9033}
9034
9035
9036static int
25e4902b 9037remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
5796c8dc
SS
9038 struct bp_target_info *bp_tgt)
9039{
9040 CORE_ADDR addr;
9041 struct remote_state *rs = get_remote_state ();
9042 char *p = rs->buf;
ef5ccd6c 9043 char *endbuf = rs->buf + get_remote_packet_size ();
5796c8dc 9044
25e4902b 9045 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5796c8dc
SS
9046 return -1;
9047
25e4902b
AHJ
9048 /* Make sure the remote is pointing at the right process, if
9049 necessary. */
9050 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9051 set_general_process ();
9052
5796c8dc
SS
9053 *(p++) = 'z';
9054 *(p++) = '1';
9055 *(p++) = ',';
9056
9057 addr = remote_address_masked (bp_tgt->placed_address);
9058 p += hexnumstr (p, (ULONGEST) addr);
ef5ccd6c 9059 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
5796c8dc
SS
9060
9061 putpkt (rs->buf);
9062 getpkt (&rs->buf, &rs->buf_size, 0);
9063
9064 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9065 {
9066 case PACKET_ERROR:
9067 case PACKET_UNKNOWN:
9068 return -1;
9069 case PACKET_OK:
9070 return 0;
9071 }
9072 internal_error (__FILE__, __LINE__,
9073 _("remote_remove_hw_breakpoint: reached end of function"));
9074}
9075
cf7f2e2d
JM
9076/* Verify memory using the "qCRC:" request. */
9077
9078static int
9079remote_verify_memory (struct target_ops *ops,
9080 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9081{
9082 struct remote_state *rs = get_remote_state ();
9083 unsigned long host_crc, target_crc;
9084 char *tmp;
9085
25e4902b
AHJ
9086 /* It doesn't make sense to use qCRC if the remote target is
9087 connected but not running. */
9088 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9089 {
9090 enum packet_result result;
cf7f2e2d 9091
25e4902b
AHJ
9092 /* Make sure the remote is pointing at the right process. */
9093 set_general_process ();
cf7f2e2d 9094
25e4902b
AHJ
9095 /* FIXME: assumes lma can fit into long. */
9096 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9097 (long) lma, (long) size);
9098 putpkt (rs->buf);
9099
9100 /* Be clever; compute the host_crc before waiting for target
9101 reply. */
9102 host_crc = xcrc32 (data, size, 0xffffffff);
cf7f2e2d 9103
25e4902b
AHJ
9104 getpkt (&rs->buf, &rs->buf_size, 0);
9105
9106 result = packet_ok (rs->buf,
9107 &remote_protocol_packets[PACKET_qCRC]);
9108 if (result == PACKET_ERROR)
9109 return -1;
9110 else if (result == PACKET_OK)
9111 {
9112 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9113 target_crc = target_crc * 16 + fromhex (*tmp);
cf7f2e2d 9114
25e4902b
AHJ
9115 return (host_crc == target_crc);
9116 }
9117 }
cf7f2e2d 9118
25e4902b 9119 return simple_verify_memory (ops, data, lma, size);
cf7f2e2d
JM
9120}
9121
5796c8dc
SS
9122/* compare-sections command
9123
9124 With no arguments, compares each loadable section in the exec bfd
9125 with the same memory range on the target, and reports mismatches.
cf7f2e2d 9126 Useful for verifying the image on the target against the exec file. */
5796c8dc
SS
9127
9128static void
9129compare_sections_command (char *args, int from_tty)
9130{
5796c8dc 9131 asection *s;
5796c8dc 9132 struct cleanup *old_chain;
25e4902b 9133 gdb_byte *sectdata;
5796c8dc
SS
9134 const char *sectname;
9135 bfd_size_type size;
9136 bfd_vma lma;
9137 int matched = 0;
9138 int mismatched = 0;
cf7f2e2d 9139 int res;
25e4902b 9140 int read_only = 0;
5796c8dc
SS
9141
9142 if (!exec_bfd)
9143 error (_("command cannot be used without an exec file"));
5796c8dc 9144
25e4902b
AHJ
9145 /* Make sure the remote is pointing at the right process. */
9146 set_general_process ();
9147
9148 if (args != NULL && strcmp (args, "-r") == 0)
9149 {
9150 read_only = 1;
9151 args = NULL;
9152 }
9153
5796c8dc
SS
9154 for (s = exec_bfd->sections; s; s = s->next)
9155 {
9156 if (!(s->flags & SEC_LOAD))
c50c785c 9157 continue; /* Skip non-loadable section. */
5796c8dc 9158
25e4902b
AHJ
9159 if (read_only && (s->flags & SEC_READONLY) == 0)
9160 continue; /* Skip writeable sections */
9161
5796c8dc
SS
9162 size = bfd_get_section_size (s);
9163 if (size == 0)
c50c785c 9164 continue; /* Skip zero-length section. */
5796c8dc
SS
9165
9166 sectname = bfd_get_section_name (exec_bfd, s);
9167 if (args && strcmp (args, sectname) != 0)
c50c785c 9168 continue; /* Not the section selected by user. */
5796c8dc 9169
c50c785c 9170 matched = 1; /* Do this section. */
5796c8dc 9171 lma = s->lma;
5796c8dc 9172
5796c8dc
SS
9173 sectdata = xmalloc (size);
9174 old_chain = make_cleanup (xfree, sectdata);
9175 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5796c8dc 9176
cf7f2e2d
JM
9177 res = target_verify_memory (sectdata, lma, size);
9178
9179 if (res == -1)
5796c8dc 9180 error (_("target memory fault, section %s, range %s -- %s"), sectname,
ef5ccd6c
JM
9181 paddress (target_gdbarch (), lma),
9182 paddress (target_gdbarch (), lma + size));
5796c8dc
SS
9183
9184 printf_filtered ("Section %s, range %s -- %s: ", sectname,
ef5ccd6c
JM
9185 paddress (target_gdbarch (), lma),
9186 paddress (target_gdbarch (), lma + size));
cf7f2e2d 9187 if (res)
5796c8dc
SS
9188 printf_filtered ("matched.\n");
9189 else
9190 {
9191 printf_filtered ("MIS-MATCHED!\n");
9192 mismatched++;
9193 }
9194
9195 do_cleanups (old_chain);
9196 }
9197 if (mismatched > 0)
25e4902b 9198 warning (_("One or more sections of the target image does not match\n\
5796c8dc
SS
9199the loaded file\n"));
9200 if (args && !matched)
9201 printf_filtered (_("No loaded section named '%s'.\n"), args);
9202}
9203
9204/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9205 into remote target. The number of bytes written to the remote
9206 target is returned, or -1 for error. */
9207
25e4902b 9208static enum target_xfer_status
5796c8dc
SS
9209remote_write_qxfer (struct target_ops *ops, const char *object_name,
9210 const char *annex, const gdb_byte *writebuf,
25e4902b 9211 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
5796c8dc
SS
9212 struct packet_config *packet)
9213{
9214 int i, buf_len;
9215 ULONGEST n;
9216 struct remote_state *rs = get_remote_state ();
9217 int max_size = get_memory_write_packet_size ();
9218
9219 if (packet->support == PACKET_DISABLE)
25e4902b 9220 return TARGET_XFER_E_IO;
5796c8dc
SS
9221
9222 /* Insert header. */
9223 i = snprintf (rs->buf, max_size,
9224 "qXfer:%s:write:%s:%s:",
9225 object_name, annex ? annex : "",
9226 phex_nz (offset, sizeof offset));
9227 max_size -= (i + 1);
9228
9229 /* Escape as much data as fits into rs->buf. */
9230 buf_len = remote_escape_output
25e4902b 9231 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
5796c8dc
SS
9232
9233 if (putpkt_binary (rs->buf, i + buf_len) < 0
9234 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9235 || packet_ok (rs->buf, packet) != PACKET_OK)
25e4902b 9236 return TARGET_XFER_E_IO;
5796c8dc
SS
9237
9238 unpack_varlen_hex (rs->buf, &n);
25e4902b
AHJ
9239
9240 *xfered_len = n;
9241 return TARGET_XFER_OK;
5796c8dc
SS
9242}
9243
9244/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9245 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9246 number of bytes read is returned, or 0 for EOF, or -1 for error.
9247 The number of bytes read may be less than LEN without indicating an
9248 EOF. PACKET is checked and updated to indicate whether the remote
9249 target supports this object. */
9250
25e4902b 9251static enum target_xfer_status
5796c8dc
SS
9252remote_read_qxfer (struct target_ops *ops, const char *object_name,
9253 const char *annex,
9254 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
25e4902b 9255 ULONGEST *xfered_len,
5796c8dc
SS
9256 struct packet_config *packet)
9257{
5796c8dc
SS
9258 struct remote_state *rs = get_remote_state ();
9259 LONGEST i, n, packet_len;
9260
9261 if (packet->support == PACKET_DISABLE)
25e4902b 9262 return TARGET_XFER_E_IO;
5796c8dc
SS
9263
9264 /* Check whether we've cached an end-of-object packet that matches
9265 this request. */
25e4902b 9266 if (rs->finished_object)
5796c8dc 9267 {
25e4902b
AHJ
9268 if (strcmp (object_name, rs->finished_object) == 0
9269 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9270 && offset == rs->finished_offset)
9271 return TARGET_XFER_EOF;
9272
5796c8dc
SS
9273
9274 /* Otherwise, we're now reading something different. Discard
9275 the cache. */
25e4902b
AHJ
9276 xfree (rs->finished_object);
9277 xfree (rs->finished_annex);
9278 rs->finished_object = NULL;
9279 rs->finished_annex = NULL;
5796c8dc
SS
9280 }
9281
9282 /* Request only enough to fit in a single packet. The actual data
9283 may not, since we don't know how much of it will need to be escaped;
9284 the target is free to respond with slightly less data. We subtract
9285 five to account for the response type and the protocol frame. */
9286 n = min (get_remote_packet_size () - 5, len);
9287 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9288 object_name, annex ? annex : "",
9289 phex_nz (offset, sizeof offset),
9290 phex_nz (n, sizeof n));
9291 i = putpkt (rs->buf);
9292 if (i < 0)
25e4902b 9293 return TARGET_XFER_E_IO;
5796c8dc
SS
9294
9295 rs->buf[0] = '\0';
9296 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9297 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
25e4902b 9298 return TARGET_XFER_E_IO;
5796c8dc
SS
9299
9300 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9301 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9302
9303 /* 'm' means there is (or at least might be) more data after this
9304 batch. That does not make sense unless there's at least one byte
9305 of data in this reply. */
9306 if (rs->buf[0] == 'm' && packet_len == 1)
9307 error (_("Remote qXfer reply contained no data."));
9308
9309 /* Got some data. */
25e4902b
AHJ
9310 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9311 packet_len - 1, readbuf, n);
5796c8dc
SS
9312
9313 /* 'l' is an EOF marker, possibly including a final block of data,
9314 or possibly empty. If we have the final block of a non-empty
9315 object, record this fact to bypass a subsequent partial read. */
9316 if (rs->buf[0] == 'l' && offset + i > 0)
9317 {
25e4902b
AHJ
9318 rs->finished_object = xstrdup (object_name);
9319 rs->finished_annex = xstrdup (annex ? annex : "");
9320 rs->finished_offset = offset + i;
5796c8dc
SS
9321 }
9322
25e4902b
AHJ
9323 if (i == 0)
9324 return TARGET_XFER_EOF;
9325 else
9326 {
9327 *xfered_len = i;
9328 return TARGET_XFER_OK;
9329 }
5796c8dc
SS
9330}
9331
25e4902b 9332static enum target_xfer_status
5796c8dc
SS
9333remote_xfer_partial (struct target_ops *ops, enum target_object object,
9334 const char *annex, gdb_byte *readbuf,
25e4902b
AHJ
9335 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9336 ULONGEST *xfered_len)
5796c8dc
SS
9337{
9338 struct remote_state *rs;
9339 int i;
9340 char *p2;
9341 char query_type;
25e4902b 9342 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
5796c8dc 9343
c50c785c 9344 set_remote_traceframe ();
5796c8dc
SS
9345 set_general_thread (inferior_ptid);
9346
9347 rs = get_remote_state ();
9348
9349 /* Handle memory using the standard memory routines. */
9350 if (object == TARGET_OBJECT_MEMORY)
9351 {
5796c8dc
SS
9352 /* If the remote target is connected but not running, we should
9353 pass this request down to a lower stratum (e.g. the executable
9354 file). */
9355 if (!target_has_execution)
25e4902b 9356 return TARGET_XFER_EOF;
5796c8dc
SS
9357
9358 if (writebuf != NULL)
25e4902b
AHJ
9359 return remote_write_bytes (offset, writebuf, len, unit_size,
9360 xfered_len);
5796c8dc 9361 else
25e4902b
AHJ
9362 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9363 xfered_len);
5796c8dc
SS
9364 }
9365
c50c785c 9366 /* Handle SPU memory using qxfer packets. */
5796c8dc
SS
9367 if (object == TARGET_OBJECT_SPU)
9368 {
9369 if (readbuf)
9370 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
25e4902b
AHJ
9371 xfered_len, &remote_protocol_packets
9372 [PACKET_qXfer_spu_read]);
5796c8dc
SS
9373 else
9374 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
25e4902b
AHJ
9375 xfered_len, &remote_protocol_packets
9376 [PACKET_qXfer_spu_write]);
5796c8dc
SS
9377 }
9378
9379 /* Handle extra signal info using qxfer packets. */
9380 if (object == TARGET_OBJECT_SIGNAL_INFO)
9381 {
9382 if (readbuf)
9383 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
25e4902b 9384 xfered_len, &remote_protocol_packets
5796c8dc
SS
9385 [PACKET_qXfer_siginfo_read]);
9386 else
c50c785c 9387 return remote_write_qxfer (ops, "siginfo", annex,
25e4902b 9388 writebuf, offset, len, xfered_len,
5796c8dc
SS
9389 &remote_protocol_packets
9390 [PACKET_qXfer_siginfo_write]);
9391 }
9392
cf7f2e2d
JM
9393 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9394 {
9395 if (readbuf)
c50c785c 9396 return remote_read_qxfer (ops, "statictrace", annex,
25e4902b 9397 readbuf, offset, len, xfered_len,
cf7f2e2d
JM
9398 &remote_protocol_packets
9399 [PACKET_qXfer_statictrace_read]);
9400 else
25e4902b 9401 return TARGET_XFER_E_IO;
cf7f2e2d
JM
9402 }
9403
5796c8dc
SS
9404 /* Only handle flash writes. */
9405 if (writebuf != NULL)
9406 {
9407 LONGEST xfered;
9408
9409 switch (object)
9410 {
9411 case TARGET_OBJECT_FLASH:
25e4902b
AHJ
9412 return remote_flash_write (ops, offset, len, xfered_len,
9413 writebuf);
5796c8dc
SS
9414
9415 default:
25e4902b 9416 return TARGET_XFER_E_IO;
5796c8dc
SS
9417 }
9418 }
9419
9420 /* Map pre-existing objects onto letters. DO NOT do this for new
9421 objects!!! Instead specify new query packets. */
9422 switch (object)
9423 {
9424 case TARGET_OBJECT_AVR:
9425 query_type = 'R';
9426 break;
9427
9428 case TARGET_OBJECT_AUXV:
9429 gdb_assert (annex == NULL);
9430 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
25e4902b 9431 xfered_len,
5796c8dc
SS
9432 &remote_protocol_packets[PACKET_qXfer_auxv]);
9433
9434 case TARGET_OBJECT_AVAILABLE_FEATURES:
9435 return remote_read_qxfer
25e4902b 9436 (ops, "features", annex, readbuf, offset, len, xfered_len,
5796c8dc
SS
9437 &remote_protocol_packets[PACKET_qXfer_features]);
9438
9439 case TARGET_OBJECT_LIBRARIES:
9440 return remote_read_qxfer
25e4902b 9441 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
5796c8dc
SS
9442 &remote_protocol_packets[PACKET_qXfer_libraries]);
9443
a45ae5f8
JM
9444 case TARGET_OBJECT_LIBRARIES_SVR4:
9445 return remote_read_qxfer
25e4902b 9446 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
a45ae5f8
JM
9447 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9448
5796c8dc
SS
9449 case TARGET_OBJECT_MEMORY_MAP:
9450 gdb_assert (annex == NULL);
9451 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
25e4902b 9452 xfered_len,
5796c8dc
SS
9453 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9454
9455 case TARGET_OBJECT_OSDATA:
9456 /* Should only get here if we're connected. */
25e4902b 9457 gdb_assert (rs->remote_desc);
5796c8dc 9458 return remote_read_qxfer
25e4902b 9459 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
5796c8dc
SS
9460 &remote_protocol_packets[PACKET_qXfer_osdata]);
9461
cf7f2e2d
JM
9462 case TARGET_OBJECT_THREADS:
9463 gdb_assert (annex == NULL);
9464 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
25e4902b 9465 xfered_len,
cf7f2e2d
JM
9466 &remote_protocol_packets[PACKET_qXfer_threads]);
9467
c50c785c
JM
9468 case TARGET_OBJECT_TRACEFRAME_INFO:
9469 gdb_assert (annex == NULL);
9470 return remote_read_qxfer
25e4902b 9471 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
c50c785c 9472 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
a45ae5f8
JM
9473
9474 case TARGET_OBJECT_FDPIC:
9475 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
25e4902b 9476 xfered_len,
a45ae5f8 9477 &remote_protocol_packets[PACKET_qXfer_fdpic]);
ef5ccd6c
JM
9478
9479 case TARGET_OBJECT_OPENVMS_UIB:
9480 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
25e4902b 9481 xfered_len,
ef5ccd6c
JM
9482 &remote_protocol_packets[PACKET_qXfer_uib]);
9483
9484 case TARGET_OBJECT_BTRACE:
9485 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
25e4902b 9486 xfered_len,
ef5ccd6c
JM
9487 &remote_protocol_packets[PACKET_qXfer_btrace]);
9488
25e4902b
AHJ
9489 case TARGET_OBJECT_BTRACE_CONF:
9490 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9491 len, xfered_len,
9492 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9493
9494 case TARGET_OBJECT_EXEC_FILE:
9495 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9496 len, xfered_len,
9497 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9498
5796c8dc 9499 default:
25e4902b 9500 return TARGET_XFER_E_IO;
5796c8dc
SS
9501 }
9502
c50c785c 9503 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
5796c8dc
SS
9504 large enough let the caller deal with it. */
9505 if (len < get_remote_packet_size ())
25e4902b 9506 return TARGET_XFER_E_IO;
5796c8dc
SS
9507 len = get_remote_packet_size ();
9508
9509 /* Except for querying the minimum buffer size, target must be open. */
25e4902b 9510 if (!rs->remote_desc)
5796c8dc
SS
9511 error (_("remote query is only available after target open"));
9512
9513 gdb_assert (annex != NULL);
9514 gdb_assert (readbuf != NULL);
9515
9516 p2 = rs->buf;
9517 *p2++ = 'q';
9518 *p2++ = query_type;
9519
9520 /* We used one buffer char for the remote protocol q command and
9521 another for the query type. As the remote protocol encapsulation
9522 uses 4 chars plus one extra in case we are debugging
9523 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9524 string. */
9525 i = 0;
9526 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9527 {
9528 /* Bad caller may have sent forbidden characters. */
9529 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9530 *p2++ = annex[i];
9531 i++;
9532 }
9533 *p2 = '\0';
9534 gdb_assert (annex[i] == '\0');
9535
9536 i = putpkt (rs->buf);
9537 if (i < 0)
25e4902b 9538 return TARGET_XFER_E_IO;
5796c8dc
SS
9539
9540 getpkt (&rs->buf, &rs->buf_size, 0);
9541 strcpy ((char *) readbuf, rs->buf);
9542
25e4902b
AHJ
9543 *xfered_len = strlen ((char *) readbuf);
9544 return TARGET_XFER_OK;
5796c8dc
SS
9545}
9546
9547static int
9548remote_search_memory (struct target_ops* ops,
9549 CORE_ADDR start_addr, ULONGEST search_space_len,
9550 const gdb_byte *pattern, ULONGEST pattern_len,
9551 CORE_ADDR *found_addrp)
9552{
ef5ccd6c 9553 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5796c8dc
SS
9554 struct remote_state *rs = get_remote_state ();
9555 int max_size = get_memory_write_packet_size ();
9556 struct packet_config *packet =
9557 &remote_protocol_packets[PACKET_qSearch_memory];
c50c785c
JM
9558 /* Number of packet bytes used to encode the pattern;
9559 this could be more than PATTERN_LEN due to escape characters. */
5796c8dc 9560 int escaped_pattern_len;
c50c785c 9561 /* Amount of pattern that was encodable in the packet. */
5796c8dc
SS
9562 int used_pattern_len;
9563 int i;
9564 int found;
9565 ULONGEST found_addr;
9566
9567 /* Don't go to the target if we don't have to.
9568 This is done before checking packet->support to avoid the possibility that
9569 a success for this edge case means the facility works in general. */
9570 if (pattern_len > search_space_len)
9571 return 0;
9572 if (pattern_len == 0)
9573 {
9574 *found_addrp = start_addr;
9575 return 1;
9576 }
9577
9578 /* If we already know the packet isn't supported, fall back to the simple
9579 way of searching memory. */
9580
25e4902b 9581 if (packet_config_support (packet) == PACKET_DISABLE)
5796c8dc
SS
9582 {
9583 /* Target doesn't provided special support, fall back and use the
9584 standard support (copy memory and do the search here). */
9585 return simple_search_memory (ops, start_addr, search_space_len,
9586 pattern, pattern_len, found_addrp);
9587 }
9588
25e4902b
AHJ
9589 /* Make sure the remote is pointing at the right process. */
9590 set_general_process ();
9591
5796c8dc
SS
9592 /* Insert header. */
9593 i = snprintf (rs->buf, max_size,
9594 "qSearch:memory:%s;%s;",
9595 phex_nz (start_addr, addr_size),
9596 phex_nz (search_space_len, sizeof (search_space_len)));
9597 max_size -= (i + 1);
9598
9599 /* Escape as much data as fits into rs->buf. */
9600 escaped_pattern_len =
25e4902b 9601 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
5796c8dc
SS
9602 &used_pattern_len, max_size);
9603
9604 /* Bail if the pattern is too large. */
9605 if (used_pattern_len != pattern_len)
c50c785c 9606 error (_("Pattern is too large to transmit to remote target."));
5796c8dc
SS
9607
9608 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9609 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9610 || packet_ok (rs->buf, packet) != PACKET_OK)
9611 {
9612 /* The request may not have worked because the command is not
9613 supported. If so, fall back to the simple way. */
9614 if (packet->support == PACKET_DISABLE)
9615 {
9616 return simple_search_memory (ops, start_addr, search_space_len,
9617 pattern, pattern_len, found_addrp);
9618 }
9619 return -1;
9620 }
9621
9622 if (rs->buf[0] == '0')
9623 found = 0;
9624 else if (rs->buf[0] == '1')
9625 {
9626 found = 1;
9627 if (rs->buf[1] != ',')
9628 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9629 unpack_varlen_hex (rs->buf + 2, &found_addr);
9630 *found_addrp = found_addr;
9631 }
9632 else
9633 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9634
9635 return found;
9636}
9637
9638static void
25e4902b 9639remote_rcmd (struct target_ops *self, const char *command,
5796c8dc
SS
9640 struct ui_file *outbuf)
9641{
9642 struct remote_state *rs = get_remote_state ();
9643 char *p = rs->buf;
9644
25e4902b 9645 if (!rs->remote_desc)
5796c8dc
SS
9646 error (_("remote rcmd is only available after target open"));
9647
9648 /* Send a NULL command across as an empty command. */
9649 if (command == NULL)
9650 command = "";
9651
9652 /* The query prefix. */
9653 strcpy (rs->buf, "qRcmd,");
9654 p = strchr (rs->buf, '\0');
9655
c50c785c
JM
9656 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9657 > get_remote_packet_size ())
5796c8dc
SS
9658 error (_("\"monitor\" command ``%s'' is too long."), command);
9659
9660 /* Encode the actual command. */
25e4902b 9661 bin2hex ((const gdb_byte *) command, p, strlen (command));
5796c8dc
SS
9662
9663 if (putpkt (rs->buf) < 0)
9664 error (_("Communication problem with target."));
9665
9666 /* get/display the response */
9667 while (1)
9668 {
9669 char *buf;
9670
cf7f2e2d 9671 /* XXX - see also remote_get_noisy_reply(). */
ef5ccd6c 9672 QUIT; /* Allow user to bail out with ^C. */
5796c8dc 9673 rs->buf[0] = '\0';
ef5ccd6c
JM
9674 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9675 {
9676 /* Timeout. Continue to (try to) read responses.
9677 This is better than stopping with an error, assuming the stub
9678 is still executing the (long) monitor command.
9679 If needed, the user can interrupt gdb using C-c, obtaining
9680 an effect similar to stop on timeout. */
9681 continue;
9682 }
5796c8dc
SS
9683 buf = rs->buf;
9684 if (buf[0] == '\0')
9685 error (_("Target does not support this command."));
9686 if (buf[0] == 'O' && buf[1] != 'K')
9687 {
9688 remote_console_output (buf + 1); /* 'O' message from stub. */
9689 continue;
9690 }
9691 if (strcmp (buf, "OK") == 0)
9692 break;
9693 if (strlen (buf) == 3 && buf[0] == 'E'
9694 && isdigit (buf[1]) && isdigit (buf[2]))
9695 {
9696 error (_("Protocol error with Rcmd"));
9697 }
9698 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9699 {
9700 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
cf7f2e2d 9701
5796c8dc
SS
9702 fputc_unfiltered (c, outbuf);
9703 }
9704 break;
9705 }
9706}
9707
9708static VEC(mem_region_s) *
9709remote_memory_map (struct target_ops *ops)
9710{
9711 VEC(mem_region_s) *result = NULL;
9712 char *text = target_read_stralloc (&current_target,
9713 TARGET_OBJECT_MEMORY_MAP, NULL);
9714
9715 if (text)
9716 {
9717 struct cleanup *back_to = make_cleanup (xfree, text);
cf7f2e2d 9718
5796c8dc
SS
9719 result = parse_memory_map (text);
9720 do_cleanups (back_to);
9721 }
9722
9723 return result;
9724}
9725
9726static void
9727packet_command (char *args, int from_tty)
9728{
9729 struct remote_state *rs = get_remote_state ();
9730
25e4902b 9731 if (!rs->remote_desc)
5796c8dc
SS
9732 error (_("command can only be used with remote target"));
9733
9734 if (!args)
9735 error (_("remote-packet command requires packet text as argument"));
9736
9737 puts_filtered ("sending: ");
9738 print_packet (args);
9739 puts_filtered ("\n");
9740 putpkt (args);
9741
9742 getpkt (&rs->buf, &rs->buf_size, 0);
9743 puts_filtered ("received: ");
9744 print_packet (rs->buf);
9745 puts_filtered ("\n");
9746}
9747
9748#if 0
9749/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9750
9751static void display_thread_info (struct gdb_ext_thread_info *info);
9752
9753static void threadset_test_cmd (char *cmd, int tty);
9754
9755static void threadalive_test (char *cmd, int tty);
9756
9757static void threadlist_test_cmd (char *cmd, int tty);
9758
9759int get_and_display_threadinfo (threadref *ref);
9760
9761static void threadinfo_test_cmd (char *cmd, int tty);
9762
9763static int thread_display_step (threadref *ref, void *context);
9764
9765static void threadlist_update_test_cmd (char *cmd, int tty);
9766
9767static void init_remote_threadtests (void);
9768
9769#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9770
9771static void
9772threadset_test_cmd (char *cmd, int tty)
9773{
9774 int sample_thread = SAMPLE_THREAD;
9775
9776 printf_filtered (_("Remote threadset test\n"));
9777 set_general_thread (sample_thread);
9778}
9779
9780
9781static void
9782threadalive_test (char *cmd, int tty)
9783{
9784 int sample_thread = SAMPLE_THREAD;
9785 int pid = ptid_get_pid (inferior_ptid);
25e4902b 9786 ptid_t ptid = ptid_build (pid, sample_thread, 0);
5796c8dc
SS
9787
9788 if (remote_thread_alive (ptid))
9789 printf_filtered ("PASS: Thread alive test\n");
9790 else
9791 printf_filtered ("FAIL: Thread alive test\n");
9792}
9793
9794void output_threadid (char *title, threadref *ref);
9795
9796void
9797output_threadid (char *title, threadref *ref)
9798{
9799 char hexid[20];
9800
9801 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9802 hexid[16] = 0;
9803 printf_filtered ("%s %s\n", title, (&hexid[0]));
9804}
9805
9806static void
9807threadlist_test_cmd (char *cmd, int tty)
9808{
9809 int startflag = 1;
9810 threadref nextthread;
9811 int done, result_count;
9812 threadref threadlist[3];
9813
9814 printf_filtered ("Remote Threadlist test\n");
9815 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9816 &result_count, &threadlist[0]))
9817 printf_filtered ("FAIL: threadlist test\n");
9818 else
9819 {
9820 threadref *scan = threadlist;
9821 threadref *limit = scan + result_count;
9822
9823 while (scan < limit)
9824 output_threadid (" thread ", scan++);
9825 }
9826}
9827
9828void
9829display_thread_info (struct gdb_ext_thread_info *info)
9830{
9831 output_threadid ("Threadid: ", &info->threadid);
9832 printf_filtered ("Name: %s\n ", info->shortname);
9833 printf_filtered ("State: %s\n", info->display);
9834 printf_filtered ("other: %s\n\n", info->more_display);
9835}
9836
9837int
9838get_and_display_threadinfo (threadref *ref)
9839{
9840 int result;
9841 int set;
9842 struct gdb_ext_thread_info threadinfo;
9843
9844 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9845 | TAG_MOREDISPLAY | TAG_DISPLAY;
9846 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9847 display_thread_info (&threadinfo);
9848 return result;
9849}
9850
9851static void
9852threadinfo_test_cmd (char *cmd, int tty)
9853{
9854 int athread = SAMPLE_THREAD;
9855 threadref thread;
9856 int set;
9857
9858 int_to_threadref (&thread, athread);
9859 printf_filtered ("Remote Threadinfo test\n");
9860 if (!get_and_display_threadinfo (&thread))
9861 printf_filtered ("FAIL cannot get thread info\n");
9862}
9863
9864static int
9865thread_display_step (threadref *ref, void *context)
9866{
9867 /* output_threadid(" threadstep ",ref); *//* simple test */
9868 return get_and_display_threadinfo (ref);
9869}
9870
9871static void
9872threadlist_update_test_cmd (char *cmd, int tty)
9873{
9874 printf_filtered ("Remote Threadlist update test\n");
9875 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9876}
9877
9878static void
9879init_remote_threadtests (void)
9880{
c50c785c
JM
9881 add_com ("tlist", class_obscure, threadlist_test_cmd,
9882 _("Fetch and print the remote list of "
9883 "thread identifiers, one pkt only"));
5796c8dc
SS
9884 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9885 _("Fetch and display info about one thread"));
9886 add_com ("tset", class_obscure, threadset_test_cmd,
9887 _("Test setting to a different thread"));
9888 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9889 _("Iterate through updating all remote thread info"));
9890 add_com ("talive", class_obscure, threadalive_test,
9891 _(" Remote thread alive test "));
9892}
9893
9894#endif /* 0 */
9895
9896/* Convert a thread ID to a string. Returns the string in a static
9897 buffer. */
9898
9899static char *
9900remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9901{
9902 static char buf[64];
9903 struct remote_state *rs = get_remote_state ();
9904
ef5ccd6c
JM
9905 if (ptid_equal (ptid, null_ptid))
9906 return normal_pid_to_str (ptid);
9907 else if (ptid_is_pid (ptid))
5796c8dc
SS
9908 {
9909 /* Printing an inferior target id. */
9910
9911 /* When multi-process extensions are off, there's no way in the
9912 remote protocol to know the remote process id, if there's any
9913 at all. There's one exception --- when we're connected with
9914 target extended-remote, and we manually attached to a process
9915 with "attach PID". We don't record anywhere a flag that
9916 allows us to distinguish that case from the case of
9917 connecting with extended-remote and the stub already being
9918 attached to a process, and reporting yes to qAttached, hence
9919 no smart special casing here. */
9920 if (!remote_multi_process_p (rs))
9921 {
9922 xsnprintf (buf, sizeof buf, "Remote target");
9923 return buf;
9924 }
9925
9926 return normal_pid_to_str (ptid);
9927 }
9928 else
9929 {
9930 if (ptid_equal (magic_null_ptid, ptid))
9931 xsnprintf (buf, sizeof buf, "Thread <main>");
ef5ccd6c 9932 else if (rs->extended && remote_multi_process_p (rs))
25e4902b
AHJ
9933 if (ptid_get_lwp (ptid) == 0)
9934 return normal_pid_to_str (ptid);
9935 else
9936 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9937 ptid_get_pid (ptid), ptid_get_lwp (ptid));
5796c8dc
SS
9938 else
9939 xsnprintf (buf, sizeof buf, "Thread %ld",
25e4902b 9940 ptid_get_lwp (ptid));
5796c8dc
SS
9941 return buf;
9942 }
9943}
9944
9945/* Get the address of the thread local variable in OBJFILE which is
9946 stored at OFFSET within the thread local storage for thread PTID. */
9947
9948static CORE_ADDR
9949remote_get_thread_local_address (struct target_ops *ops,
9950 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9951{
25e4902b 9952 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
5796c8dc
SS
9953 {
9954 struct remote_state *rs = get_remote_state ();
9955 char *p = rs->buf;
9956 char *endp = rs->buf + get_remote_packet_size ();
9957 enum packet_result result;
9958
9959 strcpy (p, "qGetTLSAddr:");
9960 p += strlen (p);
9961 p = write_ptid (p, endp, ptid);
9962 *p++ = ',';
9963 p += hexnumstr (p, offset);
9964 *p++ = ',';
9965 p += hexnumstr (p, lm);
9966 *p++ = '\0';
9967
9968 putpkt (rs->buf);
9969 getpkt (&rs->buf, &rs->buf_size, 0);
c50c785c
JM
9970 result = packet_ok (rs->buf,
9971 &remote_protocol_packets[PACKET_qGetTLSAddr]);
5796c8dc
SS
9972 if (result == PACKET_OK)
9973 {
9974 ULONGEST result;
9975
9976 unpack_varlen_hex (rs->buf, &result);
9977 return result;
9978 }
9979 else if (result == PACKET_UNKNOWN)
9980 throw_error (TLS_GENERIC_ERROR,
9981 _("Remote target doesn't support qGetTLSAddr packet"));
9982 else
9983 throw_error (TLS_GENERIC_ERROR,
9984 _("Remote target failed to process qGetTLSAddr request"));
9985 }
9986 else
9987 throw_error (TLS_GENERIC_ERROR,
9988 _("TLS not supported or disabled on this target"));
9989 /* Not reached. */
9990 return 0;
9991}
9992
cf7f2e2d
JM
9993/* Provide thread local base, i.e. Thread Information Block address.
9994 Returns 1 if ptid is found and thread_local_base is non zero. */
9995
ef5ccd6c 9996static int
25e4902b 9997remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
cf7f2e2d 9998{
25e4902b 9999 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
cf7f2e2d
JM
10000 {
10001 struct remote_state *rs = get_remote_state ();
10002 char *p = rs->buf;
10003 char *endp = rs->buf + get_remote_packet_size ();
10004 enum packet_result result;
10005
10006 strcpy (p, "qGetTIBAddr:");
10007 p += strlen (p);
10008 p = write_ptid (p, endp, ptid);
10009 *p++ = '\0';
10010
10011 putpkt (rs->buf);
10012 getpkt (&rs->buf, &rs->buf_size, 0);
10013 result = packet_ok (rs->buf,
10014 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10015 if (result == PACKET_OK)
10016 {
10017 ULONGEST result;
10018
10019 unpack_varlen_hex (rs->buf, &result);
10020 if (addr)
10021 *addr = (CORE_ADDR) result;
10022 return 1;
10023 }
10024 else if (result == PACKET_UNKNOWN)
10025 error (_("Remote target doesn't support qGetTIBAddr packet"));
10026 else
10027 error (_("Remote target failed to process qGetTIBAddr request"));
10028 }
10029 else
10030 error (_("qGetTIBAddr not supported or disabled on this target"));
10031 /* Not reached. */
10032 return 0;
10033}
10034
5796c8dc
SS
10035/* Support for inferring a target description based on the current
10036 architecture and the size of a 'g' packet. While the 'g' packet
10037 can have any size (since optional registers can be left off the
10038 end), some sizes are easily recognizable given knowledge of the
10039 approximate architecture. */
10040
10041struct remote_g_packet_guess
10042{
10043 int bytes;
10044 const struct target_desc *tdesc;
10045};
10046typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10047DEF_VEC_O(remote_g_packet_guess_s);
10048
10049struct remote_g_packet_data
10050{
10051 VEC(remote_g_packet_guess_s) *guesses;
10052};
10053
10054static struct gdbarch_data *remote_g_packet_data_handle;
10055
10056static void *
10057remote_g_packet_data_init (struct obstack *obstack)
10058{
10059 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10060}
10061
10062void
10063register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10064 const struct target_desc *tdesc)
10065{
10066 struct remote_g_packet_data *data
10067 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10068 struct remote_g_packet_guess new_guess, *guess;
10069 int ix;
10070
10071 gdb_assert (tdesc != NULL);
10072
10073 for (ix = 0;
10074 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10075 ix++)
10076 if (guess->bytes == bytes)
10077 internal_error (__FILE__, __LINE__,
c50c785c 10078 _("Duplicate g packet description added for size %d"),
5796c8dc
SS
10079 bytes);
10080
10081 new_guess.bytes = bytes;
10082 new_guess.tdesc = tdesc;
10083 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10084}
10085
10086/* Return 1 if remote_read_description would do anything on this target
10087 and architecture, 0 otherwise. */
10088
10089static int
10090remote_read_description_p (struct target_ops *target)
10091{
10092 struct remote_g_packet_data *data
ef5ccd6c 10093 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
5796c8dc
SS
10094
10095 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10096 return 1;
10097
10098 return 0;
10099}
10100
10101static const struct target_desc *
10102remote_read_description (struct target_ops *target)
10103{
10104 struct remote_g_packet_data *data
ef5ccd6c 10105 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
5796c8dc
SS
10106
10107 /* Do not try this during initial connection, when we do not know
10108 whether there is a running but stopped thread. */
10109 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
25e4902b 10110 return target->beneath->to_read_description (target->beneath);
5796c8dc
SS
10111
10112 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10113 {
10114 struct remote_g_packet_guess *guess;
10115 int ix;
10116 int bytes = send_g_packet ();
10117
10118 for (ix = 0;
10119 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10120 ix++)
10121 if (guess->bytes == bytes)
10122 return guess->tdesc;
10123
10124 /* We discard the g packet. A minor optimization would be to
10125 hold on to it, and fill the register cache once we have selected
10126 an architecture, but it's too tricky to do safely. */
10127 }
10128
25e4902b 10129 return target->beneath->to_read_description (target->beneath);
5796c8dc
SS
10130}
10131
10132/* Remote file transfer support. This is host-initiated I/O, not
10133 target-initiated; for target-initiated, see remote-fileio.c. */
10134
10135/* If *LEFT is at least the length of STRING, copy STRING to
10136 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10137 decrease *LEFT. Otherwise raise an error. */
10138
10139static void
10140remote_buffer_add_string (char **buffer, int *left, char *string)
10141{
10142 int len = strlen (string);
10143
10144 if (len > *left)
10145 error (_("Packet too long for target."));
10146
10147 memcpy (*buffer, string, len);
10148 *buffer += len;
10149 *left -= len;
10150
10151 /* NUL-terminate the buffer as a convenience, if there is
10152 room. */
10153 if (*left)
10154 **buffer = '\0';
10155}
10156
10157/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10158 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10159 decrease *LEFT. Otherwise raise an error. */
10160
10161static void
10162remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10163 int len)
10164{
10165 if (2 * len > *left)
10166 error (_("Packet too long for target."));
10167
10168 bin2hex (bytes, *buffer, len);
10169 *buffer += 2 * len;
10170 *left -= 2 * len;
10171
10172 /* NUL-terminate the buffer as a convenience, if there is
10173 room. */
10174 if (*left)
10175 **buffer = '\0';
10176}
10177
10178/* If *LEFT is large enough, convert VALUE to hex and add it to
10179 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10180 decrease *LEFT. Otherwise raise an error. */
10181
10182static void
10183remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10184{
10185 int len = hexnumlen (value);
10186
10187 if (len > *left)
10188 error (_("Packet too long for target."));
10189
10190 hexnumstr (*buffer, value);
10191 *buffer += len;
10192 *left -= len;
10193
10194 /* NUL-terminate the buffer as a convenience, if there is
10195 room. */
10196 if (*left)
10197 **buffer = '\0';
10198}
10199
10200/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10201 value, *REMOTE_ERRNO to the remote error number or zero if none
10202 was included, and *ATTACHMENT to point to the start of the annex
10203 if any. The length of the packet isn't needed here; there may
10204 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10205
10206 Return 0 if the packet could be parsed, -1 if it could not. If
10207 -1 is returned, the other variables may not be initialized. */
10208
10209static int
10210remote_hostio_parse_result (char *buffer, int *retcode,
10211 int *remote_errno, char **attachment)
10212{
10213 char *p, *p2;
10214
10215 *remote_errno = 0;
10216 *attachment = NULL;
10217
10218 if (buffer[0] != 'F')
10219 return -1;
10220
10221 errno = 0;
10222 *retcode = strtol (&buffer[1], &p, 16);
10223 if (errno != 0 || p == &buffer[1])
10224 return -1;
10225
10226 /* Check for ",errno". */
10227 if (*p == ',')
10228 {
10229 errno = 0;
10230 *remote_errno = strtol (p + 1, &p2, 16);
10231 if (errno != 0 || p + 1 == p2)
10232 return -1;
10233 p = p2;
10234 }
10235
10236 /* Check for ";attachment". If there is no attachment, the
10237 packet should end here. */
10238 if (*p == ';')
10239 {
10240 *attachment = p + 1;
10241 return 0;
10242 }
10243 else if (*p == '\0')
10244 return 0;
10245 else
10246 return -1;
10247}
10248
10249/* Send a prepared I/O packet to the target and read its response.
10250 The prepared packet is in the global RS->BUF before this function
10251 is called, and the answer is there when we return.
10252
10253 COMMAND_BYTES is the length of the request to send, which may include
10254 binary data. WHICH_PACKET is the packet configuration to check
10255 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10256 is set to the error number and -1 is returned. Otherwise the value
10257 returned by the function is returned.
10258
10259 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10260 attachment is expected; an error will be reported if there's a
10261 mismatch. If one is found, *ATTACHMENT will be set to point into
10262 the packet buffer and *ATTACHMENT_LEN will be set to the
10263 attachment's length. */
10264
10265static int
10266remote_hostio_send_command (int command_bytes, int which_packet,
10267 int *remote_errno, char **attachment,
10268 int *attachment_len)
10269{
10270 struct remote_state *rs = get_remote_state ();
10271 int ret, bytes_read;
10272 char *attachment_tmp;
10273
25e4902b
AHJ
10274 if (!rs->remote_desc
10275 || packet_support (which_packet) == PACKET_DISABLE)
5796c8dc
SS
10276 {
10277 *remote_errno = FILEIO_ENOSYS;
10278 return -1;
10279 }
10280
10281 putpkt_binary (rs->buf, command_bytes);
10282 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10283
10284 /* If it timed out, something is wrong. Don't try to parse the
10285 buffer. */
10286 if (bytes_read < 0)
10287 {
10288 *remote_errno = FILEIO_EINVAL;
10289 return -1;
10290 }
10291
10292 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10293 {
10294 case PACKET_ERROR:
10295 *remote_errno = FILEIO_EINVAL;
10296 return -1;
10297 case PACKET_UNKNOWN:
10298 *remote_errno = FILEIO_ENOSYS;
10299 return -1;
10300 case PACKET_OK:
10301 break;
10302 }
10303
10304 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10305 &attachment_tmp))
10306 {
10307 *remote_errno = FILEIO_EINVAL;
10308 return -1;
10309 }
10310
10311 /* Make sure we saw an attachment if and only if we expected one. */
10312 if ((attachment_tmp == NULL && attachment != NULL)
10313 || (attachment_tmp != NULL && attachment == NULL))
10314 {
10315 *remote_errno = FILEIO_EINVAL;
10316 return -1;
10317 }
10318
10319 /* If an attachment was found, it must point into the packet buffer;
10320 work out how many bytes there were. */
10321 if (attachment_tmp != NULL)
10322 {
10323 *attachment = attachment_tmp;
10324 *attachment_len = bytes_read - (*attachment - rs->buf);
10325 }
10326
10327 return ret;
10328}
10329
25e4902b
AHJ
10330/* Invalidate the readahead cache. */
10331
10332static void
10333readahead_cache_invalidate (void)
10334{
10335 struct remote_state *rs = get_remote_state ();
10336
10337 rs->readahead_cache.fd = -1;
10338}
10339
10340/* Invalidate the readahead cache if it is holding data for FD. */
10341
10342static void
10343readahead_cache_invalidate_fd (int fd)
10344{
10345 struct remote_state *rs = get_remote_state ();
10346
10347 if (rs->readahead_cache.fd == fd)
10348 rs->readahead_cache.fd = -1;
10349}
10350
10351/* Set the filesystem remote_hostio functions that take FILENAME
10352 arguments will use. Return 0 on success, or -1 if an error
10353 occurs (and set *REMOTE_ERRNO). */
10354
10355static int
10356remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10357{
10358 struct remote_state *rs = get_remote_state ();
10359 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10360 char *p = rs->buf;
10361 int left = get_remote_packet_size () - 1;
10362 char arg[9];
10363 int ret;
10364
10365 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10366 return 0;
10367
10368 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10369 return 0;
10370
10371 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10372
10373 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10374 remote_buffer_add_string (&p, &left, arg);
10375
10376 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10377 remote_errno, NULL, NULL);
10378
10379 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10380 return 0;
10381
10382 if (ret == 0)
10383 rs->fs_pid = required_pid;
10384
10385 return ret;
10386}
10387
10388/* Implementation of to_fileio_open. */
5796c8dc
SS
10389
10390static int
25e4902b
AHJ
10391remote_hostio_open (struct target_ops *self,
10392 struct inferior *inf, const char *filename,
10393 int flags, int mode, int warn_if_slow,
5796c8dc
SS
10394 int *remote_errno)
10395{
10396 struct remote_state *rs = get_remote_state ();
10397 char *p = rs->buf;
10398 int left = get_remote_packet_size () - 1;
10399
25e4902b
AHJ
10400 if (warn_if_slow)
10401 {
10402 static int warning_issued = 0;
10403
10404 printf_unfiltered (_("Reading %s from remote target...\n"),
10405 filename);
10406
10407 if (!warning_issued)
10408 {
10409 warning (_("File transfers from remote targets can be slow."
10410 " Use \"set sysroot\" to access files locally"
10411 " instead."));
10412 warning_issued = 1;
10413 }
10414 }
10415
10416 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10417 return -1;
10418
5796c8dc
SS
10419 remote_buffer_add_string (&p, &left, "vFile:open:");
10420
10421 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10422 strlen (filename));
10423 remote_buffer_add_string (&p, &left, ",");
10424
10425 remote_buffer_add_int (&p, &left, flags);
10426 remote_buffer_add_string (&p, &left, ",");
10427
10428 remote_buffer_add_int (&p, &left, mode);
10429
10430 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10431 remote_errno, NULL, NULL);
10432}
10433
25e4902b 10434/* Implementation of to_fileio_pwrite. */
5796c8dc
SS
10435
10436static int
25e4902b
AHJ
10437remote_hostio_pwrite (struct target_ops *self,
10438 int fd, const gdb_byte *write_buf, int len,
5796c8dc
SS
10439 ULONGEST offset, int *remote_errno)
10440{
10441 struct remote_state *rs = get_remote_state ();
10442 char *p = rs->buf;
10443 int left = get_remote_packet_size ();
10444 int out_len;
10445
25e4902b
AHJ
10446 readahead_cache_invalidate_fd (fd);
10447
5796c8dc
SS
10448 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10449
10450 remote_buffer_add_int (&p, &left, fd);
10451 remote_buffer_add_string (&p, &left, ",");
10452
10453 remote_buffer_add_int (&p, &left, offset);
10454 remote_buffer_add_string (&p, &left, ",");
10455
25e4902b 10456 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
5796c8dc
SS
10457 get_remote_packet_size () - (p - rs->buf));
10458
10459 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10460 remote_errno, NULL, NULL);
10461}
10462
25e4902b
AHJ
10463/* Helper for the implementation of to_fileio_pread. Read the file
10464 from the remote side with vFile:pread. */
5796c8dc
SS
10465
10466static int
25e4902b
AHJ
10467remote_hostio_pread_vFile (struct target_ops *self,
10468 int fd, gdb_byte *read_buf, int len,
10469 ULONGEST offset, int *remote_errno)
5796c8dc
SS
10470{
10471 struct remote_state *rs = get_remote_state ();
10472 char *p = rs->buf;
10473 char *attachment;
10474 int left = get_remote_packet_size ();
10475 int ret, attachment_len;
10476 int read_len;
10477
10478 remote_buffer_add_string (&p, &left, "vFile:pread:");
10479
10480 remote_buffer_add_int (&p, &left, fd);
10481 remote_buffer_add_string (&p, &left, ",");
10482
10483 remote_buffer_add_int (&p, &left, len);
10484 remote_buffer_add_string (&p, &left, ",");
10485
10486 remote_buffer_add_int (&p, &left, offset);
10487
10488 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10489 remote_errno, &attachment,
10490 &attachment_len);
10491
10492 if (ret < 0)
10493 return ret;
10494
25e4902b 10495 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
5796c8dc
SS
10496 read_buf, len);
10497 if (read_len != ret)
10498 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10499
10500 return ret;
10501}
10502
25e4902b
AHJ
10503/* Serve pread from the readahead cache. Returns number of bytes
10504 read, or 0 if the request can't be served from the cache. */
10505
10506static int
10507remote_hostio_pread_from_cache (struct remote_state *rs,
10508 int fd, gdb_byte *read_buf, size_t len,
10509 ULONGEST offset)
10510{
10511 struct readahead_cache *cache = &rs->readahead_cache;
10512
10513 if (cache->fd == fd
10514 && cache->offset <= offset
10515 && offset < cache->offset + cache->bufsize)
10516 {
10517 ULONGEST max = cache->offset + cache->bufsize;
10518
10519 if (offset + len > max)
10520 len = max - offset;
10521
10522 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10523 return len;
10524 }
10525
10526 return 0;
10527}
10528
10529/* Implementation of to_fileio_pread. */
10530
10531static int
10532remote_hostio_pread (struct target_ops *self,
10533 int fd, gdb_byte *read_buf, int len,
10534 ULONGEST offset, int *remote_errno)
10535{
10536 int ret;
10537 struct remote_state *rs = get_remote_state ();
10538 struct readahead_cache *cache = &rs->readahead_cache;
10539
10540 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10541 if (ret > 0)
10542 {
10543 cache->hit_count++;
10544
10545 if (remote_debug)
10546 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10547 pulongest (cache->hit_count));
10548 return ret;
10549 }
10550
10551 cache->miss_count++;
10552 if (remote_debug)
10553 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10554 pulongest (cache->miss_count));
10555
10556 cache->fd = fd;
10557 cache->offset = offset;
10558 cache->bufsize = get_remote_packet_size ();
10559 cache->buf = xrealloc (cache->buf, cache->bufsize);
10560
10561 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10562 cache->offset, remote_errno);
10563 if (ret <= 0)
10564 {
10565 readahead_cache_invalidate_fd (fd);
10566 return ret;
10567 }
10568
10569 cache->bufsize = ret;
10570 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10571}
10572
10573/* Implementation of to_fileio_close. */
5796c8dc
SS
10574
10575static int
25e4902b 10576remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
5796c8dc
SS
10577{
10578 struct remote_state *rs = get_remote_state ();
10579 char *p = rs->buf;
10580 int left = get_remote_packet_size () - 1;
10581
25e4902b
AHJ
10582 readahead_cache_invalidate_fd (fd);
10583
5796c8dc
SS
10584 remote_buffer_add_string (&p, &left, "vFile:close:");
10585
10586 remote_buffer_add_int (&p, &left, fd);
10587
10588 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10589 remote_errno, NULL, NULL);
10590}
10591
25e4902b 10592/* Implementation of to_fileio_unlink. */
5796c8dc
SS
10593
10594static int
25e4902b
AHJ
10595remote_hostio_unlink (struct target_ops *self,
10596 struct inferior *inf, const char *filename,
10597 int *remote_errno)
5796c8dc
SS
10598{
10599 struct remote_state *rs = get_remote_state ();
10600 char *p = rs->buf;
10601 int left = get_remote_packet_size () - 1;
10602
25e4902b
AHJ
10603 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10604 return -1;
10605
5796c8dc
SS
10606 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10607
10608 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10609 strlen (filename));
10610
10611 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10612 remote_errno, NULL, NULL);
10613}
10614
25e4902b 10615/* Implementation of to_fileio_readlink. */
ef5ccd6c
JM
10616
10617static char *
25e4902b
AHJ
10618remote_hostio_readlink (struct target_ops *self,
10619 struct inferior *inf, const char *filename,
10620 int *remote_errno)
ef5ccd6c
JM
10621{
10622 struct remote_state *rs = get_remote_state ();
10623 char *p = rs->buf;
10624 char *attachment;
10625 int left = get_remote_packet_size ();
10626 int len, attachment_len;
10627 int read_len;
10628 char *ret;
10629
25e4902b
AHJ
10630 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10631 return NULL;
10632
ef5ccd6c
JM
10633 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10634
10635 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10636 strlen (filename));
10637
25e4902b
AHJ
10638 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10639 remote_errno, &attachment,
10640 &attachment_len);
10641
10642 if (len < 0)
10643 return NULL;
10644
10645 ret = xmalloc (len + 1);
10646
10647 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10648 (gdb_byte *) ret, len);
10649 if (read_len != len)
10650 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10651
10652 ret[len] = '\0';
10653 return ret;
10654}
10655
10656/* Implementation of to_fileio_fstat. */
10657
10658static int
10659remote_hostio_fstat (struct target_ops *self,
10660 int fd, struct stat *st,
10661 int *remote_errno)
10662{
10663 struct remote_state *rs = get_remote_state ();
10664 char *p = rs->buf;
10665 int left = get_remote_packet_size ();
10666 int attachment_len, ret;
10667 char *attachment;
10668 struct fio_stat fst;
10669 int read_len;
10670
10671 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10672
10673 remote_buffer_add_int (&p, &left, fd);
10674
10675 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10676 remote_errno, &attachment,
10677 &attachment_len);
10678 if (ret < 0)
10679 {
10680 if (*remote_errno != FILEIO_ENOSYS)
10681 return ret;
10682
10683 /* Strictly we should return -1, ENOSYS here, but when
10684 "set sysroot remote:" was implemented in August 2008
10685 BFD's need for a stat function was sidestepped with
10686 this hack. This was not remedied until March 2015
10687 so we retain the previous behavior to avoid breaking
10688 compatibility.
10689
10690 Note that the memset is a March 2015 addition; older
10691 GDBs set st_size *and nothing else* so the structure
10692 would have garbage in all other fields. This might
10693 break something but retaining the previous behavior
10694 here would be just too wrong. */
10695
10696 memset (st, 0, sizeof (struct stat));
10697 st->st_size = INT_MAX;
10698 return 0;
10699 }
10700
10701 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10702 (gdb_byte *) &fst, sizeof (fst));
10703
10704 if (read_len != ret)
10705 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10706
10707 if (read_len != sizeof (fst))
10708 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10709 read_len, (int) sizeof (fst));
10710
10711 remote_fileio_to_host_stat (&fst, st);
10712
10713 return 0;
10714}
10715
10716/* Implementation of to_filesystem_is_local. */
10717
10718static int
10719remote_filesystem_is_local (struct target_ops *self)
10720{
10721 /* Valgrind GDB presents itself as a remote target but works
10722 on the local filesystem: it does not implement remote get
10723 and users are not expected to set a sysroot. To handle
10724 this case we treat the remote filesystem as local if the
10725 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10726 does not support vFile:open. */
10727 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
10728 {
10729 enum packet_support ps = packet_support (PACKET_vFile_open);
10730
10731 if (ps == PACKET_SUPPORT_UNKNOWN)
10732 {
10733 int fd, remote_errno;
10734
10735 /* Try opening a file to probe support. The supplied
10736 filename is irrelevant, we only care about whether
10737 the stub recognizes the packet or not. */
10738 fd = remote_hostio_open (self, NULL, "just probing",
10739 FILEIO_O_RDONLY, 0700, 0,
10740 &remote_errno);
10741
10742 if (fd >= 0)
10743 remote_hostio_close (self, fd, &remote_errno);
ef5ccd6c 10744
25e4902b
AHJ
10745 ps = packet_support (PACKET_vFile_open);
10746 }
ef5ccd6c 10747
25e4902b
AHJ
10748 if (ps == PACKET_DISABLE)
10749 {
10750 static int warning_issued = 0;
ef5ccd6c 10751
25e4902b
AHJ
10752 if (!warning_issued)
10753 {
10754 warning (_("remote target does not support file"
10755 " transfer, attempting to access files"
10756 " from local filesystem."));
10757 warning_issued = 1;
10758 }
ef5ccd6c 10759
25e4902b
AHJ
10760 return 1;
10761 }
10762 }
10763
10764 return 0;
ef5ccd6c
JM
10765}
10766
5796c8dc
SS
10767static int
10768remote_fileio_errno_to_host (int errnum)
10769{
10770 switch (errnum)
10771 {
10772 case FILEIO_EPERM:
10773 return EPERM;
10774 case FILEIO_ENOENT:
10775 return ENOENT;
10776 case FILEIO_EINTR:
10777 return EINTR;
10778 case FILEIO_EIO:
10779 return EIO;
10780 case FILEIO_EBADF:
10781 return EBADF;
10782 case FILEIO_EACCES:
10783 return EACCES;
10784 case FILEIO_EFAULT:
10785 return EFAULT;
10786 case FILEIO_EBUSY:
10787 return EBUSY;
10788 case FILEIO_EEXIST:
10789 return EEXIST;
10790 case FILEIO_ENODEV:
10791 return ENODEV;
10792 case FILEIO_ENOTDIR:
10793 return ENOTDIR;
10794 case FILEIO_EISDIR:
10795 return EISDIR;
10796 case FILEIO_EINVAL:
10797 return EINVAL;
10798 case FILEIO_ENFILE:
10799 return ENFILE;
10800 case FILEIO_EMFILE:
10801 return EMFILE;
10802 case FILEIO_EFBIG:
10803 return EFBIG;
10804 case FILEIO_ENOSPC:
10805 return ENOSPC;
10806 case FILEIO_ESPIPE:
10807 return ESPIPE;
10808 case FILEIO_EROFS:
10809 return EROFS;
10810 case FILEIO_ENOSYS:
10811 return ENOSYS;
10812 case FILEIO_ENAMETOOLONG:
10813 return ENAMETOOLONG;
10814 }
10815 return -1;
10816}
10817
10818static char *
10819remote_hostio_error (int errnum)
10820{
10821 int host_error = remote_fileio_errno_to_host (errnum);
10822
10823 if (host_error == -1)
10824 error (_("Unknown remote I/O error %d"), errnum);
10825 else
10826 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10827}
10828
10829static void
10830remote_hostio_close_cleanup (void *opaque)
10831{
10832 int fd = *(int *) opaque;
10833 int remote_errno;
10834
25e4902b 10835 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
5796c8dc
SS
10836}
10837
10838void
10839remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10840{
10841 struct cleanup *back_to, *close_cleanup;
10842 int retcode, fd, remote_errno, bytes, io_size;
10843 FILE *file;
10844 gdb_byte *buffer;
10845 int bytes_in_buffer;
10846 int saw_eof;
10847 ULONGEST offset;
25e4902b 10848 struct remote_state *rs = get_remote_state ();
5796c8dc 10849
25e4902b 10850 if (!rs->remote_desc)
5796c8dc
SS
10851 error (_("command can only be used with remote target"));
10852
25e4902b 10853 file = gdb_fopen_cloexec (local_file, "rb");
5796c8dc
SS
10854 if (file == NULL)
10855 perror_with_name (local_file);
10856 back_to = make_cleanup_fclose (file);
10857
25e4902b
AHJ
10858 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
10859 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
5796c8dc 10860 | FILEIO_O_TRUNC),
25e4902b 10861 0700, 0, &remote_errno);
5796c8dc
SS
10862 if (fd == -1)
10863 remote_hostio_error (remote_errno);
10864
10865 /* Send up to this many bytes at once. They won't all fit in the
10866 remote packet limit, so we'll transfer slightly fewer. */
10867 io_size = get_remote_packet_size ();
10868 buffer = xmalloc (io_size);
10869 make_cleanup (xfree, buffer);
10870
10871 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10872
10873 bytes_in_buffer = 0;
10874 saw_eof = 0;
10875 offset = 0;
10876 while (bytes_in_buffer || !saw_eof)
10877 {
10878 if (!saw_eof)
10879 {
c50c785c
JM
10880 bytes = fread (buffer + bytes_in_buffer, 1,
10881 io_size - bytes_in_buffer,
5796c8dc
SS
10882 file);
10883 if (bytes == 0)
10884 {
10885 if (ferror (file))
10886 error (_("Error reading %s."), local_file);
10887 else
10888 {
10889 /* EOF. Unless there is something still in the
10890 buffer from the last iteration, we are done. */
10891 saw_eof = 1;
10892 if (bytes_in_buffer == 0)
10893 break;
10894 }
10895 }
10896 }
10897 else
10898 bytes = 0;
10899
10900 bytes += bytes_in_buffer;
10901 bytes_in_buffer = 0;
10902
25e4902b
AHJ
10903 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10904 fd, buffer, bytes,
c50c785c 10905 offset, &remote_errno);
5796c8dc
SS
10906
10907 if (retcode < 0)
10908 remote_hostio_error (remote_errno);
10909 else if (retcode == 0)
10910 error (_("Remote write of %d bytes returned 0!"), bytes);
10911 else if (retcode < bytes)
10912 {
10913 /* Short write. Save the rest of the read data for the next
10914 write. */
10915 bytes_in_buffer = bytes - retcode;
10916 memmove (buffer, buffer + retcode, bytes_in_buffer);
10917 }
10918
10919 offset += retcode;
10920 }
10921
10922 discard_cleanups (close_cleanup);
25e4902b 10923 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
5796c8dc
SS
10924 remote_hostio_error (remote_errno);
10925
10926 if (from_tty)
10927 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10928 do_cleanups (back_to);
10929}
10930
10931void
10932remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10933{
10934 struct cleanup *back_to, *close_cleanup;
10935 int fd, remote_errno, bytes, io_size;
10936 FILE *file;
10937 gdb_byte *buffer;
10938 ULONGEST offset;
25e4902b 10939 struct remote_state *rs = get_remote_state ();
5796c8dc 10940
25e4902b 10941 if (!rs->remote_desc)
5796c8dc
SS
10942 error (_("command can only be used with remote target"));
10943
25e4902b
AHJ
10944 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
10945 remote_file, FILEIO_O_RDONLY, 0, 0,
10946 &remote_errno);
5796c8dc
SS
10947 if (fd == -1)
10948 remote_hostio_error (remote_errno);
10949
25e4902b 10950 file = gdb_fopen_cloexec (local_file, "wb");
5796c8dc
SS
10951 if (file == NULL)
10952 perror_with_name (local_file);
10953 back_to = make_cleanup_fclose (file);
10954
10955 /* Send up to this many bytes at once. They won't all fit in the
10956 remote packet limit, so we'll transfer slightly fewer. */
10957 io_size = get_remote_packet_size ();
10958 buffer = xmalloc (io_size);
10959 make_cleanup (xfree, buffer);
10960
10961 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10962
10963 offset = 0;
10964 while (1)
10965 {
25e4902b
AHJ
10966 bytes = remote_hostio_pread (find_target_at (process_stratum),
10967 fd, buffer, io_size, offset, &remote_errno);
5796c8dc
SS
10968 if (bytes == 0)
10969 /* Success, but no bytes, means end-of-file. */
10970 break;
10971 if (bytes == -1)
10972 remote_hostio_error (remote_errno);
10973
10974 offset += bytes;
10975
10976 bytes = fwrite (buffer, 1, bytes, file);
10977 if (bytes == 0)
10978 perror_with_name (local_file);
10979 }
10980
10981 discard_cleanups (close_cleanup);
25e4902b 10982 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
5796c8dc
SS
10983 remote_hostio_error (remote_errno);
10984
10985 if (from_tty)
10986 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10987 do_cleanups (back_to);
10988}
10989
10990void
10991remote_file_delete (const char *remote_file, int from_tty)
10992{
10993 int retcode, remote_errno;
25e4902b 10994 struct remote_state *rs = get_remote_state ();
5796c8dc 10995
25e4902b 10996 if (!rs->remote_desc)
5796c8dc
SS
10997 error (_("command can only be used with remote target"));
10998
25e4902b
AHJ
10999 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11000 NULL, remote_file, &remote_errno);
5796c8dc
SS
11001 if (retcode == -1)
11002 remote_hostio_error (remote_errno);
11003
11004 if (from_tty)
11005 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11006}
11007
11008static void
11009remote_put_command (char *args, int from_tty)
11010{
11011 struct cleanup *back_to;
11012 char **argv;
11013
11014 if (args == NULL)
11015 error_no_arg (_("file to put"));
11016
11017 argv = gdb_buildargv (args);
11018 back_to = make_cleanup_freeargv (argv);
11019 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11020 error (_("Invalid parameters to remote put"));
11021
11022 remote_file_put (argv[0], argv[1], from_tty);
11023
11024 do_cleanups (back_to);
11025}
11026
11027static void
11028remote_get_command (char *args, int from_tty)
11029{
11030 struct cleanup *back_to;
11031 char **argv;
11032
11033 if (args == NULL)
11034 error_no_arg (_("file to get"));
11035
11036 argv = gdb_buildargv (args);
11037 back_to = make_cleanup_freeargv (argv);
11038 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11039 error (_("Invalid parameters to remote get"));
11040
11041 remote_file_get (argv[0], argv[1], from_tty);
11042
11043 do_cleanups (back_to);
11044}
11045
11046static void
11047remote_delete_command (char *args, int from_tty)
11048{
11049 struct cleanup *back_to;
11050 char **argv;
11051
11052 if (args == NULL)
11053 error_no_arg (_("file to delete"));
11054
11055 argv = gdb_buildargv (args);
11056 back_to = make_cleanup_freeargv (argv);
11057 if (argv[0] == NULL || argv[1] != NULL)
11058 error (_("Invalid parameters to remote delete"));
11059
11060 remote_file_delete (argv[0], from_tty);
11061
11062 do_cleanups (back_to);
11063}
11064
11065static void
11066remote_command (char *args, int from_tty)
11067{
25e4902b 11068 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
5796c8dc
SS
11069}
11070
11071static int
25e4902b 11072remote_can_execute_reverse (struct target_ops *self)
5796c8dc 11073{
25e4902b
AHJ
11074 if (packet_support (PACKET_bs) == PACKET_ENABLE
11075 || packet_support (PACKET_bc) == PACKET_ENABLE)
5796c8dc
SS
11076 return 1;
11077 else
11078 return 0;
11079}
11080
11081static int
25e4902b 11082remote_supports_non_stop (struct target_ops *self)
5796c8dc
SS
11083{
11084 return 1;
11085}
11086
a45ae5f8 11087static int
25e4902b 11088remote_supports_disable_randomization (struct target_ops *self)
a45ae5f8
JM
11089{
11090 /* Only supported in extended mode. */
11091 return 0;
11092}
11093
5796c8dc 11094static int
25e4902b 11095remote_supports_multi_process (struct target_ops *self)
5796c8dc
SS
11096{
11097 struct remote_state *rs = get_remote_state ();
cf7f2e2d 11098
ef5ccd6c
JM
11099 /* Only extended-remote handles being attached to multiple
11100 processes, even though plain remote can use the multi-process
11101 thread id extensions, so that GDB knows the target process's
11102 PID. */
11103 return rs->extended && remote_multi_process_p (rs);
5796c8dc
SS
11104}
11105
ef5ccd6c 11106static int
5796c8dc
SS
11107remote_supports_cond_tracepoints (void)
11108{
25e4902b 11109 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
5796c8dc
SS
11110}
11111
ef5ccd6c 11112static int
25e4902b 11113remote_supports_cond_breakpoints (struct target_ops *self)
ef5ccd6c 11114{
25e4902b 11115 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
ef5ccd6c
JM
11116}
11117
11118static int
cf7f2e2d
JM
11119remote_supports_fast_tracepoints (void)
11120{
25e4902b 11121 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
cf7f2e2d
JM
11122}
11123
11124static int
11125remote_supports_static_tracepoints (void)
11126{
25e4902b 11127 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
cf7f2e2d
JM
11128}
11129
a45ae5f8
JM
11130static int
11131remote_supports_install_in_trace (void)
11132{
25e4902b 11133 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
a45ae5f8
JM
11134}
11135
11136static int
25e4902b 11137remote_supports_enable_disable_tracepoint (struct target_ops *self)
a45ae5f8 11138{
25e4902b
AHJ
11139 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11140 == PACKET_ENABLE);
a45ae5f8
JM
11141}
11142
11143static int
25e4902b 11144remote_supports_string_tracing (struct target_ops *self)
a45ae5f8 11145{
25e4902b 11146 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
a45ae5f8
JM
11147}
11148
ef5ccd6c 11149static int
25e4902b 11150remote_can_run_breakpoint_commands (struct target_ops *self)
ef5ccd6c 11151{
25e4902b 11152 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
ef5ccd6c
JM
11153}
11154
cf7f2e2d 11155static void
25e4902b 11156remote_trace_init (struct target_ops *self)
cf7f2e2d
JM
11157{
11158 putpkt ("QTinit");
11159 remote_get_noisy_reply (&target_buf, &target_buf_size);
11160 if (strcmp (target_buf, "OK") != 0)
11161 error (_("Target does not support this command."));
11162}
11163
11164static void free_actions_list (char **actions_list);
11165static void free_actions_list_cleanup_wrapper (void *);
11166static void
11167free_actions_list_cleanup_wrapper (void *al)
11168{
11169 free_actions_list (al);
11170}
11171
11172static void
11173free_actions_list (char **actions_list)
11174{
11175 int ndx;
11176
11177 if (actions_list == 0)
11178 return;
11179
11180 for (ndx = 0; actions_list[ndx]; ndx++)
11181 xfree (actions_list[ndx]);
11182
11183 xfree (actions_list);
11184}
11185
11186/* Recursive routine to walk through command list including loops, and
11187 download packets for each command. */
11188
11189static void
11190remote_download_command_source (int num, ULONGEST addr,
11191 struct command_line *cmds)
11192{
11193 struct remote_state *rs = get_remote_state ();
11194 struct command_line *cmd;
11195
11196 for (cmd = cmds; cmd; cmd = cmd->next)
11197 {
c50c785c 11198 QUIT; /* Allow user to bail out with ^C. */
cf7f2e2d
JM
11199 strcpy (rs->buf, "QTDPsrc:");
11200 encode_source_string (num, addr, "cmd", cmd->line,
11201 rs->buf + strlen (rs->buf),
11202 rs->buf_size - strlen (rs->buf));
11203 putpkt (rs->buf);
11204 remote_get_noisy_reply (&target_buf, &target_buf_size);
11205 if (strcmp (target_buf, "OK"))
11206 warning (_("Target does not support source download."));
11207
11208 if (cmd->control_type == while_control
11209 || cmd->control_type == while_stepping_control)
11210 {
11211 remote_download_command_source (num, addr, *cmd->body_list);
11212
c50c785c 11213 QUIT; /* Allow user to bail out with ^C. */
cf7f2e2d
JM
11214 strcpy (rs->buf, "QTDPsrc:");
11215 encode_source_string (num, addr, "cmd", "end",
11216 rs->buf + strlen (rs->buf),
11217 rs->buf_size - strlen (rs->buf));
11218 putpkt (rs->buf);
11219 remote_get_noisy_reply (&target_buf, &target_buf_size);
11220 if (strcmp (target_buf, "OK"))
11221 warning (_("Target does not support source download."));
11222 }
11223 }
11224}
11225
11226static void
25e4902b 11227remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
cf7f2e2d 11228{
ef5ccd6c 11229#define BUF_SIZE 2048
a45ae5f8 11230
cf7f2e2d
JM
11231 CORE_ADDR tpaddr;
11232 char addrbuf[40];
ef5ccd6c 11233 char buf[BUF_SIZE];
cf7f2e2d
JM
11234 char **tdp_actions;
11235 char **stepping_actions;
11236 int ndx;
11237 struct cleanup *old_chain = NULL;
11238 struct agent_expr *aexpr;
11239 struct cleanup *aexpr_chain = NULL;
11240 char *pkt;
a45ae5f8
JM
11241 struct breakpoint *b = loc->owner;
11242 struct tracepoint *t = (struct tracepoint *) b;
11243
25e4902b 11244 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
a45ae5f8
JM
11245 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11246 tdp_actions);
11247 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11248 stepping_actions);
11249
11250 tpaddr = loc->address;
11251 sprintf_vma (addrbuf, tpaddr);
ef5ccd6c
JM
11252 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11253 addrbuf, /* address */
11254 (b->enable_state == bp_enabled ? 'E' : 'D'),
11255 t->step_count, t->pass_count);
a45ae5f8
JM
11256 /* Fast tracepoints are mostly handled by the target, but we can
11257 tell the target how big of an instruction block should be moved
11258 around. */
11259 if (b->type == bp_fast_tracepoint)
11260 {
11261 /* Only test for support at download time; we may not know
11262 target capabilities at definition time. */
11263 if (remote_supports_fast_tracepoints ())
cf7f2e2d 11264 {
a45ae5f8 11265 int isize;
cf7f2e2d 11266
ef5ccd6c 11267 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
a45ae5f8 11268 tpaddr, &isize, NULL))
ef5ccd6c
JM
11269 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11270 isize);
cf7f2e2d 11271 else
a45ae5f8
JM
11272 /* If it passed validation at definition but fails now,
11273 something is very wrong. */
11274 internal_error (__FILE__, __LINE__,
11275 _("Fast tracepoint not "
11276 "valid during download"));
cf7f2e2d 11277 }
a45ae5f8
JM
11278 else
11279 /* Fast tracepoints are functionally identical to regular
11280 tracepoints, so don't take lack of support as a reason to
11281 give up on the trace run. */
11282 warning (_("Target does not support fast tracepoints, "
11283 "downloading %d as regular tracepoint"), b->number);
11284 }
11285 else if (b->type == bp_static_tracepoint)
11286 {
11287 /* Only test for support at download time; we may not know
11288 target capabilities at definition time. */
11289 if (remote_supports_static_tracepoints ())
cf7f2e2d 11290 {
a45ae5f8 11291 struct static_tracepoint_marker marker;
cf7f2e2d 11292
a45ae5f8
JM
11293 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11294 strcat (buf, ":S");
cf7f2e2d 11295 else
a45ae5f8 11296 error (_("Static tracepoint not valid during download"));
cf7f2e2d 11297 }
a45ae5f8
JM
11298 else
11299 /* Fast tracepoints are functionally identical to regular
11300 tracepoints, so don't take lack of support as a reason
11301 to give up on the trace run. */
11302 error (_("Target does not support static tracepoints"));
11303 }
11304 /* If the tracepoint has a conditional, make it into an agent
11305 expression and append to the definition. */
11306 if (loc->cond)
11307 {
11308 /* Only test support at download time, we may not know target
11309 capabilities at definition time. */
11310 if (remote_supports_cond_tracepoints ())
cf7f2e2d 11311 {
a45ae5f8
JM
11312 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11313 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
ef5ccd6c
JM
11314 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11315 aexpr->len);
a45ae5f8
JM
11316 pkt = buf + strlen (buf);
11317 for (ndx = 0; ndx < aexpr->len; ++ndx)
11318 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11319 *pkt = '\0';
11320 do_cleanups (aexpr_chain);
cf7f2e2d 11321 }
a45ae5f8
JM
11322 else
11323 warning (_("Target does not support conditional tracepoints, "
11324 "ignoring tp %d cond"), b->number);
11325 }
cf7f2e2d 11326
a45ae5f8
JM
11327 if (b->commands || *default_collect)
11328 strcat (buf, "-");
11329 putpkt (buf);
11330 remote_get_noisy_reply (&target_buf, &target_buf_size);
11331 if (strcmp (target_buf, "OK"))
11332 error (_("Target does not support tracepoints."));
cf7f2e2d 11333
a45ae5f8
JM
11334 /* do_single_steps (t); */
11335 if (tdp_actions)
11336 {
11337 for (ndx = 0; tdp_actions[ndx]; ndx++)
cf7f2e2d 11338 {
a45ae5f8 11339 QUIT; /* Allow user to bail out with ^C. */
ef5ccd6c
JM
11340 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11341 b->number, addrbuf, /* address */
11342 tdp_actions[ndx],
11343 ((tdp_actions[ndx + 1] || stepping_actions)
11344 ? '-' : 0));
a45ae5f8
JM
11345 putpkt (buf);
11346 remote_get_noisy_reply (&target_buf,
11347 &target_buf_size);
11348 if (strcmp (target_buf, "OK"))
11349 error (_("Error on target while setting tracepoints."));
cf7f2e2d 11350 }
a45ae5f8
JM
11351 }
11352 if (stepping_actions)
11353 {
11354 for (ndx = 0; stepping_actions[ndx]; ndx++)
cf7f2e2d 11355 {
a45ae5f8 11356 QUIT; /* Allow user to bail out with ^C. */
ef5ccd6c
JM
11357 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11358 b->number, addrbuf, /* address */
11359 ((ndx == 0) ? "S" : ""),
11360 stepping_actions[ndx],
11361 (stepping_actions[ndx + 1] ? "-" : ""));
a45ae5f8
JM
11362 putpkt (buf);
11363 remote_get_noisy_reply (&target_buf,
11364 &target_buf_size);
11365 if (strcmp (target_buf, "OK"))
11366 error (_("Error on target while setting tracepoints."));
cf7f2e2d 11367 }
a45ae5f8 11368 }
cf7f2e2d 11369
25e4902b 11370 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
a45ae5f8
JM
11371 {
11372 if (b->addr_string)
cf7f2e2d 11373 {
a45ae5f8
JM
11374 strcpy (buf, "QTDPsrc:");
11375 encode_source_string (b->number, loc->address,
11376 "at", b->addr_string, buf + strlen (buf),
11377 2048 - strlen (buf));
cf7f2e2d 11378
a45ae5f8
JM
11379 putpkt (buf);
11380 remote_get_noisy_reply (&target_buf, &target_buf_size);
11381 if (strcmp (target_buf, "OK"))
11382 warning (_("Target does not support source download."));
cf7f2e2d 11383 }
a45ae5f8
JM
11384 if (b->cond_string)
11385 {
11386 strcpy (buf, "QTDPsrc:");
11387 encode_source_string (b->number, loc->address,
11388 "cond", b->cond_string, buf + strlen (buf),
11389 2048 - strlen (buf));
11390 putpkt (buf);
11391 remote_get_noisy_reply (&target_buf, &target_buf_size);
11392 if (strcmp (target_buf, "OK"))
11393 warning (_("Target does not support source download."));
11394 }
11395 remote_download_command_source (b->number, loc->address,
11396 breakpoint_commands (b));
cf7f2e2d 11397 }
a45ae5f8
JM
11398
11399 do_cleanups (old_chain);
11400}
11401
11402static int
25e4902b 11403remote_can_download_tracepoint (struct target_ops *self)
a45ae5f8
JM
11404{
11405 struct remote_state *rs = get_remote_state ();
11406 struct trace_status *ts;
11407 int status;
11408
11409 /* Don't try to install tracepoints until we've relocated our
11410 symbols, and fetched and merged the target's tracepoint list with
11411 ours. */
11412 if (rs->starting_up)
11413 return 0;
11414
11415 ts = current_trace_status ();
25e4902b 11416 status = remote_get_trace_status (self, ts);
a45ae5f8
JM
11417
11418 if (status == -1 || !ts->running_known || !ts->running)
11419 return 0;
11420
11421 /* If we are in a tracing experiment, but remote stub doesn't support
11422 installing tracepoint in trace, we have to return. */
11423 if (!remote_supports_install_in_trace ())
11424 return 0;
11425
11426 return 1;
cf7f2e2d
JM
11427}
11428
a45ae5f8 11429
cf7f2e2d 11430static void
25e4902b
AHJ
11431remote_download_trace_state_variable (struct target_ops *self,
11432 struct trace_state_variable *tsv)
cf7f2e2d
JM
11433{
11434 struct remote_state *rs = get_remote_state ();
11435 char *p;
11436
ef5ccd6c
JM
11437 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11438 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11439 tsv->builtin);
cf7f2e2d
JM
11440 p = rs->buf + strlen (rs->buf);
11441 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11442 error (_("Trace state variable name too long for tsv definition packet"));
25e4902b 11443 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
cf7f2e2d
JM
11444 *p++ = '\0';
11445 putpkt (rs->buf);
11446 remote_get_noisy_reply (&target_buf, &target_buf_size);
11447 if (*target_buf == '\0')
11448 error (_("Target does not support this command."));
11449 if (strcmp (target_buf, "OK") != 0)
11450 error (_("Error on target while downloading trace state variable."));
11451}
11452
a45ae5f8 11453static void
25e4902b
AHJ
11454remote_enable_tracepoint (struct target_ops *self,
11455 struct bp_location *location)
a45ae5f8
JM
11456{
11457 struct remote_state *rs = get_remote_state ();
11458 char addr_buf[40];
11459
11460 sprintf_vma (addr_buf, location->address);
ef5ccd6c
JM
11461 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11462 location->owner->number, addr_buf);
a45ae5f8
JM
11463 putpkt (rs->buf);
11464 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11465 if (*rs->buf == '\0')
11466 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11467 if (strcmp (rs->buf, "OK") != 0)
11468 error (_("Error on target while enabling tracepoint."));
11469}
11470
11471static void
25e4902b
AHJ
11472remote_disable_tracepoint (struct target_ops *self,
11473 struct bp_location *location)
a45ae5f8
JM
11474{
11475 struct remote_state *rs = get_remote_state ();
11476 char addr_buf[40];
11477
11478 sprintf_vma (addr_buf, location->address);
ef5ccd6c
JM
11479 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11480 location->owner->number, addr_buf);
a45ae5f8
JM
11481 putpkt (rs->buf);
11482 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11483 if (*rs->buf == '\0')
11484 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11485 if (strcmp (rs->buf, "OK") != 0)
11486 error (_("Error on target while disabling tracepoint."));
11487}
11488
cf7f2e2d 11489static void
25e4902b 11490remote_trace_set_readonly_regions (struct target_ops *self)
cf7f2e2d
JM
11491{
11492 asection *s;
ef5ccd6c 11493 bfd *abfd = NULL;
cf7f2e2d 11494 bfd_size_type size;
c50c785c 11495 bfd_vma vma;
cf7f2e2d 11496 int anysecs = 0;
c50c785c 11497 int offset = 0;
cf7f2e2d
JM
11498
11499 if (!exec_bfd)
11500 return; /* No information to give. */
11501
11502 strcpy (target_buf, "QTro");
ef5ccd6c 11503 offset = strlen (target_buf);
cf7f2e2d
JM
11504 for (s = exec_bfd->sections; s; s = s->next)
11505 {
11506 char tmp1[40], tmp2[40];
c50c785c 11507 int sec_length;
cf7f2e2d
JM
11508
11509 if ((s->flags & SEC_LOAD) == 0 ||
c50c785c 11510 /* (s->flags & SEC_CODE) == 0 || */
cf7f2e2d
JM
11511 (s->flags & SEC_READONLY) == 0)
11512 continue;
11513
11514 anysecs = 1;
ef5ccd6c 11515 vma = bfd_get_section_vma (abfd, s);
cf7f2e2d 11516 size = bfd_get_section_size (s);
c50c785c
JM
11517 sprintf_vma (tmp1, vma);
11518 sprintf_vma (tmp2, vma + size);
11519 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11520 if (offset + sec_length + 1 > target_buf_size)
11521 {
25e4902b 11522 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
c50c785c
JM
11523 warning (_("\
11524Too many sections for read-only sections definition packet."));
11525 break;
11526 }
ef5ccd6c
JM
11527 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11528 tmp1, tmp2);
c50c785c 11529 offset += sec_length;
cf7f2e2d
JM
11530 }
11531 if (anysecs)
11532 {
11533 putpkt (target_buf);
11534 getpkt (&target_buf, &target_buf_size, 0);
11535 }
11536}
11537
11538static void
25e4902b 11539remote_trace_start (struct target_ops *self)
cf7f2e2d
JM
11540{
11541 putpkt ("QTStart");
11542 remote_get_noisy_reply (&target_buf, &target_buf_size);
11543 if (*target_buf == '\0')
11544 error (_("Target does not support this command."));
11545 if (strcmp (target_buf, "OK") != 0)
11546 error (_("Bogus reply from target: %s"), target_buf);
11547}
11548
11549static int
25e4902b 11550remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
cf7f2e2d 11551{
c50c785c
JM
11552 /* Initialize it just to avoid a GCC false warning. */
11553 char *p = NULL;
11554 /* FIXME we need to get register block size some other way. */
cf7f2e2d 11555 extern int trace_regblock_size;
25e4902b
AHJ
11556 enum packet_result result;
11557
11558 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11559 return -1;
cf7f2e2d
JM
11560
11561 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11562
11563 putpkt ("qTStatus");
c50c785c 11564
25e4902b 11565 TRY
c50c785c
JM
11566 {
11567 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11568 }
25e4902b 11569 CATCH (ex, RETURN_MASK_ERROR)
c50c785c 11570 {
ef5ccd6c
JM
11571 if (ex.error != TARGET_CLOSE_ERROR)
11572 {
11573 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11574 return -1;
11575 }
11576 throw_exception (ex);
c50c785c 11577 }
25e4902b
AHJ
11578 END_CATCH
11579
11580 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
cf7f2e2d
JM
11581
11582 /* If the remote target doesn't do tracing, flag it. */
25e4902b 11583 if (result == PACKET_UNKNOWN)
cf7f2e2d
JM
11584 return -1;
11585
11586 /* We're working with a live target. */
ef5ccd6c 11587 ts->filename = NULL;
cf7f2e2d
JM
11588
11589 if (*p++ != 'T')
11590 error (_("Bogus trace status reply from target: %s"), target_buf);
11591
ef5ccd6c
JM
11592 /* Function 'parse_trace_status' sets default value of each field of
11593 'ts' at first, so we don't have to do it here. */
cf7f2e2d
JM
11594 parse_trace_status (p, ts);
11595
11596 return ts->running;
11597}
11598
ef5ccd6c 11599static void
25e4902b 11600remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
a45ae5f8
JM
11601 struct uploaded_tp *utp)
11602{
11603 struct remote_state *rs = get_remote_state ();
11604 char *reply;
11605 struct bp_location *loc;
11606 struct tracepoint *tp = (struct tracepoint *) bp;
ef5ccd6c 11607 size_t size = get_remote_packet_size ();
a45ae5f8
JM
11608
11609 if (tp)
11610 {
11611 tp->base.hit_count = 0;
11612 tp->traceframe_usage = 0;
11613 for (loc = tp->base.loc; loc; loc = loc->next)
11614 {
11615 /* If the tracepoint was never downloaded, don't go asking for
11616 any status. */
11617 if (tp->number_on_target == 0)
11618 continue;
ef5ccd6c
JM
11619 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11620 phex_nz (loc->address, 0));
a45ae5f8
JM
11621 putpkt (rs->buf);
11622 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11623 if (reply && *reply)
11624 {
11625 if (*reply == 'V')
11626 parse_tracepoint_status (reply + 1, bp, utp);
11627 }
11628 }
11629 }
11630 else if (utp)
11631 {
11632 utp->hit_count = 0;
11633 utp->traceframe_usage = 0;
ef5ccd6c
JM
11634 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11635 phex_nz (utp->addr, 0));
a45ae5f8
JM
11636 putpkt (rs->buf);
11637 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11638 if (reply && *reply)
11639 {
11640 if (*reply == 'V')
11641 parse_tracepoint_status (reply + 1, bp, utp);
11642 }
11643 }
11644}
11645
cf7f2e2d 11646static void
25e4902b 11647remote_trace_stop (struct target_ops *self)
cf7f2e2d
JM
11648{
11649 putpkt ("QTStop");
11650 remote_get_noisy_reply (&target_buf, &target_buf_size);
11651 if (*target_buf == '\0')
11652 error (_("Target does not support this command."));
11653 if (strcmp (target_buf, "OK") != 0)
11654 error (_("Bogus reply from target: %s"), target_buf);
11655}
11656
11657static int
25e4902b
AHJ
11658remote_trace_find (struct target_ops *self,
11659 enum trace_find_type type, int num,
11660 CORE_ADDR addr1, CORE_ADDR addr2,
cf7f2e2d
JM
11661 int *tpp)
11662{
11663 struct remote_state *rs = get_remote_state ();
ef5ccd6c 11664 char *endbuf = rs->buf + get_remote_packet_size ();
cf7f2e2d
JM
11665 char *p, *reply;
11666 int target_frameno = -1, target_tracept = -1;
11667
c50c785c
JM
11668 /* Lookups other than by absolute frame number depend on the current
11669 trace selected, so make sure it is correct on the remote end
11670 first. */
11671 if (type != tfind_number)
11672 set_remote_traceframe ();
11673
cf7f2e2d
JM
11674 p = rs->buf;
11675 strcpy (p, "QTFrame:");
11676 p = strchr (p, '\0');
11677 switch (type)
11678 {
11679 case tfind_number:
ef5ccd6c 11680 xsnprintf (p, endbuf - p, "%x", num);
cf7f2e2d
JM
11681 break;
11682 case tfind_pc:
ef5ccd6c 11683 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
cf7f2e2d
JM
11684 break;
11685 case tfind_tp:
ef5ccd6c 11686 xsnprintf (p, endbuf - p, "tdp:%x", num);
cf7f2e2d
JM
11687 break;
11688 case tfind_range:
ef5ccd6c
JM
11689 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11690 phex_nz (addr2, 0));
cf7f2e2d
JM
11691 break;
11692 case tfind_outside:
ef5ccd6c
JM
11693 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11694 phex_nz (addr2, 0));
cf7f2e2d
JM
11695 break;
11696 default:
c50c785c 11697 error (_("Unknown trace find type %d"), type);
cf7f2e2d
JM
11698 }
11699
11700 putpkt (rs->buf);
25e4902b 11701 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
cf7f2e2d
JM
11702 if (*reply == '\0')
11703 error (_("Target does not support this command."));
11704
11705 while (reply && *reply)
11706 switch (*reply)
11707 {
11708 case 'F':
11709 p = ++reply;
11710 target_frameno = (int) strtol (p, &reply, 16);
11711 if (reply == p)
11712 error (_("Unable to parse trace frame number"));
c50c785c
JM
11713 /* Don't update our remote traceframe number cache on failure
11714 to select a remote traceframe. */
cf7f2e2d
JM
11715 if (target_frameno == -1)
11716 return -1;
11717 break;
11718 case 'T':
11719 p = ++reply;
11720 target_tracept = (int) strtol (p, &reply, 16);
11721 if (reply == p)
11722 error (_("Unable to parse tracepoint number"));
11723 break;
11724 case 'O': /* "OK"? */
11725 if (reply[1] == 'K' && reply[2] == '\0')
11726 reply += 2;
11727 else
11728 error (_("Bogus reply from target: %s"), reply);
11729 break;
11730 default:
11731 error (_("Bogus reply from target: %s"), reply);
11732 }
11733 if (tpp)
11734 *tpp = target_tracept;
c50c785c 11735
25e4902b 11736 rs->remote_traceframe_number = target_frameno;
cf7f2e2d
JM
11737 return target_frameno;
11738}
11739
11740static int
25e4902b
AHJ
11741remote_get_trace_state_variable_value (struct target_ops *self,
11742 int tsvnum, LONGEST *val)
cf7f2e2d
JM
11743{
11744 struct remote_state *rs = get_remote_state ();
11745 char *reply;
11746 ULONGEST uval;
11747
c50c785c
JM
11748 set_remote_traceframe ();
11749
ef5ccd6c 11750 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
cf7f2e2d
JM
11751 putpkt (rs->buf);
11752 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11753 if (reply && *reply)
11754 {
11755 if (*reply == 'V')
11756 {
11757 unpack_varlen_hex (reply + 1, &uval);
11758 *val = (LONGEST) uval;
11759 return 1;
11760 }
11761 }
11762 return 0;
11763}
11764
11765static int
25e4902b 11766remote_save_trace_data (struct target_ops *self, const char *filename)
cf7f2e2d
JM
11767{
11768 struct remote_state *rs = get_remote_state ();
11769 char *p, *reply;
11770
11771 p = rs->buf;
11772 strcpy (p, "QTSave:");
11773 p += strlen (p);
11774 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11775 error (_("Remote file name too long for trace save packet"));
25e4902b 11776 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
cf7f2e2d
JM
11777 *p++ = '\0';
11778 putpkt (rs->buf);
11779 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
a45ae5f8 11780 if (*reply == '\0')
cf7f2e2d
JM
11781 error (_("Target does not support this command."));
11782 if (strcmp (reply, "OK") != 0)
11783 error (_("Bogus reply from target: %s"), reply);
11784 return 0;
11785}
11786
11787/* This is basically a memory transfer, but needs to be its own packet
11788 because we don't know how the target actually organizes its trace
11789 memory, plus we want to be able to ask for as much as possible, but
11790 not be unhappy if we don't get as much as we ask for. */
11791
11792static LONGEST
25e4902b
AHJ
11793remote_get_raw_trace_data (struct target_ops *self,
11794 gdb_byte *buf, ULONGEST offset, LONGEST len)
cf7f2e2d
JM
11795{
11796 struct remote_state *rs = get_remote_state ();
11797 char *reply;
11798 char *p;
11799 int rslt;
11800
11801 p = rs->buf;
11802 strcpy (p, "qTBuffer:");
11803 p += strlen (p);
11804 p += hexnumstr (p, offset);
11805 *p++ = ',';
11806 p += hexnumstr (p, len);
11807 *p++ = '\0';
11808
11809 putpkt (rs->buf);
11810 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11811 if (reply && *reply)
11812 {
11813 /* 'l' by itself means we're at the end of the buffer and
11814 there is nothing more to get. */
11815 if (*reply == 'l')
11816 return 0;
11817
11818 /* Convert the reply into binary. Limit the number of bytes to
11819 convert according to our passed-in buffer size, rather than
11820 what was returned in the packet; if the target is
11821 unexpectedly generous and gives us a bigger reply than we
11822 asked for, we don't want to crash. */
11823 rslt = hex2bin (target_buf, buf, len);
11824 return rslt;
11825 }
11826
11827 /* Something went wrong, flag as an error. */
11828 return -1;
11829}
11830
11831static void
25e4902b 11832remote_set_disconnected_tracing (struct target_ops *self, int val)
cf7f2e2d
JM
11833{
11834 struct remote_state *rs = get_remote_state ();
11835
25e4902b 11836 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
cf7f2e2d
JM
11837 {
11838 char *reply;
11839
ef5ccd6c 11840 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
cf7f2e2d
JM
11841 putpkt (rs->buf);
11842 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11843 if (*reply == '\0')
11844 error (_("Target does not support this command."));
11845 if (strcmp (reply, "OK") != 0)
11846 error (_("Bogus reply from target: %s"), reply);
11847 }
11848 else if (val)
11849 warning (_("Target does not support disconnected tracing."));
11850}
11851
11852static int
11853remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11854{
11855 struct thread_info *info = find_thread_ptid (ptid);
11856
25e4902b
AHJ
11857 if (info && info->priv)
11858 return info->priv->core;
cf7f2e2d
JM
11859 return -1;
11860}
11861
11862static void
25e4902b 11863remote_set_circular_trace_buffer (struct target_ops *self, int val)
cf7f2e2d
JM
11864{
11865 struct remote_state *rs = get_remote_state ();
11866 char *reply;
11867
ef5ccd6c 11868 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
cf7f2e2d
JM
11869 putpkt (rs->buf);
11870 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11871 if (*reply == '\0')
11872 error (_("Target does not support this command."));
11873 if (strcmp (reply, "OK") != 0)
11874 error (_("Bogus reply from target: %s"), reply);
11875}
11876
c50c785c 11877static struct traceframe_info *
25e4902b 11878remote_traceframe_info (struct target_ops *self)
c50c785c
JM
11879{
11880 char *text;
11881
11882 text = target_read_stralloc (&current_target,
11883 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11884 if (text != NULL)
11885 {
11886 struct traceframe_info *info;
11887 struct cleanup *back_to = make_cleanup (xfree, text);
11888
11889 info = parse_traceframe_info (text);
11890 do_cleanups (back_to);
11891 return info;
11892 }
11893
11894 return NULL;
11895}
11896
a45ae5f8
JM
11897/* Handle the qTMinFTPILen packet. Returns the minimum length of
11898 instruction on which a fast tracepoint may be placed. Returns -1
11899 if the packet is not supported, and 0 if the minimum instruction
11900 length is unknown. */
11901
11902static int
25e4902b 11903remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
a45ae5f8
JM
11904{
11905 struct remote_state *rs = get_remote_state ();
11906 char *reply;
11907
ef5ccd6c
JM
11908 /* If we're not debugging a process yet, the IPA can't be
11909 loaded. */
11910 if (!target_has_execution)
11911 return 0;
11912
11913 /* Make sure the remote is pointing at the right process. */
11914 set_general_process ();
11915
11916 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
a45ae5f8
JM
11917 putpkt (rs->buf);
11918 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11919 if (*reply == '\0')
11920 return -1;
11921 else
11922 {
11923 ULONGEST min_insn_len;
11924
11925 unpack_varlen_hex (reply, &min_insn_len);
11926
11927 return (int) min_insn_len;
11928 }
11929}
11930
ef5ccd6c 11931static void
25e4902b 11932remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
ef5ccd6c 11933{
25e4902b 11934 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
ef5ccd6c
JM
11935 {
11936 struct remote_state *rs = get_remote_state ();
11937 char *buf = rs->buf;
11938 char *endbuf = rs->buf + get_remote_packet_size ();
11939 enum packet_result result;
11940
11941 gdb_assert (val >= 0 || val == -1);
11942 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11943 /* Send -1 as literal "-1" to avoid host size dependency. */
11944 if (val < 0)
11945 {
11946 *buf++ = '-';
11947 buf += hexnumstr (buf, (ULONGEST) -val);
11948 }
11949 else
11950 buf += hexnumstr (buf, (ULONGEST) val);
11951
11952 putpkt (rs->buf);
11953 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11954 result = packet_ok (rs->buf,
11955 &remote_protocol_packets[PACKET_QTBuffer_size]);
11956
11957 if (result != PACKET_OK)
11958 warning (_("Bogus reply from target: %s"), rs->buf);
11959 }
11960}
11961
a45ae5f8 11962static int
25e4902b
AHJ
11963remote_set_trace_notes (struct target_ops *self,
11964 const char *user, const char *notes,
11965 const char *stop_notes)
a45ae5f8
JM
11966{
11967 struct remote_state *rs = get_remote_state ();
11968 char *reply;
11969 char *buf = rs->buf;
11970 char *endbuf = rs->buf + get_remote_packet_size ();
11971 int nbytes;
11972
11973 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11974 if (user)
11975 {
11976 buf += xsnprintf (buf, endbuf - buf, "user:");
25e4902b 11977 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
a45ae5f8
JM
11978 buf += 2 * nbytes;
11979 *buf++ = ';';
11980 }
11981 if (notes)
11982 {
11983 buf += xsnprintf (buf, endbuf - buf, "notes:");
25e4902b 11984 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
a45ae5f8
JM
11985 buf += 2 * nbytes;
11986 *buf++ = ';';
11987 }
11988 if (stop_notes)
11989 {
11990 buf += xsnprintf (buf, endbuf - buf, "tstop:");
25e4902b 11991 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
a45ae5f8
JM
11992 buf += 2 * nbytes;
11993 *buf++ = ';';
11994 }
11995 /* Ensure the buffer is terminated. */
11996 *buf = '\0';
11997
11998 putpkt (rs->buf);
11999 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12000 if (*reply == '\0')
12001 return 0;
12002
12003 if (strcmp (reply, "OK") != 0)
12004 error (_("Bogus reply from target: %s"), reply);
12005
12006 return 1;
12007}
12008
ef5ccd6c 12009static int
25e4902b 12010remote_use_agent (struct target_ops *self, int use)
ef5ccd6c 12011{
25e4902b 12012 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
ef5ccd6c
JM
12013 {
12014 struct remote_state *rs = get_remote_state ();
12015
12016 /* If the stub supports QAgent. */
12017 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12018 putpkt (rs->buf);
12019 getpkt (&rs->buf, &rs->buf_size, 0);
12020
12021 if (strcmp (rs->buf, "OK") == 0)
12022 {
12023 use_agent = use;
12024 return 1;
12025 }
12026 }
12027
12028 return 0;
12029}
12030
12031static int
25e4902b 12032remote_can_use_agent (struct target_ops *self)
ef5ccd6c 12033{
25e4902b 12034 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
ef5ccd6c
JM
12035}
12036
12037struct btrace_target_info
12038{
12039 /* The ptid of the traced thread. */
12040 ptid_t ptid;
25e4902b
AHJ
12041
12042 /* The obtained branch trace configuration. */
12043 struct btrace_config conf;
ef5ccd6c
JM
12044};
12045
25e4902b
AHJ
12046/* Reset our idea of our target's btrace configuration. */
12047
12048static void
12049remote_btrace_reset (void)
12050{
12051 struct remote_state *rs = get_remote_state ();
12052
12053 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12054}
12055
ef5ccd6c
JM
12056/* Check whether the target supports branch tracing. */
12057
12058static int
25e4902b 12059remote_supports_btrace (struct target_ops *self, enum btrace_format format)
ef5ccd6c 12060{
25e4902b 12061 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
ef5ccd6c 12062 return 0;
25e4902b 12063 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
ef5ccd6c
JM
12064 return 0;
12065
25e4902b
AHJ
12066 switch (format)
12067 {
12068 case BTRACE_FORMAT_NONE:
12069 return 0;
12070
12071 case BTRACE_FORMAT_BTS:
12072 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12073
12074 case BTRACE_FORMAT_PT:
12075 /* The trace is decoded on the host. Even if our target supports it,
12076 we still need to have libipt to decode the trace. */
12077#if defined (HAVE_LIBIPT)
12078 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12079#else /* !defined (HAVE_LIBIPT) */
12080 return 0;
12081#endif /* !defined (HAVE_LIBIPT) */
12082 }
12083
12084 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12085}
12086
12087/* Synchronize the configuration with the target. */
12088
12089static void
12090btrace_sync_conf (const struct btrace_config *conf)
12091{
12092 struct packet_config *packet;
12093 struct remote_state *rs;
12094 char *buf, *pos, *endbuf;
12095
12096 rs = get_remote_state ();
12097 buf = rs->buf;
12098 endbuf = buf + get_remote_packet_size ();
12099
12100 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12101 if (packet_config_support (packet) == PACKET_ENABLE
12102 && conf->bts.size != rs->btrace_config.bts.size)
12103 {
12104 pos = buf;
12105 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12106 conf->bts.size);
12107
12108 putpkt (buf);
12109 getpkt (&buf, &rs->buf_size, 0);
12110
12111 if (packet_ok (buf, packet) == PACKET_ERROR)
12112 {
12113 if (buf[0] == 'E' && buf[1] == '.')
12114 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12115 else
12116 error (_("Failed to configure the BTS buffer size."));
12117 }
12118
12119 rs->btrace_config.bts.size = conf->bts.size;
12120 }
12121
12122 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12123 if (packet_config_support (packet) == PACKET_ENABLE
12124 && conf->pt.size != rs->btrace_config.pt.size)
12125 {
12126 pos = buf;
12127 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12128 conf->pt.size);
12129
12130 putpkt (buf);
12131 getpkt (&buf, &rs->buf_size, 0);
12132
12133 if (packet_ok (buf, packet) == PACKET_ERROR)
12134 {
12135 if (buf[0] == 'E' && buf[1] == '.')
12136 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12137 else
12138 error (_("Failed to configure the trace buffer size."));
12139 }
12140
12141 rs->btrace_config.pt.size = conf->pt.size;
12142 }
12143}
12144
12145/* Read the current thread's btrace configuration from the target and
12146 store it into CONF. */
12147
12148static void
12149btrace_read_config (struct btrace_config *conf)
12150{
12151 char *xml;
12152
12153 xml = target_read_stralloc (&current_target,
12154 TARGET_OBJECT_BTRACE_CONF, "");
12155 if (xml != NULL)
12156 {
12157 struct cleanup *cleanup;
12158
12159 cleanup = make_cleanup (xfree, xml);
12160 parse_xml_btrace_conf (conf, xml);
12161 do_cleanups (cleanup);
12162 }
ef5ccd6c
JM
12163}
12164
12165/* Enable branch tracing. */
12166
12167static struct btrace_target_info *
25e4902b
AHJ
12168remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12169 const struct btrace_config *conf)
ef5ccd6c
JM
12170{
12171 struct btrace_target_info *tinfo = NULL;
25e4902b 12172 struct packet_config *packet = NULL;
ef5ccd6c
JM
12173 struct remote_state *rs = get_remote_state ();
12174 char *buf = rs->buf;
12175 char *endbuf = rs->buf + get_remote_packet_size ();
12176
25e4902b
AHJ
12177 switch (conf->format)
12178 {
12179 case BTRACE_FORMAT_BTS:
12180 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12181 break;
12182
12183 case BTRACE_FORMAT_PT:
12184 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12185 break;
12186 }
12187
12188 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
ef5ccd6c
JM
12189 error (_("Target does not support branch tracing."));
12190
25e4902b
AHJ
12191 btrace_sync_conf (conf);
12192
ef5ccd6c
JM
12193 set_general_thread (ptid);
12194
12195 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12196 putpkt (rs->buf);
12197 getpkt (&rs->buf, &rs->buf_size, 0);
12198
12199 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12200 {
12201 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12202 error (_("Could not enable branch tracing for %s: %s"),
12203 target_pid_to_str (ptid), rs->buf + 2);
12204 else
12205 error (_("Could not enable branch tracing for %s."),
12206 target_pid_to_str (ptid));
12207 }
12208
12209 tinfo = xzalloc (sizeof (*tinfo));
12210 tinfo->ptid = ptid;
12211
25e4902b
AHJ
12212 /* If we fail to read the configuration, we lose some information, but the
12213 tracing itself is not impacted. */
12214 TRY
12215 {
12216 btrace_read_config (&tinfo->conf);
12217 }
12218 CATCH (err, RETURN_MASK_ERROR)
12219 {
12220 if (err.message != NULL)
12221 warning ("%s", err.message);
12222 }
12223 END_CATCH
12224
ef5ccd6c
JM
12225 return tinfo;
12226}
12227
12228/* Disable branch tracing. */
12229
12230static void
25e4902b
AHJ
12231remote_disable_btrace (struct target_ops *self,
12232 struct btrace_target_info *tinfo)
ef5ccd6c
JM
12233{
12234 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12235 struct remote_state *rs = get_remote_state ();
12236 char *buf = rs->buf;
12237 char *endbuf = rs->buf + get_remote_packet_size ();
12238
25e4902b 12239 if (packet_config_support (packet) != PACKET_ENABLE)
ef5ccd6c
JM
12240 error (_("Target does not support branch tracing."));
12241
12242 set_general_thread (tinfo->ptid);
12243
12244 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12245 putpkt (rs->buf);
12246 getpkt (&rs->buf, &rs->buf_size, 0);
12247
12248 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12249 {
12250 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12251 error (_("Could not disable branch tracing for %s: %s"),
12252 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12253 else
12254 error (_("Could not disable branch tracing for %s."),
12255 target_pid_to_str (tinfo->ptid));
12256 }
12257
12258 xfree (tinfo);
12259}
12260
12261/* Teardown branch tracing. */
12262
12263static void
25e4902b
AHJ
12264remote_teardown_btrace (struct target_ops *self,
12265 struct btrace_target_info *tinfo)
ef5ccd6c
JM
12266{
12267 /* We must not talk to the target during teardown. */
12268 xfree (tinfo);
12269}
12270
12271/* Read the branch trace. */
12272
25e4902b
AHJ
12273static enum btrace_error
12274remote_read_btrace (struct target_ops *self,
12275 struct btrace_data *btrace,
12276 struct btrace_target_info *tinfo,
ef5ccd6c
JM
12277 enum btrace_read_type type)
12278{
12279 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12280 struct remote_state *rs = get_remote_state ();
25e4902b 12281 struct cleanup *cleanup;
ef5ccd6c
JM
12282 const char *annex;
12283 char *xml;
12284
25e4902b 12285 if (packet_config_support (packet) != PACKET_ENABLE)
ef5ccd6c
JM
12286 error (_("Target does not support branch tracing."));
12287
12288#if !defined(HAVE_LIBEXPAT)
12289 error (_("Cannot process branch tracing result. XML parsing not supported."));
12290#endif
12291
12292 switch (type)
12293 {
25e4902b 12294 case BTRACE_READ_ALL:
ef5ccd6c
JM
12295 annex = "all";
12296 break;
25e4902b 12297 case BTRACE_READ_NEW:
ef5ccd6c
JM
12298 annex = "new";
12299 break;
25e4902b
AHJ
12300 case BTRACE_READ_DELTA:
12301 annex = "delta";
12302 break;
ef5ccd6c
JM
12303 default:
12304 internal_error (__FILE__, __LINE__,
12305 _("Bad branch tracing read type: %u."),
12306 (unsigned int) type);
12307 }
12308
12309 xml = target_read_stralloc (&current_target,
25e4902b
AHJ
12310 TARGET_OBJECT_BTRACE, annex);
12311 if (xml == NULL)
12312 return BTRACE_ERR_UNKNOWN;
12313
12314 cleanup = make_cleanup (xfree, xml);
12315 parse_xml_btrace (btrace, xml);
12316 do_cleanups (cleanup);
12317
12318 return BTRACE_ERR_NONE;
12319}
12320
12321static const struct btrace_config *
12322remote_btrace_conf (struct target_ops *self,
12323 const struct btrace_target_info *tinfo)
12324{
12325 return &tinfo->conf;
12326}
12327
12328static int
12329remote_augmented_libraries_svr4_read (struct target_ops *self)
12330{
12331 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12332 == PACKET_ENABLE);
12333}
12334
12335/* Implementation of to_load. */
12336
12337static void
12338remote_load (struct target_ops *self, const char *name, int from_tty)
12339{
12340 generic_load (name, from_tty);
12341}
12342
12343/* Accepts an integer PID; returns a string representing a file that
12344 can be opened on the remote side to get the symbols for the child
12345 process. Returns NULL if the operation is not supported. */
12346
12347static char *
12348remote_pid_to_exec_file (struct target_ops *self, int pid)
12349{
12350 static char *filename = NULL;
12351 struct inferior *inf;
12352 char *annex = NULL;
12353
12354 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12355 return NULL;
12356
12357 if (filename != NULL)
12358 xfree (filename);
12359
12360 inf = find_inferior_pid (pid);
12361 if (inf == NULL)
12362 internal_error (__FILE__, __LINE__,
12363 _("not currently attached to process %d"), pid);
12364
12365 if (!inf->fake_pid_p)
ef5ccd6c 12366 {
25e4902b 12367 const int annex_size = 9;
ef5ccd6c 12368
25e4902b
AHJ
12369 annex = alloca (annex_size);
12370 xsnprintf (annex, annex_size, "%x", pid);
ef5ccd6c
JM
12371 }
12372
25e4902b
AHJ
12373 filename = target_read_stralloc (&current_target,
12374 TARGET_OBJECT_EXEC_FILE, annex);
12375
12376 return filename;
ef5ccd6c
JM
12377}
12378
5796c8dc
SS
12379static void
12380init_remote_ops (void)
12381{
12382 remote_ops.to_shortname = "remote";
12383 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12384 remote_ops.to_doc =
12385 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12386Specify the serial device it is connected to\n\
12387(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12388 remote_ops.to_open = remote_open;
12389 remote_ops.to_close = remote_close;
12390 remote_ops.to_detach = remote_detach;
12391 remote_ops.to_disconnect = remote_disconnect;
12392 remote_ops.to_resume = remote_resume;
12393 remote_ops.to_wait = remote_wait;
12394 remote_ops.to_fetch_registers = remote_fetch_registers;
12395 remote_ops.to_store_registers = remote_store_registers;
12396 remote_ops.to_prepare_to_store = remote_prepare_to_store;
5796c8dc
SS
12397 remote_ops.to_files_info = remote_files_info;
12398 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12399 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
25e4902b
AHJ
12400 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12401 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12402 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12403 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
5796c8dc
SS
12404 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12405 remote_ops.to_stopped_data_address = remote_stopped_data_address;
ef5ccd6c
JM
12406 remote_ops.to_watchpoint_addr_within_range =
12407 remote_watchpoint_addr_within_range;
5796c8dc
SS
12408 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12409 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12410 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
a45ae5f8
JM
12411 remote_ops.to_region_ok_for_hw_watchpoint
12412 = remote_region_ok_for_hw_watchpoint;
5796c8dc
SS
12413 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12414 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12415 remote_ops.to_kill = remote_kill;
25e4902b 12416 remote_ops.to_load = remote_load;
5796c8dc 12417 remote_ops.to_mourn_inferior = remote_mourn;
a45ae5f8 12418 remote_ops.to_pass_signals = remote_pass_signals;
ef5ccd6c 12419 remote_ops.to_program_signals = remote_program_signals;
5796c8dc 12420 remote_ops.to_thread_alive = remote_thread_alive;
25e4902b 12421 remote_ops.to_update_thread_list = remote_update_thread_list;
5796c8dc
SS
12422 remote_ops.to_pid_to_str = remote_pid_to_str;
12423 remote_ops.to_extra_thread_info = remote_threads_extra_info;
cf7f2e2d 12424 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
5796c8dc 12425 remote_ops.to_stop = remote_stop;
25e4902b 12426 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
5796c8dc
SS
12427 remote_ops.to_xfer_partial = remote_xfer_partial;
12428 remote_ops.to_rcmd = remote_rcmd;
25e4902b 12429 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
5796c8dc
SS
12430 remote_ops.to_log_command = serial_log_command;
12431 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12432 remote_ops.to_stratum = process_stratum;
12433 remote_ops.to_has_all_memory = default_child_has_all_memory;
12434 remote_ops.to_has_memory = default_child_has_memory;
12435 remote_ops.to_has_stack = default_child_has_stack;
12436 remote_ops.to_has_registers = default_child_has_registers;
12437 remote_ops.to_has_execution = default_child_has_execution;
c50c785c 12438 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
5796c8dc
SS
12439 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12440 remote_ops.to_magic = OPS_MAGIC;
12441 remote_ops.to_memory_map = remote_memory_map;
12442 remote_ops.to_flash_erase = remote_flash_erase;
12443 remote_ops.to_flash_done = remote_flash_done;
12444 remote_ops.to_read_description = remote_read_description;
12445 remote_ops.to_search_memory = remote_search_memory;
12446 remote_ops.to_can_async_p = remote_can_async_p;
12447 remote_ops.to_is_async_p = remote_is_async_p;
12448 remote_ops.to_async = remote_async;
5796c8dc
SS
12449 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12450 remote_ops.to_terminal_ours = remote_terminal_ours;
12451 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12452 remote_ops.to_supports_multi_process = remote_supports_multi_process;
a45ae5f8
JM
12453 remote_ops.to_supports_disable_randomization
12454 = remote_supports_disable_randomization;
25e4902b 12455 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
ef5ccd6c
JM
12456 remote_ops.to_fileio_open = remote_hostio_open;
12457 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12458 remote_ops.to_fileio_pread = remote_hostio_pread;
25e4902b 12459 remote_ops.to_fileio_fstat = remote_hostio_fstat;
ef5ccd6c
JM
12460 remote_ops.to_fileio_close = remote_hostio_close;
12461 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12462 remote_ops.to_fileio_readlink = remote_hostio_readlink;
a45ae5f8
JM
12463 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12464 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
ef5ccd6c
JM
12465 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12466 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
cf7f2e2d
JM
12467 remote_ops.to_trace_init = remote_trace_init;
12468 remote_ops.to_download_tracepoint = remote_download_tracepoint;
a45ae5f8 12469 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
c50c785c
JM
12470 remote_ops.to_download_trace_state_variable
12471 = remote_download_trace_state_variable;
a45ae5f8
JM
12472 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12473 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
cf7f2e2d
JM
12474 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12475 remote_ops.to_trace_start = remote_trace_start;
12476 remote_ops.to_get_trace_status = remote_get_trace_status;
a45ae5f8 12477 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
cf7f2e2d
JM
12478 remote_ops.to_trace_stop = remote_trace_stop;
12479 remote_ops.to_trace_find = remote_trace_find;
c50c785c
JM
12480 remote_ops.to_get_trace_state_variable_value
12481 = remote_get_trace_state_variable_value;
cf7f2e2d
JM
12482 remote_ops.to_save_trace_data = remote_save_trace_data;
12483 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
c50c785c
JM
12484 remote_ops.to_upload_trace_state_variables
12485 = remote_upload_trace_state_variables;
cf7f2e2d 12486 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
a45ae5f8 12487 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
cf7f2e2d
JM
12488 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12489 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
ef5ccd6c 12490 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
a45ae5f8 12491 remote_ops.to_set_trace_notes = remote_set_trace_notes;
cf7f2e2d
JM
12492 remote_ops.to_core_of_thread = remote_core_of_thread;
12493 remote_ops.to_verify_memory = remote_verify_memory;
12494 remote_ops.to_get_tib_address = remote_get_tib_address;
12495 remote_ops.to_set_permissions = remote_set_permissions;
12496 remote_ops.to_static_tracepoint_marker_at
12497 = remote_static_tracepoint_marker_at;
12498 remote_ops.to_static_tracepoint_markers_by_strid
12499 = remote_static_tracepoint_markers_by_strid;
c50c785c 12500 remote_ops.to_traceframe_info = remote_traceframe_info;
ef5ccd6c
JM
12501 remote_ops.to_use_agent = remote_use_agent;
12502 remote_ops.to_can_use_agent = remote_can_use_agent;
12503 remote_ops.to_supports_btrace = remote_supports_btrace;
12504 remote_ops.to_enable_btrace = remote_enable_btrace;
12505 remote_ops.to_disable_btrace = remote_disable_btrace;
12506 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12507 remote_ops.to_read_btrace = remote_read_btrace;
25e4902b
AHJ
12508 remote_ops.to_btrace_conf = remote_btrace_conf;
12509 remote_ops.to_augmented_libraries_svr4_read =
12510 remote_augmented_libraries_svr4_read;
5796c8dc
SS
12511}
12512
12513/* Set up the extended remote vector by making a copy of the standard
12514 remote vector and adding to it. */
12515
12516static void
12517init_extended_remote_ops (void)
12518{
12519 extended_remote_ops = remote_ops;
12520
12521 extended_remote_ops.to_shortname = "extended-remote";
12522 extended_remote_ops.to_longname =
12523 "Extended remote serial target in gdb-specific protocol";
12524 extended_remote_ops.to_doc =
12525 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12526Specify the serial device it is connected to (e.g. /dev/ttya).";
12527 extended_remote_ops.to_open = extended_remote_open;
12528 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12529 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
12530 extended_remote_ops.to_detach = extended_remote_detach;
12531 extended_remote_ops.to_attach = extended_remote_attach;
25e4902b 12532 extended_remote_ops.to_post_attach = extended_remote_post_attach;
5796c8dc 12533 extended_remote_ops.to_kill = extended_remote_kill;
a45ae5f8
JM
12534 extended_remote_ops.to_supports_disable_randomization
12535 = extended_remote_supports_disable_randomization;
25e4902b
AHJ
12536 extended_remote_ops.to_follow_fork = remote_follow_fork;
12537 extended_remote_ops.to_insert_fork_catchpoint
12538 = remote_insert_fork_catchpoint;
12539 extended_remote_ops.to_remove_fork_catchpoint
12540 = remote_remove_fork_catchpoint;
12541 extended_remote_ops.to_insert_vfork_catchpoint
12542 = remote_insert_vfork_catchpoint;
12543 extended_remote_ops.to_remove_vfork_catchpoint
12544 = remote_remove_vfork_catchpoint;
5796c8dc
SS
12545}
12546
12547static int
25e4902b 12548remote_can_async_p (struct target_ops *ops)
5796c8dc 12549{
25e4902b
AHJ
12550 struct remote_state *rs = get_remote_state ();
12551
5796c8dc
SS
12552 if (!target_async_permitted)
12553 /* We only enable async when the user specifically asks for it. */
12554 return 0;
12555
12556 /* We're async whenever the serial device is. */
25e4902b 12557 return serial_can_async_p (rs->remote_desc);
5796c8dc
SS
12558}
12559
12560static int
25e4902b 12561remote_is_async_p (struct target_ops *ops)
5796c8dc 12562{
25e4902b
AHJ
12563 struct remote_state *rs = get_remote_state ();
12564
5796c8dc
SS
12565 if (!target_async_permitted)
12566 /* We only enable async when the user specifically asks for it. */
12567 return 0;
12568
12569 /* We're async whenever the serial device is. */
25e4902b 12570 return serial_is_async_p (rs->remote_desc);
5796c8dc
SS
12571}
12572
12573/* Pass the SERIAL event on and up to the client. One day this code
12574 will be able to delay notifying the client of an event until the
12575 point where an entire packet has been received. */
12576
5796c8dc
SS
12577static serial_event_ftype remote_async_serial_handler;
12578
12579static void
12580remote_async_serial_handler (struct serial *scb, void *context)
12581{
25e4902b
AHJ
12582 struct remote_state *rs = context;
12583
5796c8dc
SS
12584 /* Don't propogate error information up to the client. Instead let
12585 the client find out about the error by querying the target. */
25e4902b 12586 inferior_event_handler (INF_REG_EVENT, NULL);
5796c8dc
SS
12587}
12588
12589static void
12590remote_async_inferior_event_handler (gdb_client_data data)
12591{
12592 inferior_event_handler (INF_REG_EVENT, NULL);
12593}
12594
5796c8dc 12595static void
25e4902b 12596remote_async (struct target_ops *ops, int enable)
5796c8dc 12597{
25e4902b
AHJ
12598 struct remote_state *rs = get_remote_state ();
12599
12600 if (enable)
5796c8dc 12601 {
25e4902b
AHJ
12602 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
12603
12604 /* If there are pending events in the stop reply queue tell the
12605 event loop to process them. */
12606 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12607 mark_async_event_handler (remote_async_inferior_event_token);
5796c8dc
SS
12608 }
12609 else
25e4902b
AHJ
12610 {
12611 serial_async (rs->remote_desc, NULL, NULL);
12612 clear_async_event_handler (remote_async_inferior_event_token);
12613 }
5796c8dc
SS
12614}
12615
5796c8dc
SS
12616static void
12617set_remote_cmd (char *args, int from_tty)
12618{
25e4902b 12619 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5796c8dc
SS
12620}
12621
12622static void
12623show_remote_cmd (char *args, int from_tty)
12624{
12625 /* We can't just use cmd_show_list here, because we want to skip
12626 the redundant "show remote Z-packet" and the legacy aliases. */
12627 struct cleanup *showlist_chain;
12628 struct cmd_list_element *list = remote_show_cmdlist;
a45ae5f8 12629 struct ui_out *uiout = current_uiout;
5796c8dc
SS
12630
12631 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12632 for (; list != NULL; list = list->next)
12633 if (strcmp (list->name, "Z-packet") == 0)
12634 continue;
12635 else if (list->type == not_set_cmd)
12636 /* Alias commands are exactly like the original, except they
12637 don't have the normal type. */
12638 continue;
12639 else
12640 {
12641 struct cleanup *option_chain
12642 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
cf7f2e2d 12643
5796c8dc
SS
12644 ui_out_field_string (uiout, "name", list->name);
12645 ui_out_text (uiout, ": ");
12646 if (list->type == show_cmd)
ef5ccd6c 12647 do_show_command ((char *) NULL, from_tty, list);
5796c8dc
SS
12648 else
12649 cmd_func (list, NULL, from_tty);
12650 /* Close the tuple. */
12651 do_cleanups (option_chain);
12652 }
12653
12654 /* Close the tuple. */
12655 do_cleanups (showlist_chain);
12656}
12657
12658
12659/* Function to be called whenever a new objfile (shlib) is detected. */
12660static void
12661remote_new_objfile (struct objfile *objfile)
12662{
25e4902b
AHJ
12663 struct remote_state *rs = get_remote_state ();
12664
12665 if (rs->remote_desc != 0) /* Have a remote connection. */
12666 remote_check_symbols ();
5796c8dc
SS
12667}
12668
cf7f2e2d
JM
12669/* Pull all the tracepoints defined on the target and create local
12670 data structures representing them. We don't want to create real
12671 tracepoints yet, we don't want to mess up the user's existing
12672 collection. */
12673
12674static int
25e4902b 12675remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
cf7f2e2d
JM
12676{
12677 struct remote_state *rs = get_remote_state ();
12678 char *p;
12679
12680 /* Ask for a first packet of tracepoint definition. */
12681 putpkt ("qTfP");
12682 getpkt (&rs->buf, &rs->buf_size, 0);
12683 p = rs->buf;
12684 while (*p && *p != 'l')
12685 {
12686 parse_tracepoint_definition (p, utpp);
12687 /* Ask for another packet of tracepoint definition. */
12688 putpkt ("qTsP");
12689 getpkt (&rs->buf, &rs->buf_size, 0);
12690 p = rs->buf;
12691 }
12692 return 0;
12693}
12694
12695static int
25e4902b
AHJ
12696remote_upload_trace_state_variables (struct target_ops *self,
12697 struct uploaded_tsv **utsvp)
cf7f2e2d
JM
12698{
12699 struct remote_state *rs = get_remote_state ();
12700 char *p;
12701
12702 /* Ask for a first packet of variable definition. */
12703 putpkt ("qTfV");
12704 getpkt (&rs->buf, &rs->buf_size, 0);
12705 p = rs->buf;
12706 while (*p && *p != 'l')
12707 {
12708 parse_tsv_definition (p, utsvp);
12709 /* Ask for another packet of variable definition. */
12710 putpkt ("qTsV");
12711 getpkt (&rs->buf, &rs->buf_size, 0);
12712 p = rs->buf;
12713 }
12714 return 0;
12715}
12716
25e4902b
AHJ
12717/* The "set/show range-stepping" show hook. */
12718
12719static void
12720show_range_stepping (struct ui_file *file, int from_tty,
12721 struct cmd_list_element *c,
12722 const char *value)
12723{
12724 fprintf_filtered (file,
12725 _("Debugger's willingness to use range stepping "
12726 "is %s.\n"), value);
12727}
12728
12729/* The "set/show range-stepping" set hook. */
12730
12731static void
12732set_range_stepping (char *ignore_args, int from_tty,
12733 struct cmd_list_element *c)
12734{
12735 struct remote_state *rs = get_remote_state ();
12736
12737 /* Whene enabling, check whether range stepping is actually
12738 supported by the target, and warn if not. */
12739 if (use_range_stepping)
12740 {
12741 if (rs->remote_desc != NULL)
12742 {
12743 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12744 remote_vcont_probe (rs);
12745
12746 if (packet_support (PACKET_vCont) == PACKET_ENABLE
12747 && rs->supports_vCont.r)
12748 return;
12749 }
12750
12751 warning (_("Range stepping is not supported by the current target"));
12752 }
12753}
12754
5796c8dc
SS
12755void
12756_initialize_remote (void)
12757{
12758 struct remote_state *rs;
cf7f2e2d 12759 struct cmd_list_element *cmd;
25e4902b 12760 const char *cmd_name;
5796c8dc
SS
12761
12762 /* architecture specific data */
12763 remote_gdbarch_data_handle =
12764 gdbarch_data_register_post_init (init_remote_state);
12765 remote_g_packet_data_handle =
12766 gdbarch_data_register_pre_init (remote_g_packet_data_init);
12767
12768 /* Initialize the per-target state. At the moment there is only one
12769 of these, not one per target. Only one target is active at a
25e4902b
AHJ
12770 time. */
12771 remote_state = new_remote_state ();
5796c8dc
SS
12772
12773 init_remote_ops ();
12774 add_target (&remote_ops);
12775
12776 init_extended_remote_ops ();
12777 add_target (&extended_remote_ops);
12778
12779 /* Hook into new objfile notification. */
12780 observer_attach_new_objfile (remote_new_objfile);
ef5ccd6c
JM
12781 /* We're no longer interested in notification events of an inferior
12782 when it exits. */
12783 observer_attach_inferior_exit (discard_pending_stop_replies);
5796c8dc
SS
12784
12785 /* Set up signal handlers. */
25e4902b 12786 async_sigint_remote_token =
5796c8dc 12787 create_async_signal_handler (async_remote_interrupt, NULL);
25e4902b 12788 async_sigint_remote_twice_token =
a45ae5f8 12789 create_async_signal_handler (async_remote_interrupt_twice, NULL);
5796c8dc
SS
12790
12791#if 0
12792 init_remote_threadtests ();
12793#endif
12794
ef5ccd6c 12795 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
5796c8dc
SS
12796 /* set/show remote ... */
12797
12798 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12799Remote protocol specific variables\n\
12800Configure various remote-protocol specific variables such as\n\
12801the packets being used"),
12802 &remote_set_cmdlist, "set remote ",
12803 0 /* allow-unknown */, &setlist);
12804 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12805Remote protocol specific variables\n\
12806Configure various remote-protocol specific variables such as\n\
12807the packets being used"),
12808 &remote_show_cmdlist, "show remote ",
12809 0 /* allow-unknown */, &showlist);
12810
12811 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12812Compare section data on target to the exec file.\n\
25e4902b
AHJ
12813Argument is a single section name (default: all loaded sections).\n\
12814To compare only read-only loaded sections, specify the -r option."),
5796c8dc
SS
12815 &cmdlist);
12816
12817 add_cmd ("packet", class_maintenance, packet_command, _("\
12818Send an arbitrary packet to a remote target.\n\
12819 maintenance packet TEXT\n\
12820If GDB is talking to an inferior via the GDB serial protocol, then\n\
12821this command sends the string TEXT to the inferior, and displays the\n\
12822response packet. GDB supplies the initial `$' character, and the\n\
12823terminating `#' character and checksum."),
12824 &maintenancelist);
12825
12826 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12827Set whether to send break if interrupted."), _("\
12828Show whether to send break if interrupted."), _("\
12829If set, a break, instead of a cntrl-c, is sent to the remote target."),
cf7f2e2d 12830 set_remotebreak, show_remotebreak,
5796c8dc 12831 &setlist, &showlist);
cf7f2e2d
JM
12832 cmd_name = "remotebreak";
12833 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12834 deprecate_cmd (cmd, "set remote interrupt-sequence");
12835 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12836 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12837 deprecate_cmd (cmd, "show remote interrupt-sequence");
12838
12839 add_setshow_enum_cmd ("interrupt-sequence", class_support,
c50c785c
JM
12840 interrupt_sequence_modes, &interrupt_sequence_mode,
12841 _("\
cf7f2e2d
JM
12842Set interrupt sequence to remote target."), _("\
12843Show interrupt sequence to remote target."), _("\
12844Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12845 NULL, show_interrupt_sequence,
12846 &remote_set_cmdlist,
12847 &remote_show_cmdlist);
12848
12849 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12850 &interrupt_on_connect, _("\
12851Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12852Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12853If set, interrupt sequence is sent to remote target."),
12854 NULL, NULL,
12855 &remote_set_cmdlist, &remote_show_cmdlist);
5796c8dc
SS
12856
12857 /* Install commands for configuring memory read/write packets. */
12858
12859 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12860Set the maximum number of bytes per memory write packet (deprecated)."),
12861 &setlist);
12862 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12863Show the maximum number of bytes per memory write packet (deprecated)."),
12864 &showlist);
12865 add_cmd ("memory-write-packet-size", no_class,
12866 set_memory_write_packet_size, _("\
12867Set the maximum number of bytes per memory-write packet.\n\
12868Specify the number of bytes in a packet or 0 (zero) for the\n\
12869default packet size. The actual limit is further reduced\n\
12870dependent on the target. Specify ``fixed'' to disable the\n\
12871further restriction and ``limit'' to enable that restriction."),
12872 &remote_set_cmdlist);
12873 add_cmd ("memory-read-packet-size", no_class,
12874 set_memory_read_packet_size, _("\
12875Set the maximum number of bytes per memory-read packet.\n\
12876Specify the number of bytes in a packet or 0 (zero) for the\n\
12877default packet size. The actual limit is further reduced\n\
12878dependent on the target. Specify ``fixed'' to disable the\n\
12879further restriction and ``limit'' to enable that restriction."),
12880 &remote_set_cmdlist);
12881 add_cmd ("memory-write-packet-size", no_class,
12882 show_memory_write_packet_size,
12883 _("Show the maximum number of bytes per memory-write packet."),
12884 &remote_show_cmdlist);
12885 add_cmd ("memory-read-packet-size", no_class,
12886 show_memory_read_packet_size,
12887 _("Show the maximum number of bytes per memory-read packet."),
12888 &remote_show_cmdlist);
12889
12890 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12891 &remote_hw_watchpoint_limit, _("\
12892Set the maximum number of target hardware watchpoints."), _("\
12893Show the maximum number of target hardware watchpoints."), _("\
12894Specify a negative limit for unlimited."),
c50c785c
JM
12895 NULL, NULL, /* FIXME: i18n: The maximum
12896 number of target hardware
12897 watchpoints is %s. */
5796c8dc 12898 &remote_set_cmdlist, &remote_show_cmdlist);
a45ae5f8
JM
12899 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12900 &remote_hw_watchpoint_length_limit, _("\
12901Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12902Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12903Specify a negative limit for unlimited."),
12904 NULL, NULL, /* FIXME: i18n: The maximum
12905 length (in bytes) of a target
12906 hardware watchpoint is %s. */
12907 &remote_set_cmdlist, &remote_show_cmdlist);
5796c8dc
SS
12908 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12909 &remote_hw_breakpoint_limit, _("\
12910Set the maximum number of target hardware breakpoints."), _("\
12911Show the maximum number of target hardware breakpoints."), _("\
12912Specify a negative limit for unlimited."),
c50c785c
JM
12913 NULL, NULL, /* FIXME: i18n: The maximum
12914 number of target hardware
12915 breakpoints is %s. */
5796c8dc
SS
12916 &remote_set_cmdlist, &remote_show_cmdlist);
12917
25e4902b
AHJ
12918 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12919 &remote_address_size, _("\
5796c8dc
SS
12920Set the maximum size of the address (in bits) in a memory packet."), _("\
12921Show the maximum size of the address (in bits) in a memory packet."), NULL,
25e4902b
AHJ
12922 NULL,
12923 NULL, /* FIXME: i18n: */
12924 &setlist, &showlist);
12925
12926 init_all_packet_configs ();
5796c8dc
SS
12927
12928 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12929 "X", "binary-download", 1);
12930
12931 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12932 "vCont", "verbose-resume", 0);
12933
12934 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12935 "QPassSignals", "pass-signals", 0);
12936
ef5ccd6c
JM
12937 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12938 "QProgramSignals", "program-signals", 0);
12939
5796c8dc
SS
12940 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12941 "qSymbol", "symbol-lookup", 0);
12942
12943 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12944 "P", "set-register", 1);
12945
12946 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12947 "p", "fetch-register", 1);
12948
12949 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12950 "Z0", "software-breakpoint", 0);
12951
12952 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12953 "Z1", "hardware-breakpoint", 0);
12954
12955 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12956 "Z2", "write-watchpoint", 0);
12957
12958 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12959 "Z3", "read-watchpoint", 0);
12960
12961 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12962 "Z4", "access-watchpoint", 0);
12963
12964 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12965 "qXfer:auxv:read", "read-aux-vector", 0);
12966
25e4902b
AHJ
12967 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
12968 "qXfer:exec-file:read", "pid-to-exec-file", 0);
12969
5796c8dc
SS
12970 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12971 "qXfer:features:read", "target-features", 0);
12972
12973 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12974 "qXfer:libraries:read", "library-info", 0);
12975
a45ae5f8
JM
12976 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12977 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12978
5796c8dc
SS
12979 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12980 "qXfer:memory-map:read", "memory-map", 0);
12981
12982 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12983 "qXfer:spu:read", "read-spu-object", 0);
12984
12985 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12986 "qXfer:spu:write", "write-spu-object", 0);
12987
12988 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12989 "qXfer:osdata:read", "osdata", 0);
12990
cf7f2e2d
JM
12991 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12992 "qXfer:threads:read", "threads", 0);
12993
5796c8dc
SS
12994 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12995 "qXfer:siginfo:read", "read-siginfo-object", 0);
12996
12997 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12998 "qXfer:siginfo:write", "write-siginfo-object", 0);
12999
c50c785c
JM
13000 add_packet_config_cmd
13001 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
25e4902b 13002 "qXfer:traceframe-info:read", "traceframe-info", 0);
c50c785c 13003
ef5ccd6c
JM
13004 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13005 "qXfer:uib:read", "unwind-info-block", 0);
13006
5796c8dc
SS
13007 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13008 "qGetTLSAddr", "get-thread-local-storage-address",
13009 0);
13010
cf7f2e2d
JM
13011 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13012 "qGetTIBAddr", "get-thread-information-block-address",
13013 0);
13014
5796c8dc
SS
13015 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13016 "bc", "reverse-continue", 0);
13017
13018 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13019 "bs", "reverse-step", 0);
13020
13021 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13022 "qSupported", "supported-packets", 0);
13023
13024 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13025 "qSearch:memory", "search-memory", 0);
13026
25e4902b
AHJ
13027 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13028 "qTStatus", "trace-status", 0);
13029
13030 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13031 "vFile:setfs", "hostio-setfs", 0);
13032
5796c8dc
SS
13033 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13034 "vFile:open", "hostio-open", 0);
13035
13036 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13037 "vFile:pread", "hostio-pread", 0);
13038
13039 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13040 "vFile:pwrite", "hostio-pwrite", 0);
13041
13042 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13043 "vFile:close", "hostio-close", 0);
13044
13045 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13046 "vFile:unlink", "hostio-unlink", 0);
13047
ef5ccd6c
JM
13048 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13049 "vFile:readlink", "hostio-readlink", 0);
13050
25e4902b
AHJ
13051 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13052 "vFile:fstat", "hostio-fstat", 0);
13053
5796c8dc
SS
13054 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13055 "vAttach", "attach", 0);
13056
13057 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13058 "vRun", "run", 0);
13059
13060 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13061 "QStartNoAckMode", "noack", 0);
13062
13063 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13064 "vKill", "kill", 0);
13065
13066 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13067 "qAttached", "query-attached", 0);
13068
13069 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
c50c785c
JM
13070 "ConditionalTracepoints",
13071 "conditional-tracepoints", 0);
ef5ccd6c
JM
13072
13073 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13074 "ConditionalBreakpoints",
13075 "conditional-breakpoints", 0);
13076
13077 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13078 "BreakpointCommands",
13079 "breakpoint-commands", 0);
13080
cf7f2e2d
JM
13081 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13082 "FastTracepoints", "fast-tracepoints", 0);
13083
13084 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13085 "TracepointSource", "TracepointSource", 0);
13086
13087 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13088 "QAllow", "allow", 0);
13089
13090 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13091 "StaticTracepoints", "static-tracepoints", 0);
13092
a45ae5f8
JM
13093 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13094 "InstallInTrace", "install-in-trace", 0);
13095
cf7f2e2d
JM
13096 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13097 "qXfer:statictrace:read", "read-sdata-object", 0);
5796c8dc 13098
a45ae5f8
JM
13099 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13100 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13101
13102 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13103 "QDisableRandomization", "disable-randomization", 0);
13104
ef5ccd6c
JM
13105 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13106 "QAgent", "agent", 0);
13107
13108 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13109 "QTBuffer:size", "trace-buffer-size", 0);
13110
13111 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13112 "Qbtrace:off", "disable-btrace", 0);
13113
13114 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
25e4902b
AHJ
13115 "Qbtrace:bts", "enable-btrace-bts", 0);
13116
13117 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13118 "Qbtrace:pt", "enable-btrace-pt", 0);
ef5ccd6c
JM
13119
13120 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13121 "qXfer:btrace", "read-btrace", 0);
13122
25e4902b
AHJ
13123 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13124 "qXfer:btrace-conf", "read-btrace-conf", 0);
13125
13126 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13127 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13128
13129 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13130 "swbreak-feature", "swbreak-feature", 0);
13131
13132 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13133 "hwbreak-feature", "hwbreak-feature", 0);
13134
13135 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13136 "fork-event-feature", "fork-event-feature", 0);
13137
13138 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13139 "vfork-event-feature", "vfork-event-feature", 0);
13140
13141 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13142 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13143
13144 /* Assert that we've registered "set remote foo-packet" commands
13145 for all packet configs. */
13146 {
13147 int i;
13148
13149 for (i = 0; i < PACKET_MAX; i++)
13150 {
13151 /* Ideally all configs would have a command associated. Some
13152 still don't though. */
13153 int excepted;
13154
13155 switch (i)
13156 {
13157 case PACKET_QNonStop:
13158 case PACKET_multiprocess_feature:
13159 case PACKET_EnableDisableTracepoints_feature:
13160 case PACKET_tracenz_feature:
13161 case PACKET_DisconnectedTracing_feature:
13162 case PACKET_augmented_libraries_svr4_read_feature:
13163 case PACKET_qCRC:
13164 /* Additions to this list need to be well justified:
13165 pre-existing packets are OK; new packets are not. */
13166 excepted = 1;
13167 break;
13168 default:
13169 excepted = 0;
13170 break;
13171 }
13172
13173 /* This catches both forgetting to add a config command, and
13174 forgetting to remove a packet from the exception list. */
13175 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13176 }
13177 }
13178
5796c8dc
SS
13179 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13180 Z sub-packet has its own set and show commands, but users may
13181 have sets to this variable in their .gdbinit files (or in their
13182 documentation). */
13183 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13184 &remote_Z_packet_detect, _("\
13185Set use of remote protocol `Z' packets"), _("\
13186Show use of remote protocol `Z' packets "), _("\
13187When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13188packets."),
13189 set_remote_protocol_Z_packet_cmd,
c50c785c
JM
13190 show_remote_protocol_Z_packet_cmd,
13191 /* FIXME: i18n: Use of remote protocol
13192 `Z' packets is %s. */
5796c8dc
SS
13193 &remote_set_cmdlist, &remote_show_cmdlist);
13194
13195 add_prefix_cmd ("remote", class_files, remote_command, _("\
13196Manipulate files on the remote system\n\
13197Transfer files to and from the remote target system."),
13198 &remote_cmdlist, "remote ",
13199 0 /* allow-unknown */, &cmdlist);
13200
13201 add_cmd ("put", class_files, remote_put_command,
13202 _("Copy a local file to the remote system."),
13203 &remote_cmdlist);
13204
13205 add_cmd ("get", class_files, remote_get_command,
13206 _("Copy a remote file to the local system."),
13207 &remote_cmdlist);
13208
13209 add_cmd ("delete", class_files, remote_delete_command,
13210 _("Delete a remote file."),
13211 &remote_cmdlist);
13212
13213 remote_exec_file = xstrdup ("");
13214 add_setshow_string_noescape_cmd ("exec-file", class_files,
13215 &remote_exec_file, _("\
13216Set the remote pathname for \"run\""), _("\
13217Show the remote pathname for \"run\""), NULL, NULL, NULL,
13218 &remote_set_cmdlist, &remote_show_cmdlist);
13219
25e4902b
AHJ
13220 add_setshow_boolean_cmd ("range-stepping", class_run,
13221 &use_range_stepping, _("\
13222Enable or disable range stepping."), _("\
13223Show whether target-assisted range stepping is enabled."), _("\
13224If on, and the target supports it, when stepping a source line, GDB\n\
13225tells the target to step the corresponding range of addresses itself instead\n\
13226of issuing multiple single-steps. This speeds up source level\n\
13227stepping. If off, GDB always issues single-steps, even if range\n\
13228stepping is supported by the target. The default is on."),
13229 set_range_stepping,
13230 show_range_stepping,
13231 &setlist,
13232 &showlist);
13233
5796c8dc
SS
13234 /* Eventually initialize fileio. See fileio.c */
13235 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13236
25e4902b 13237 /* Take advantage of the fact that the TID field is not used, to tag
5796c8dc 13238 special ptids with it set to != 0. */
25e4902b
AHJ
13239 magic_null_ptid = ptid_build (42000, -1, 1);
13240 not_sent_ptid = ptid_build (42000, -2, 1);
13241 any_thread_ptid = ptid_build (42000, 0, 1);
cf7f2e2d
JM
13242
13243 target_buf_size = 2048;
13244 target_buf = xmalloc (target_buf_size);
5796c8dc 13245}
cf7f2e2d 13246