]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame_incremental - gdb/remote.c
Introduce string_appendf/string_vappendf
[thirdparty/binutils-gdb.git] / gdb / remote.c
... / ...
CommitLineData
1/* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2017 Free Software Foundation, Inc.
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"
23#include <ctype.h>
24#include <fcntl.h>
25#include "inferior.h"
26#include "infrun.h"
27#include "bfd.h"
28#include "symfile.h"
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"
36#include "remote-notif.h"
37#include "regcache.h"
38#include "value.h"
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"
44#include "gdb_bfd.h"
45#include "filestuff.h"
46#include "rsp-low.h"
47#include "disasm.h"
48#include "location.h"
49
50#include "gdb_sys_time.h"
51
52#include "event-loop.h"
53#include "event-top.h"
54#include "inf-loop.h"
55
56#include <signal.h>
57#include "serial.h"
58
59#include "gdbcore.h" /* for exec_bfd */
60
61#include "remote-fileio.h"
62#include "gdb/fileio.h"
63#include <sys/stat.h>
64#include "xml-support.h"
65
66#include "memory-map.h"
67
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
71#include "agent.h"
72#include "btrace.h"
73#include "record-btrace.h"
74#include <algorithm>
75#include "common/scoped_restore.h"
76#include "environ.h"
77#include "common/byte-vector.h"
78
79/* Per-program-space data key. */
80static const struct program_space_data *remote_pspace_data;
81
82/* The variable registered as the control variable used by the
83 remote exec-file commands. While the remote exec-file setting is
84 per-program-space, the set/show machinery uses this as the
85 location of the remote exec-file value. */
86static char *remote_exec_file_var;
87
88/* The size to align memory write packets, when practical. The protocol
89 does not guarantee any alignment, and gdb will generate short
90 writes and unaligned writes, but even as a best-effort attempt this
91 can improve bulk transfers. For instance, if a write is misaligned
92 relative to the target's data bus, the stub may need to make an extra
93 round trip fetching data from the target. This doesn't make a
94 huge difference, but it's easy to do, so we try to be helpful.
95
96 The alignment chosen is arbitrary; usually data bus width is
97 important here, not the possibly larger cache line size. */
98enum { REMOTE_ALIGN_WRITES = 16 };
99
100/* Prototypes for local functions. */
101static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
102static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
103 int forever, int *is_notif);
104
105static void remote_files_info (struct target_ops *ignore);
106
107static void remote_prepare_to_store (struct target_ops *self,
108 struct regcache *regcache);
109
110static void remote_open_1 (const char *, int, struct target_ops *,
111 int extended_p);
112
113static void remote_close (struct target_ops *self);
114
115struct remote_state;
116
117static int remote_vkill (int pid, struct remote_state *rs);
118
119static void remote_kill_k (void);
120
121static void remote_mourn (struct target_ops *ops);
122
123static void extended_remote_restart (void);
124
125static void remote_send (char **buf, long *sizeof_buf_p);
126
127static int readchar (int timeout);
128
129static void remote_serial_write (const char *str, int len);
130
131static void remote_kill (struct target_ops *ops);
132
133static int remote_can_async_p (struct target_ops *);
134
135static int remote_is_async_p (struct target_ops *);
136
137static void remote_async (struct target_ops *ops, int enable);
138
139static void remote_thread_events (struct target_ops *ops, int enable);
140
141static void interrupt_query (void);
142
143static void set_general_thread (ptid_t ptid);
144static void set_continue_thread (ptid_t ptid);
145
146static void get_offsets (void);
147
148static void skip_frame (void);
149
150static long read_frame (char **buf_p, long *sizeof_buf);
151
152static int hexnumlen (ULONGEST num);
153
154static void init_remote_ops (void);
155
156static void init_extended_remote_ops (void);
157
158static void remote_stop (struct target_ops *self, ptid_t);
159
160static int stubhex (int ch);
161
162static int hexnumstr (char *, ULONGEST);
163
164static int hexnumnstr (char *, ULONGEST, int);
165
166static CORE_ADDR remote_address_masked (CORE_ADDR);
167
168static void print_packet (const char *);
169
170static int stub_unpack_int (char *buff, int fieldlength);
171
172static ptid_t remote_current_thread (ptid_t oldptid);
173
174static int putpkt_binary (const char *buf, int cnt);
175
176static void check_binary_download (CORE_ADDR addr);
177
178struct packet_config;
179
180static void show_packet_config_cmd (struct packet_config *config);
181
182static void show_remote_protocol_packet_cmd (struct ui_file *file,
183 int from_tty,
184 struct cmd_list_element *c,
185 const char *value);
186
187static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
188static ptid_t read_ptid (const char *buf, const char **obuf);
189
190static void remote_set_permissions (struct target_ops *self);
191
192static int remote_get_trace_status (struct target_ops *self,
193 struct trace_status *ts);
194
195static int remote_upload_tracepoints (struct target_ops *self,
196 struct uploaded_tp **utpp);
197
198static int remote_upload_trace_state_variables (struct target_ops *self,
199 struct uploaded_tsv **utsvp);
200
201static void remote_query_supported (void);
202
203static void remote_check_symbols (void);
204
205struct stop_reply;
206static void stop_reply_xfree (struct stop_reply *);
207static void remote_parse_stop_reply (char *, struct stop_reply *);
208static void push_stop_reply (struct stop_reply *);
209static void discard_pending_stop_replies_in_queue (struct remote_state *);
210static int peek_stop_reply (ptid_t ptid);
211
212struct threads_listing_context;
213static void remove_new_fork_children (struct threads_listing_context *);
214
215static void remote_async_inferior_event_handler (gdb_client_data);
216
217static void remote_terminal_ours (struct target_ops *self);
218
219static int remote_read_description_p (struct target_ops *target);
220
221static void remote_console_output (char *msg);
222
223static int remote_supports_cond_breakpoints (struct target_ops *self);
224
225static int remote_can_run_breakpoint_commands (struct target_ops *self);
226
227static void remote_btrace_reset (void);
228
229static void remote_btrace_maybe_reopen (void);
230
231static int stop_reply_queue_length (void);
232
233static void readahead_cache_invalidate (void);
234
235static void remote_unpush_and_throw (void);
236
237static struct remote_state *get_remote_state (void);
238
239/* For "remote". */
240
241static struct cmd_list_element *remote_cmdlist;
242
243/* For "set remote" and "show remote". */
244
245static struct cmd_list_element *remote_set_cmdlist;
246static struct cmd_list_element *remote_show_cmdlist;
247
248/* Stub vCont actions support.
249
250 Each field is a boolean flag indicating whether the stub reports
251 support for the corresponding action. */
252
253struct vCont_action_support
254{
255 /* vCont;t */
256 int t;
257
258 /* vCont;r */
259 int r;
260
261 /* vCont;s */
262 int s;
263
264 /* vCont;S */
265 int S;
266};
267
268/* Controls whether GDB is willing to use range stepping. */
269
270static int use_range_stepping = 1;
271
272#define OPAQUETHREADBYTES 8
273
274/* a 64 bit opaque identifier */
275typedef unsigned char threadref[OPAQUETHREADBYTES];
276
277/* About this many threadisds fit in a packet. */
278
279#define MAXTHREADLISTRESULTS 32
280
281/* The max number of chars in debug output. The rest of chars are
282 omitted. */
283
284#define REMOTE_DEBUG_MAX_CHAR 512
285
286/* Data for the vFile:pread readahead cache. */
287
288struct readahead_cache
289{
290 /* The file descriptor for the file that is being cached. -1 if the
291 cache is invalid. */
292 int fd;
293
294 /* The offset into the file that the cache buffer corresponds
295 to. */
296 ULONGEST offset;
297
298 /* The buffer holding the cache contents. */
299 gdb_byte *buf;
300 /* The buffer's size. We try to read as much as fits into a packet
301 at a time. */
302 size_t bufsize;
303
304 /* Cache hit and miss counters. */
305 ULONGEST hit_count;
306 ULONGEST miss_count;
307};
308
309/* Description of the remote protocol state for the currently
310 connected target. This is per-target state, and independent of the
311 selected architecture. */
312
313struct remote_state
314{
315 /* A buffer to use for incoming packets, and its current size. The
316 buffer is grown dynamically for larger incoming packets.
317 Outgoing packets may also be constructed in this buffer.
318 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320 packets. */
321 char *buf;
322 long buf_size;
323
324 /* True if we're going through initial connection setup (finding out
325 about the remote side's threads, relocating symbols, etc.). */
326 int starting_up;
327
328 /* If we negotiated packet size explicitly (and thus can bypass
329 heuristics for the largest packet size that will not overflow
330 a buffer in the stub), this will be set to that packet size.
331 Otherwise zero, meaning to use the guessed size. */
332 long explicit_packet_size;
333
334 /* remote_wait is normally called when the target is running and
335 waits for a stop reply packet. But sometimes we need to call it
336 when the target is already stopped. We can send a "?" packet
337 and have remote_wait read the response. Or, if we already have
338 the response, we can stash it in BUF and tell remote_wait to
339 skip calling getpkt. This flag is set when BUF contains a
340 stop reply packet and the target is not waiting. */
341 int cached_wait_status;
342
343 /* True, if in no ack mode. That is, neither GDB nor the stub will
344 expect acks from each other. The connection is assumed to be
345 reliable. */
346 int noack_mode;
347
348 /* True if we're connected in extended remote mode. */
349 int extended;
350
351 /* True if we resumed the target and we're waiting for the target to
352 stop. In the mean time, we can't start another command/query.
353 The remote server wouldn't be ready to process it, so we'd
354 timeout waiting for a reply that would never come and eventually
355 we'd close the connection. This can happen in asynchronous mode
356 because we allow GDB commands while the target is running. */
357 int waiting_for_stop_reply;
358
359 /* The status of the stub support for the various vCont actions. */
360 struct vCont_action_support supports_vCont;
361
362 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363 responded to that. */
364 int ctrlc_pending_p;
365
366 /* True if we saw a Ctrl-C while reading or writing from/to the
367 remote descriptor. At that point it is not safe to send a remote
368 interrupt packet, so we instead remember we saw the Ctrl-C and
369 process it once we're done with sending/receiving the current
370 packet, which should be shortly. If however that takes too long,
371 and the user presses Ctrl-C again, we offer to disconnect. */
372 int got_ctrlc_during_io;
373
374 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
375 remote_open knows that we don't have a file open when the program
376 starts. */
377 struct serial *remote_desc;
378
379 /* These are the threads which we last sent to the remote system. The
380 TID member will be -1 for all or -2 for not sent yet. */
381 ptid_t general_thread;
382 ptid_t continue_thread;
383
384 /* This is the traceframe which we last selected on the remote system.
385 It will be -1 if no traceframe is selected. */
386 int remote_traceframe_number;
387
388 char *last_pass_packet;
389
390 /* The last QProgramSignals packet sent to the target. We bypass
391 sending a new program signals list down to the target if the new
392 packet is exactly the same as the last we sent. IOW, we only let
393 the target know about program signals list changes. */
394 char *last_program_signals_packet;
395
396 enum gdb_signal last_sent_signal;
397
398 int last_sent_step;
399
400 /* The execution direction of the last resume we got. */
401 enum exec_direction_kind last_resume_exec_dir;
402
403 char *finished_object;
404 char *finished_annex;
405 ULONGEST finished_offset;
406
407 /* Should we try the 'ThreadInfo' query packet?
408
409 This variable (NOT available to the user: auto-detect only!)
410 determines whether GDB will use the new, simpler "ThreadInfo"
411 query or the older, more complex syntax for thread queries.
412 This is an auto-detect variable (set to true at each connect,
413 and set to false when the target fails to recognize it). */
414 int use_threadinfo_query;
415 int use_threadextra_query;
416
417 threadref echo_nextthread;
418 threadref nextthread;
419 threadref resultthreadlist[MAXTHREADLISTRESULTS];
420
421 /* The state of remote notification. */
422 struct remote_notif_state *notif_state;
423
424 /* The branch trace configuration. */
425 struct btrace_config btrace_config;
426
427 /* The argument to the last "vFile:setfs:" packet we sent, used
428 to avoid sending repeated unnecessary "vFile:setfs:" packets.
429 Initialized to -1 to indicate that no "vFile:setfs:" packet
430 has yet been sent. */
431 int fs_pid;
432
433 /* A readahead cache for vFile:pread. Often, reading a binary
434 involves a sequence of small reads. E.g., when parsing an ELF
435 file. A readahead cache helps mostly the case of remote
436 debugging on a connection with higher latency, due to the
437 request/reply nature of the RSP. We only cache data for a single
438 file descriptor at a time. */
439 struct readahead_cache readahead_cache;
440};
441
442/* Private data that we'll store in (struct thread_info)->private. */
443struct private_thread_info
444{
445 char *extra;
446 char *name;
447 int core;
448
449 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
450 sequence of bytes. */
451 gdb::byte_vector *thread_handle;
452
453 /* Whether the target stopped for a breakpoint/watchpoint. */
454 enum target_stop_reason stop_reason;
455
456 /* This is set to the data address of the access causing the target
457 to stop for a watchpoint. */
458 CORE_ADDR watch_data_address;
459
460 /* Fields used by the vCont action coalescing implemented in
461 remote_resume / remote_commit_resume. remote_resume stores each
462 thread's last resume request in these fields, so that a later
463 remote_commit_resume knows which is the proper action for this
464 thread to include in the vCont packet. */
465
466 /* True if the last target_resume call for this thread was a step
467 request, false if a continue request. */
468 int last_resume_step;
469
470 /* The signal specified in the last target_resume call for this
471 thread. */
472 enum gdb_signal last_resume_sig;
473
474 /* Whether this thread was already vCont-resumed on the remote
475 side. */
476 int vcont_resumed;
477};
478
479static void
480free_private_thread_info (struct private_thread_info *info)
481{
482 xfree (info->extra);
483 xfree (info->name);
484 delete info->thread_handle;
485 xfree (info);
486}
487
488/* This data could be associated with a target, but we do not always
489 have access to the current target when we need it, so for now it is
490 static. This will be fine for as long as only one target is in use
491 at a time. */
492static struct remote_state *remote_state;
493
494static struct remote_state *
495get_remote_state_raw (void)
496{
497 return remote_state;
498}
499
500/* Allocate a new struct remote_state with xmalloc, initialize it, and
501 return it. */
502
503static struct remote_state *
504new_remote_state (void)
505{
506 struct remote_state *result = XCNEW (struct remote_state);
507
508 /* The default buffer size is unimportant; it will be expanded
509 whenever a larger buffer is needed. */
510 result->buf_size = 400;
511 result->buf = (char *) xmalloc (result->buf_size);
512 result->remote_traceframe_number = -1;
513 result->last_sent_signal = GDB_SIGNAL_0;
514 result->last_resume_exec_dir = EXEC_FORWARD;
515 result->fs_pid = -1;
516
517 return result;
518}
519
520/* Description of the remote protocol for a given architecture. */
521
522struct packet_reg
523{
524 long offset; /* Offset into G packet. */
525 long regnum; /* GDB's internal register number. */
526 LONGEST pnum; /* Remote protocol register number. */
527 int in_g_packet; /* Always part of G packet. */
528 /* long size in bytes; == register_size (target_gdbarch (), regnum);
529 at present. */
530 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
531 at present. */
532};
533
534struct remote_arch_state
535{
536 /* Description of the remote protocol registers. */
537 long sizeof_g_packet;
538
539 /* Description of the remote protocol registers indexed by REGNUM
540 (making an array gdbarch_num_regs in size). */
541 struct packet_reg *regs;
542
543 /* This is the size (in chars) of the first response to the ``g''
544 packet. It is used as a heuristic when determining the maximum
545 size of memory-read and memory-write packets. A target will
546 typically only reserve a buffer large enough to hold the ``g''
547 packet. The size does not include packet overhead (headers and
548 trailers). */
549 long actual_register_packet_size;
550
551 /* This is the maximum size (in chars) of a non read/write packet.
552 It is also used as a cap on the size of read/write packets. */
553 long remote_packet_size;
554};
555
556/* Utility: generate error from an incoming stub packet. */
557static void
558trace_error (char *buf)
559{
560 if (*buf++ != 'E')
561 return; /* not an error msg */
562 switch (*buf)
563 {
564 case '1': /* malformed packet error */
565 if (*++buf == '0') /* general case: */
566 error (_("remote.c: error in outgoing packet."));
567 else
568 error (_("remote.c: error in outgoing packet at field #%ld."),
569 strtol (buf, NULL, 16));
570 default:
571 error (_("Target returns error code '%s'."), buf);
572 }
573}
574
575/* Utility: wait for reply from stub, while accepting "O" packets. */
576
577static char *
578remote_get_noisy_reply ()
579{
580 struct remote_state *rs = get_remote_state ();
581
582 do /* Loop on reply from remote stub. */
583 {
584 char *buf;
585
586 QUIT; /* Allow user to bail out with ^C. */
587 getpkt (&rs->buf, &rs->buf_size, 0);
588 buf = rs->buf;
589 if (buf[0] == 'E')
590 trace_error (buf);
591 else if (startswith (buf, "qRelocInsn:"))
592 {
593 ULONGEST ul;
594 CORE_ADDR from, to, org_to;
595 const char *p, *pp;
596 int adjusted_size = 0;
597 int relocated = 0;
598
599 p = buf + strlen ("qRelocInsn:");
600 pp = unpack_varlen_hex (p, &ul);
601 if (*pp != ';')
602 error (_("invalid qRelocInsn packet: %s"), buf);
603 from = ul;
604
605 p = pp + 1;
606 unpack_varlen_hex (p, &ul);
607 to = ul;
608
609 org_to = to;
610
611 TRY
612 {
613 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
614 relocated = 1;
615 }
616 CATCH (ex, RETURN_MASK_ALL)
617 {
618 if (ex.error == MEMORY_ERROR)
619 {
620 /* Propagate memory errors silently back to the
621 target. The stub may have limited the range of
622 addresses we can write to, for example. */
623 }
624 else
625 {
626 /* Something unexpectedly bad happened. Be verbose
627 so we can tell what, and propagate the error back
628 to the stub, so it doesn't get stuck waiting for
629 a response. */
630 exception_fprintf (gdb_stderr, ex,
631 _("warning: relocating instruction: "));
632 }
633 putpkt ("E01");
634 }
635 END_CATCH
636
637 if (relocated)
638 {
639 adjusted_size = to - org_to;
640
641 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
642 putpkt (buf);
643 }
644 }
645 else if (buf[0] == 'O' && buf[1] != 'K')
646 remote_console_output (buf + 1); /* 'O' message from stub */
647 else
648 return buf; /* Here's the actual reply. */
649 }
650 while (1);
651}
652
653/* Handle for retreving the remote protocol data from gdbarch. */
654static struct gdbarch_data *remote_gdbarch_data_handle;
655
656static struct remote_arch_state *
657get_remote_arch_state (struct gdbarch *gdbarch)
658{
659 gdb_assert (gdbarch != NULL);
660 return ((struct remote_arch_state *)
661 gdbarch_data (gdbarch, remote_gdbarch_data_handle));
662}
663
664/* Fetch the global remote target state. */
665
666static struct remote_state *
667get_remote_state (void)
668{
669 /* Make sure that the remote architecture state has been
670 initialized, because doing so might reallocate rs->buf. Any
671 function which calls getpkt also needs to be mindful of changes
672 to rs->buf, but this call limits the number of places which run
673 into trouble. */
674 get_remote_arch_state (target_gdbarch ());
675
676 return get_remote_state_raw ();
677}
678
679/* Cleanup routine for the remote module's pspace data. */
680
681static void
682remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
683{
684 char *remote_exec_file = (char *) arg;
685
686 xfree (remote_exec_file);
687}
688
689/* Fetch the remote exec-file from the current program space. */
690
691static const char *
692get_remote_exec_file (void)
693{
694 char *remote_exec_file;
695
696 remote_exec_file
697 = (char *) program_space_data (current_program_space,
698 remote_pspace_data);
699 if (remote_exec_file == NULL)
700 return "";
701
702 return remote_exec_file;
703}
704
705/* Set the remote exec file for PSPACE. */
706
707static void
708set_pspace_remote_exec_file (struct program_space *pspace,
709 char *remote_exec_file)
710{
711 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
712
713 xfree (old_file);
714 set_program_space_data (pspace, remote_pspace_data,
715 xstrdup (remote_exec_file));
716}
717
718/* The "set/show remote exec-file" set command hook. */
719
720static void
721set_remote_exec_file (char *ignored, int from_tty,
722 struct cmd_list_element *c)
723{
724 gdb_assert (remote_exec_file_var != NULL);
725 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
726}
727
728/* The "set/show remote exec-file" show command hook. */
729
730static void
731show_remote_exec_file (struct ui_file *file, int from_tty,
732 struct cmd_list_element *cmd, const char *value)
733{
734 fprintf_filtered (file, "%s\n", remote_exec_file_var);
735}
736
737static int
738compare_pnums (const void *lhs_, const void *rhs_)
739{
740 const struct packet_reg * const *lhs
741 = (const struct packet_reg * const *) lhs_;
742 const struct packet_reg * const *rhs
743 = (const struct packet_reg * const *) rhs_;
744
745 if ((*lhs)->pnum < (*rhs)->pnum)
746 return -1;
747 else if ((*lhs)->pnum == (*rhs)->pnum)
748 return 0;
749 else
750 return 1;
751}
752
753static int
754map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
755{
756 int regnum, num_remote_regs, offset;
757 struct packet_reg **remote_regs;
758
759 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
760 {
761 struct packet_reg *r = &regs[regnum];
762
763 if (register_size (gdbarch, regnum) == 0)
764 /* Do not try to fetch zero-sized (placeholder) registers. */
765 r->pnum = -1;
766 else
767 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
768
769 r->regnum = regnum;
770 }
771
772 /* Define the g/G packet format as the contents of each register
773 with a remote protocol number, in order of ascending protocol
774 number. */
775
776 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
777 for (num_remote_regs = 0, regnum = 0;
778 regnum < gdbarch_num_regs (gdbarch);
779 regnum++)
780 if (regs[regnum].pnum != -1)
781 remote_regs[num_remote_regs++] = &regs[regnum];
782
783 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
784 compare_pnums);
785
786 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
787 {
788 remote_regs[regnum]->in_g_packet = 1;
789 remote_regs[regnum]->offset = offset;
790 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
791 }
792
793 return offset;
794}
795
796/* Given the architecture described by GDBARCH, return the remote
797 protocol register's number and the register's offset in the g/G
798 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
799 If the target does not have a mapping for REGNUM, return false,
800 otherwise, return true. */
801
802int
803remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
804 int *pnum, int *poffset)
805{
806 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
807
808 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
809
810 map_regcache_remote_table (gdbarch, regs.data ());
811
812 *pnum = regs[regnum].pnum;
813 *poffset = regs[regnum].offset;
814
815 return *pnum != -1;
816}
817
818static void *
819init_remote_state (struct gdbarch *gdbarch)
820{
821 struct remote_state *rs = get_remote_state_raw ();
822 struct remote_arch_state *rsa;
823
824 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
825
826 /* Use the architecture to build a regnum<->pnum table, which will be
827 1:1 unless a feature set specifies otherwise. */
828 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
829 gdbarch_num_regs (gdbarch),
830 struct packet_reg);
831
832 /* Record the maximum possible size of the g packet - it may turn out
833 to be smaller. */
834 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
835
836 /* Default maximum number of characters in a packet body. Many
837 remote stubs have a hardwired buffer size of 400 bytes
838 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
839 as the maximum packet-size to ensure that the packet and an extra
840 NUL character can always fit in the buffer. This stops GDB
841 trashing stubs that try to squeeze an extra NUL into what is
842 already a full buffer (As of 1999-12-04 that was most stubs). */
843 rsa->remote_packet_size = 400 - 1;
844
845 /* This one is filled in when a ``g'' packet is received. */
846 rsa->actual_register_packet_size = 0;
847
848 /* Should rsa->sizeof_g_packet needs more space than the
849 default, adjust the size accordingly. Remember that each byte is
850 encoded as two characters. 32 is the overhead for the packet
851 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
852 (``$NN:G...#NN'') is a better guess, the below has been padded a
853 little. */
854 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
855 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
856
857 /* Make sure that the packet buffer is plenty big enough for
858 this architecture. */
859 if (rs->buf_size < rsa->remote_packet_size)
860 {
861 rs->buf_size = 2 * rsa->remote_packet_size;
862 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
863 }
864
865 return rsa;
866}
867
868/* Return the current allowed size of a remote packet. This is
869 inferred from the current architecture, and should be used to
870 limit the length of outgoing packets. */
871static long
872get_remote_packet_size (void)
873{
874 struct remote_state *rs = get_remote_state ();
875 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
876
877 if (rs->explicit_packet_size)
878 return rs->explicit_packet_size;
879
880 return rsa->remote_packet_size;
881}
882
883static struct packet_reg *
884packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
885 long regnum)
886{
887 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
888 return NULL;
889 else
890 {
891 struct packet_reg *r = &rsa->regs[regnum];
892
893 gdb_assert (r->regnum == regnum);
894 return r;
895 }
896}
897
898static struct packet_reg *
899packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
900 LONGEST pnum)
901{
902 int i;
903
904 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
905 {
906 struct packet_reg *r = &rsa->regs[i];
907
908 if (r->pnum == pnum)
909 return r;
910 }
911 return NULL;
912}
913
914static struct target_ops remote_ops;
915
916static struct target_ops extended_remote_ops;
917
918/* FIXME: cagney/1999-09-23: Even though getpkt was called with
919 ``forever'' still use the normal timeout mechanism. This is
920 currently used by the ASYNC code to guarentee that target reads
921 during the initial connect always time-out. Once getpkt has been
922 modified to return a timeout indication and, in turn
923 remote_wait()/wait_for_inferior() have gained a timeout parameter
924 this can go away. */
925static int wait_forever_enabled_p = 1;
926
927/* Allow the user to specify what sequence to send to the remote
928 when he requests a program interruption: Although ^C is usually
929 what remote systems expect (this is the default, here), it is
930 sometimes preferable to send a break. On other systems such
931 as the Linux kernel, a break followed by g, which is Magic SysRq g
932 is required in order to interrupt the execution. */
933const char interrupt_sequence_control_c[] = "Ctrl-C";
934const char interrupt_sequence_break[] = "BREAK";
935const char interrupt_sequence_break_g[] = "BREAK-g";
936static const char *const interrupt_sequence_modes[] =
937 {
938 interrupt_sequence_control_c,
939 interrupt_sequence_break,
940 interrupt_sequence_break_g,
941 NULL
942 };
943static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
944
945static void
946show_interrupt_sequence (struct ui_file *file, int from_tty,
947 struct cmd_list_element *c,
948 const char *value)
949{
950 if (interrupt_sequence_mode == interrupt_sequence_control_c)
951 fprintf_filtered (file,
952 _("Send the ASCII ETX character (Ctrl-c) "
953 "to the remote target to interrupt the "
954 "execution of the program.\n"));
955 else if (interrupt_sequence_mode == interrupt_sequence_break)
956 fprintf_filtered (file,
957 _("send a break signal to the remote target "
958 "to interrupt the execution of the program.\n"));
959 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
960 fprintf_filtered (file,
961 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
962 "the remote target to interrupt the execution "
963 "of Linux kernel.\n"));
964 else
965 internal_error (__FILE__, __LINE__,
966 _("Invalid value for interrupt_sequence_mode: %s."),
967 interrupt_sequence_mode);
968}
969
970/* This boolean variable specifies whether interrupt_sequence is sent
971 to the remote target when gdb connects to it.
972 This is mostly needed when you debug the Linux kernel: The Linux kernel
973 expects BREAK g which is Magic SysRq g for connecting gdb. */
974static int interrupt_on_connect = 0;
975
976/* This variable is used to implement the "set/show remotebreak" commands.
977 Since these commands are now deprecated in favor of "set/show remote
978 interrupt-sequence", it no longer has any effect on the code. */
979static int remote_break;
980
981static void
982set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
983{
984 if (remote_break)
985 interrupt_sequence_mode = interrupt_sequence_break;
986 else
987 interrupt_sequence_mode = interrupt_sequence_control_c;
988}
989
990static void
991show_remotebreak (struct ui_file *file, int from_tty,
992 struct cmd_list_element *c,
993 const char *value)
994{
995}
996
997/* This variable sets the number of bits in an address that are to be
998 sent in a memory ("M" or "m") packet. Normally, after stripping
999 leading zeros, the entire address would be sent. This variable
1000 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1001 initial implementation of remote.c restricted the address sent in
1002 memory packets to ``host::sizeof long'' bytes - (typically 32
1003 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1004 address was never sent. Since fixing this bug may cause a break in
1005 some remote targets this variable is principly provided to
1006 facilitate backward compatibility. */
1007
1008static unsigned int remote_address_size;
1009
1010\f
1011/* User configurable variables for the number of characters in a
1012 memory read/write packet. MIN (rsa->remote_packet_size,
1013 rsa->sizeof_g_packet) is the default. Some targets need smaller
1014 values (fifo overruns, et.al.) and some users need larger values
1015 (speed up transfers). The variables ``preferred_*'' (the user
1016 request), ``current_*'' (what was actually set) and ``forced_*''
1017 (Positive - a soft limit, negative - a hard limit). */
1018
1019struct memory_packet_config
1020{
1021 const char *name;
1022 long size;
1023 int fixed_p;
1024};
1025
1026/* The default max memory-write-packet-size. The 16k is historical.
1027 (It came from older GDB's using alloca for buffers and the
1028 knowledge (folklore?) that some hosts don't cope very well with
1029 large alloca calls.) */
1030#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1031
1032/* The minimum remote packet size for memory transfers. Ensures we
1033 can write at least one byte. */
1034#define MIN_MEMORY_PACKET_SIZE 20
1035
1036/* Compute the current size of a read/write packet. Since this makes
1037 use of ``actual_register_packet_size'' the computation is dynamic. */
1038
1039static long
1040get_memory_packet_size (struct memory_packet_config *config)
1041{
1042 struct remote_state *rs = get_remote_state ();
1043 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1044
1045 long what_they_get;
1046 if (config->fixed_p)
1047 {
1048 if (config->size <= 0)
1049 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1050 else
1051 what_they_get = config->size;
1052 }
1053 else
1054 {
1055 what_they_get = get_remote_packet_size ();
1056 /* Limit the packet to the size specified by the user. */
1057 if (config->size > 0
1058 && what_they_get > config->size)
1059 what_they_get = config->size;
1060
1061 /* Limit it to the size of the targets ``g'' response unless we have
1062 permission from the stub to use a larger packet size. */
1063 if (rs->explicit_packet_size == 0
1064 && rsa->actual_register_packet_size > 0
1065 && what_they_get > rsa->actual_register_packet_size)
1066 what_they_get = rsa->actual_register_packet_size;
1067 }
1068 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1069 what_they_get = MIN_MEMORY_PACKET_SIZE;
1070
1071 /* Make sure there is room in the global buffer for this packet
1072 (including its trailing NUL byte). */
1073 if (rs->buf_size < what_they_get + 1)
1074 {
1075 rs->buf_size = 2 * what_they_get;
1076 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1077 }
1078
1079 return what_they_get;
1080}
1081
1082/* Update the size of a read/write packet. If they user wants
1083 something really big then do a sanity check. */
1084
1085static void
1086set_memory_packet_size (const char *args, struct memory_packet_config *config)
1087{
1088 int fixed_p = config->fixed_p;
1089 long size = config->size;
1090
1091 if (args == NULL)
1092 error (_("Argument required (integer, `fixed' or `limited')."));
1093 else if (strcmp (args, "hard") == 0
1094 || strcmp (args, "fixed") == 0)
1095 fixed_p = 1;
1096 else if (strcmp (args, "soft") == 0
1097 || strcmp (args, "limit") == 0)
1098 fixed_p = 0;
1099 else
1100 {
1101 char *end;
1102
1103 size = strtoul (args, &end, 0);
1104 if (args == end)
1105 error (_("Invalid %s (bad syntax)."), config->name);
1106
1107 /* Instead of explicitly capping the size of a packet to or
1108 disallowing it, the user is allowed to set the size to
1109 something arbitrarily large. */
1110 }
1111
1112 /* So that the query shows the correct value. */
1113 if (size <= 0)
1114 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1115
1116 /* Extra checks? */
1117 if (fixed_p && !config->fixed_p)
1118 {
1119 if (! query (_("The target may not be able to correctly handle a %s\n"
1120 "of %ld bytes. Change the packet size? "),
1121 config->name, size))
1122 error (_("Packet size not changed."));
1123 }
1124 /* Update the config. */
1125 config->fixed_p = fixed_p;
1126 config->size = size;
1127}
1128
1129static void
1130show_memory_packet_size (struct memory_packet_config *config)
1131{
1132 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1133 if (config->fixed_p)
1134 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1135 get_memory_packet_size (config));
1136 else
1137 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1138 get_memory_packet_size (config));
1139}
1140
1141static struct memory_packet_config memory_write_packet_config =
1142{
1143 "memory-write-packet-size",
1144};
1145
1146static void
1147set_memory_write_packet_size (const char *args, int from_tty)
1148{
1149 set_memory_packet_size (args, &memory_write_packet_config);
1150}
1151
1152static void
1153show_memory_write_packet_size (const char *args, int from_tty)
1154{
1155 show_memory_packet_size (&memory_write_packet_config);
1156}
1157
1158static long
1159get_memory_write_packet_size (void)
1160{
1161 return get_memory_packet_size (&memory_write_packet_config);
1162}
1163
1164static struct memory_packet_config memory_read_packet_config =
1165{
1166 "memory-read-packet-size",
1167};
1168
1169static void
1170set_memory_read_packet_size (const char *args, int from_tty)
1171{
1172 set_memory_packet_size (args, &memory_read_packet_config);
1173}
1174
1175static void
1176show_memory_read_packet_size (const char *args, int from_tty)
1177{
1178 show_memory_packet_size (&memory_read_packet_config);
1179}
1180
1181static long
1182get_memory_read_packet_size (void)
1183{
1184 long size = get_memory_packet_size (&memory_read_packet_config);
1185
1186 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1187 extra buffer size argument before the memory read size can be
1188 increased beyond this. */
1189 if (size > get_remote_packet_size ())
1190 size = get_remote_packet_size ();
1191 return size;
1192}
1193
1194\f
1195/* Generic configuration support for packets the stub optionally
1196 supports. Allows the user to specify the use of the packet as well
1197 as allowing GDB to auto-detect support in the remote stub. */
1198
1199enum packet_support
1200 {
1201 PACKET_SUPPORT_UNKNOWN = 0,
1202 PACKET_ENABLE,
1203 PACKET_DISABLE
1204 };
1205
1206struct packet_config
1207 {
1208 const char *name;
1209 const char *title;
1210
1211 /* If auto, GDB auto-detects support for this packet or feature,
1212 either through qSupported, or by trying the packet and looking
1213 at the response. If true, GDB assumes the target supports this
1214 packet. If false, the packet is disabled. Configs that don't
1215 have an associated command always have this set to auto. */
1216 enum auto_boolean detect;
1217
1218 /* Does the target support this packet? */
1219 enum packet_support support;
1220 };
1221
1222/* Analyze a packet's return value and update the packet config
1223 accordingly. */
1224
1225enum packet_result
1226{
1227 PACKET_ERROR,
1228 PACKET_OK,
1229 PACKET_UNKNOWN
1230};
1231
1232static enum packet_support packet_config_support (struct packet_config *config);
1233static enum packet_support packet_support (int packet);
1234
1235static void
1236show_packet_config_cmd (struct packet_config *config)
1237{
1238 const char *support = "internal-error";
1239
1240 switch (packet_config_support (config))
1241 {
1242 case PACKET_ENABLE:
1243 support = "enabled";
1244 break;
1245 case PACKET_DISABLE:
1246 support = "disabled";
1247 break;
1248 case PACKET_SUPPORT_UNKNOWN:
1249 support = "unknown";
1250 break;
1251 }
1252 switch (config->detect)
1253 {
1254 case AUTO_BOOLEAN_AUTO:
1255 printf_filtered (_("Support for the `%s' packet "
1256 "is auto-detected, currently %s.\n"),
1257 config->name, support);
1258 break;
1259 case AUTO_BOOLEAN_TRUE:
1260 case AUTO_BOOLEAN_FALSE:
1261 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1262 config->name, support);
1263 break;
1264 }
1265}
1266
1267static void
1268add_packet_config_cmd (struct packet_config *config, const char *name,
1269 const char *title, int legacy)
1270{
1271 char *set_doc;
1272 char *show_doc;
1273 char *cmd_name;
1274
1275 config->name = name;
1276 config->title = title;
1277 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1278 name, title);
1279 show_doc = xstrprintf ("Show current use of remote "
1280 "protocol `%s' (%s) packet",
1281 name, title);
1282 /* set/show TITLE-packet {auto,on,off} */
1283 cmd_name = xstrprintf ("%s-packet", title);
1284 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1285 &config->detect, set_doc,
1286 show_doc, NULL, /* help_doc */
1287 NULL,
1288 show_remote_protocol_packet_cmd,
1289 &remote_set_cmdlist, &remote_show_cmdlist);
1290 /* The command code copies the documentation strings. */
1291 xfree (set_doc);
1292 xfree (show_doc);
1293 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1294 if (legacy)
1295 {
1296 char *legacy_name;
1297
1298 legacy_name = xstrprintf ("%s-packet", name);
1299 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1300 &remote_set_cmdlist);
1301 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1302 &remote_show_cmdlist);
1303 }
1304}
1305
1306static enum packet_result
1307packet_check_result (const char *buf)
1308{
1309 if (buf[0] != '\0')
1310 {
1311 /* The stub recognized the packet request. Check that the
1312 operation succeeded. */
1313 if (buf[0] == 'E'
1314 && isxdigit (buf[1]) && isxdigit (buf[2])
1315 && buf[3] == '\0')
1316 /* "Enn" - definitly an error. */
1317 return PACKET_ERROR;
1318
1319 /* Always treat "E." as an error. This will be used for
1320 more verbose error messages, such as E.memtypes. */
1321 if (buf[0] == 'E' && buf[1] == '.')
1322 return PACKET_ERROR;
1323
1324 /* The packet may or may not be OK. Just assume it is. */
1325 return PACKET_OK;
1326 }
1327 else
1328 /* The stub does not support the packet. */
1329 return PACKET_UNKNOWN;
1330}
1331
1332static enum packet_result
1333packet_ok (const char *buf, struct packet_config *config)
1334{
1335 enum packet_result result;
1336
1337 if (config->detect != AUTO_BOOLEAN_TRUE
1338 && config->support == PACKET_DISABLE)
1339 internal_error (__FILE__, __LINE__,
1340 _("packet_ok: attempt to use a disabled packet"));
1341
1342 result = packet_check_result (buf);
1343 switch (result)
1344 {
1345 case PACKET_OK:
1346 case PACKET_ERROR:
1347 /* The stub recognized the packet request. */
1348 if (config->support == PACKET_SUPPORT_UNKNOWN)
1349 {
1350 if (remote_debug)
1351 fprintf_unfiltered (gdb_stdlog,
1352 "Packet %s (%s) is supported\n",
1353 config->name, config->title);
1354 config->support = PACKET_ENABLE;
1355 }
1356 break;
1357 case PACKET_UNKNOWN:
1358 /* The stub does not support the packet. */
1359 if (config->detect == AUTO_BOOLEAN_AUTO
1360 && config->support == PACKET_ENABLE)
1361 {
1362 /* If the stub previously indicated that the packet was
1363 supported then there is a protocol error. */
1364 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1365 config->name, config->title);
1366 }
1367 else if (config->detect == AUTO_BOOLEAN_TRUE)
1368 {
1369 /* The user set it wrong. */
1370 error (_("Enabled packet %s (%s) not recognized by stub"),
1371 config->name, config->title);
1372 }
1373
1374 if (remote_debug)
1375 fprintf_unfiltered (gdb_stdlog,
1376 "Packet %s (%s) is NOT supported\n",
1377 config->name, config->title);
1378 config->support = PACKET_DISABLE;
1379 break;
1380 }
1381
1382 return result;
1383}
1384
1385enum {
1386 PACKET_vCont = 0,
1387 PACKET_X,
1388 PACKET_qSymbol,
1389 PACKET_P,
1390 PACKET_p,
1391 PACKET_Z0,
1392 PACKET_Z1,
1393 PACKET_Z2,
1394 PACKET_Z3,
1395 PACKET_Z4,
1396 PACKET_vFile_setfs,
1397 PACKET_vFile_open,
1398 PACKET_vFile_pread,
1399 PACKET_vFile_pwrite,
1400 PACKET_vFile_close,
1401 PACKET_vFile_unlink,
1402 PACKET_vFile_readlink,
1403 PACKET_vFile_fstat,
1404 PACKET_qXfer_auxv,
1405 PACKET_qXfer_features,
1406 PACKET_qXfer_exec_file,
1407 PACKET_qXfer_libraries,
1408 PACKET_qXfer_libraries_svr4,
1409 PACKET_qXfer_memory_map,
1410 PACKET_qXfer_spu_read,
1411 PACKET_qXfer_spu_write,
1412 PACKET_qXfer_osdata,
1413 PACKET_qXfer_threads,
1414 PACKET_qXfer_statictrace_read,
1415 PACKET_qXfer_traceframe_info,
1416 PACKET_qXfer_uib,
1417 PACKET_qGetTIBAddr,
1418 PACKET_qGetTLSAddr,
1419 PACKET_qSupported,
1420 PACKET_qTStatus,
1421 PACKET_QPassSignals,
1422 PACKET_QCatchSyscalls,
1423 PACKET_QProgramSignals,
1424 PACKET_QSetWorkingDir,
1425 PACKET_QStartupWithShell,
1426 PACKET_QEnvironmentHexEncoded,
1427 PACKET_QEnvironmentReset,
1428 PACKET_QEnvironmentUnset,
1429 PACKET_qCRC,
1430 PACKET_qSearch_memory,
1431 PACKET_vAttach,
1432 PACKET_vRun,
1433 PACKET_QStartNoAckMode,
1434 PACKET_vKill,
1435 PACKET_qXfer_siginfo_read,
1436 PACKET_qXfer_siginfo_write,
1437 PACKET_qAttached,
1438
1439 /* Support for conditional tracepoints. */
1440 PACKET_ConditionalTracepoints,
1441
1442 /* Support for target-side breakpoint conditions. */
1443 PACKET_ConditionalBreakpoints,
1444
1445 /* Support for target-side breakpoint commands. */
1446 PACKET_BreakpointCommands,
1447
1448 /* Support for fast tracepoints. */
1449 PACKET_FastTracepoints,
1450
1451 /* Support for static tracepoints. */
1452 PACKET_StaticTracepoints,
1453
1454 /* Support for installing tracepoints while a trace experiment is
1455 running. */
1456 PACKET_InstallInTrace,
1457
1458 PACKET_bc,
1459 PACKET_bs,
1460 PACKET_TracepointSource,
1461 PACKET_QAllow,
1462 PACKET_qXfer_fdpic,
1463 PACKET_QDisableRandomization,
1464 PACKET_QAgent,
1465 PACKET_QTBuffer_size,
1466 PACKET_Qbtrace_off,
1467 PACKET_Qbtrace_bts,
1468 PACKET_Qbtrace_pt,
1469 PACKET_qXfer_btrace,
1470
1471 /* Support for the QNonStop packet. */
1472 PACKET_QNonStop,
1473
1474 /* Support for the QThreadEvents packet. */
1475 PACKET_QThreadEvents,
1476
1477 /* Support for multi-process extensions. */
1478 PACKET_multiprocess_feature,
1479
1480 /* Support for enabling and disabling tracepoints while a trace
1481 experiment is running. */
1482 PACKET_EnableDisableTracepoints_feature,
1483
1484 /* Support for collecting strings using the tracenz bytecode. */
1485 PACKET_tracenz_feature,
1486
1487 /* Support for continuing to run a trace experiment while GDB is
1488 disconnected. */
1489 PACKET_DisconnectedTracing_feature,
1490
1491 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1492 PACKET_augmented_libraries_svr4_read_feature,
1493
1494 /* Support for the qXfer:btrace-conf:read packet. */
1495 PACKET_qXfer_btrace_conf,
1496
1497 /* Support for the Qbtrace-conf:bts:size packet. */
1498 PACKET_Qbtrace_conf_bts_size,
1499
1500 /* Support for swbreak+ feature. */
1501 PACKET_swbreak_feature,
1502
1503 /* Support for hwbreak+ feature. */
1504 PACKET_hwbreak_feature,
1505
1506 /* Support for fork events. */
1507 PACKET_fork_event_feature,
1508
1509 /* Support for vfork events. */
1510 PACKET_vfork_event_feature,
1511
1512 /* Support for the Qbtrace-conf:pt:size packet. */
1513 PACKET_Qbtrace_conf_pt_size,
1514
1515 /* Support for exec events. */
1516 PACKET_exec_event_feature,
1517
1518 /* Support for query supported vCont actions. */
1519 PACKET_vContSupported,
1520
1521 /* Support remote CTRL-C. */
1522 PACKET_vCtrlC,
1523
1524 /* Support TARGET_WAITKIND_NO_RESUMED. */
1525 PACKET_no_resumed,
1526
1527 PACKET_MAX
1528};
1529
1530static struct packet_config remote_protocol_packets[PACKET_MAX];
1531
1532/* Returns the packet's corresponding "set remote foo-packet" command
1533 state. See struct packet_config for more details. */
1534
1535static enum auto_boolean
1536packet_set_cmd_state (int packet)
1537{
1538 return remote_protocol_packets[packet].detect;
1539}
1540
1541/* Returns whether a given packet or feature is supported. This takes
1542 into account the state of the corresponding "set remote foo-packet"
1543 command, which may be used to bypass auto-detection. */
1544
1545static enum packet_support
1546packet_config_support (struct packet_config *config)
1547{
1548 switch (config->detect)
1549 {
1550 case AUTO_BOOLEAN_TRUE:
1551 return PACKET_ENABLE;
1552 case AUTO_BOOLEAN_FALSE:
1553 return PACKET_DISABLE;
1554 case AUTO_BOOLEAN_AUTO:
1555 return config->support;
1556 default:
1557 gdb_assert_not_reached (_("bad switch"));
1558 }
1559}
1560
1561/* Same as packet_config_support, but takes the packet's enum value as
1562 argument. */
1563
1564static enum packet_support
1565packet_support (int packet)
1566{
1567 struct packet_config *config = &remote_protocol_packets[packet];
1568
1569 return packet_config_support (config);
1570}
1571
1572static void
1573show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1574 struct cmd_list_element *c,
1575 const char *value)
1576{
1577 struct packet_config *packet;
1578
1579 for (packet = remote_protocol_packets;
1580 packet < &remote_protocol_packets[PACKET_MAX];
1581 packet++)
1582 {
1583 if (&packet->detect == c->var)
1584 {
1585 show_packet_config_cmd (packet);
1586 return;
1587 }
1588 }
1589 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1590 c->name);
1591}
1592
1593/* Should we try one of the 'Z' requests? */
1594
1595enum Z_packet_type
1596{
1597 Z_PACKET_SOFTWARE_BP,
1598 Z_PACKET_HARDWARE_BP,
1599 Z_PACKET_WRITE_WP,
1600 Z_PACKET_READ_WP,
1601 Z_PACKET_ACCESS_WP,
1602 NR_Z_PACKET_TYPES
1603};
1604
1605/* For compatibility with older distributions. Provide a ``set remote
1606 Z-packet ...'' command that updates all the Z packet types. */
1607
1608static enum auto_boolean remote_Z_packet_detect;
1609
1610static void
1611set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1612 struct cmd_list_element *c)
1613{
1614 int i;
1615
1616 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1617 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1618}
1619
1620static void
1621show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1622 struct cmd_list_element *c,
1623 const char *value)
1624{
1625 int i;
1626
1627 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1628 {
1629 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1630 }
1631}
1632
1633/* Returns true if the multi-process extensions are in effect. */
1634
1635static int
1636remote_multi_process_p (struct remote_state *rs)
1637{
1638 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1639}
1640
1641/* Returns true if fork events are supported. */
1642
1643static int
1644remote_fork_event_p (struct remote_state *rs)
1645{
1646 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1647}
1648
1649/* Returns true if vfork events are supported. */
1650
1651static int
1652remote_vfork_event_p (struct remote_state *rs)
1653{
1654 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1655}
1656
1657/* Returns true if exec events are supported. */
1658
1659static int
1660remote_exec_event_p (struct remote_state *rs)
1661{
1662 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1663}
1664
1665/* Insert fork catchpoint target routine. If fork events are enabled
1666 then return success, nothing more to do. */
1667
1668static int
1669remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1670{
1671 struct remote_state *rs = get_remote_state ();
1672
1673 return !remote_fork_event_p (rs);
1674}
1675
1676/* Remove fork catchpoint target routine. Nothing to do, just
1677 return success. */
1678
1679static int
1680remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1681{
1682 return 0;
1683}
1684
1685/* Insert vfork catchpoint target routine. If vfork events are enabled
1686 then return success, nothing more to do. */
1687
1688static int
1689remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1690{
1691 struct remote_state *rs = get_remote_state ();
1692
1693 return !remote_vfork_event_p (rs);
1694}
1695
1696/* Remove vfork catchpoint target routine. Nothing to do, just
1697 return success. */
1698
1699static int
1700remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1701{
1702 return 0;
1703}
1704
1705/* Insert exec catchpoint target routine. If exec events are
1706 enabled, just return success. */
1707
1708static int
1709remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1710{
1711 struct remote_state *rs = get_remote_state ();
1712
1713 return !remote_exec_event_p (rs);
1714}
1715
1716/* Remove exec catchpoint target routine. Nothing to do, just
1717 return success. */
1718
1719static int
1720remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1721{
1722 return 0;
1723}
1724
1725\f
1726/* Asynchronous signal handle registered as event loop source for
1727 when we have pending events ready to be passed to the core. */
1728
1729static struct async_event_handler *remote_async_inferior_event_token;
1730
1731\f
1732
1733static ptid_t magic_null_ptid;
1734static ptid_t not_sent_ptid;
1735static ptid_t any_thread_ptid;
1736
1737/* Find out if the stub attached to PID (and hence GDB should offer to
1738 detach instead of killing it when bailing out). */
1739
1740static int
1741remote_query_attached (int pid)
1742{
1743 struct remote_state *rs = get_remote_state ();
1744 size_t size = get_remote_packet_size ();
1745
1746 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1747 return 0;
1748
1749 if (remote_multi_process_p (rs))
1750 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1751 else
1752 xsnprintf (rs->buf, size, "qAttached");
1753
1754 putpkt (rs->buf);
1755 getpkt (&rs->buf, &rs->buf_size, 0);
1756
1757 switch (packet_ok (rs->buf,
1758 &remote_protocol_packets[PACKET_qAttached]))
1759 {
1760 case PACKET_OK:
1761 if (strcmp (rs->buf, "1") == 0)
1762 return 1;
1763 break;
1764 case PACKET_ERROR:
1765 warning (_("Remote failure reply: %s"), rs->buf);
1766 break;
1767 case PACKET_UNKNOWN:
1768 break;
1769 }
1770
1771 return 0;
1772}
1773
1774/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1775 has been invented by GDB, instead of reported by the target. Since
1776 we can be connected to a remote system before before knowing about
1777 any inferior, mark the target with execution when we find the first
1778 inferior. If ATTACHED is 1, then we had just attached to this
1779 inferior. If it is 0, then we just created this inferior. If it
1780 is -1, then try querying the remote stub to find out if it had
1781 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1782 attempt to open this inferior's executable as the main executable
1783 if no main executable is open already. */
1784
1785static struct inferior *
1786remote_add_inferior (int fake_pid_p, int pid, int attached,
1787 int try_open_exec)
1788{
1789 struct inferior *inf;
1790
1791 /* Check whether this process we're learning about is to be
1792 considered attached, or if is to be considered to have been
1793 spawned by the stub. */
1794 if (attached == -1)
1795 attached = remote_query_attached (pid);
1796
1797 if (gdbarch_has_global_solist (target_gdbarch ()))
1798 {
1799 /* If the target shares code across all inferiors, then every
1800 attach adds a new inferior. */
1801 inf = add_inferior (pid);
1802
1803 /* ... and every inferior is bound to the same program space.
1804 However, each inferior may still have its own address
1805 space. */
1806 inf->aspace = maybe_new_address_space ();
1807 inf->pspace = current_program_space;
1808 }
1809 else
1810 {
1811 /* In the traditional debugging scenario, there's a 1-1 match
1812 between program/address spaces. We simply bind the inferior
1813 to the program space's address space. */
1814 inf = current_inferior ();
1815 inferior_appeared (inf, pid);
1816 }
1817
1818 inf->attach_flag = attached;
1819 inf->fake_pid_p = fake_pid_p;
1820
1821 /* If no main executable is currently open then attempt to
1822 open the file that was executed to create this inferior. */
1823 if (try_open_exec && get_exec_file (0) == NULL)
1824 exec_file_locate_attach (pid, 0, 1);
1825
1826 return inf;
1827}
1828
1829static struct private_thread_info *
1830 get_private_info_thread (struct thread_info *info);
1831
1832/* Add thread PTID to GDB's thread list. Tag it as executing/running
1833 according to RUNNING. */
1834
1835static void
1836remote_add_thread (ptid_t ptid, int running, int executing)
1837{
1838 struct remote_state *rs = get_remote_state ();
1839 struct thread_info *thread;
1840
1841 /* GDB historically didn't pull threads in the initial connection
1842 setup. If the remote target doesn't even have a concept of
1843 threads (e.g., a bare-metal target), even if internally we
1844 consider that a single-threaded target, mentioning a new thread
1845 might be confusing to the user. Be silent then, preserving the
1846 age old behavior. */
1847 if (rs->starting_up)
1848 thread = add_thread_silent (ptid);
1849 else
1850 thread = add_thread (ptid);
1851
1852 get_private_info_thread (thread)->vcont_resumed = executing;
1853 set_executing (ptid, executing);
1854 set_running (ptid, running);
1855}
1856
1857/* Come here when we learn about a thread id from the remote target.
1858 It may be the first time we hear about such thread, so take the
1859 opportunity to add it to GDB's thread list. In case this is the
1860 first time we're noticing its corresponding inferior, add it to
1861 GDB's inferior list as well. EXECUTING indicates whether the
1862 thread is (internally) executing or stopped. */
1863
1864static void
1865remote_notice_new_inferior (ptid_t currthread, int executing)
1866{
1867 /* In non-stop mode, we assume new found threads are (externally)
1868 running until proven otherwise with a stop reply. In all-stop,
1869 we can only get here if all threads are stopped. */
1870 int running = target_is_non_stop_p () ? 1 : 0;
1871
1872 /* If this is a new thread, add it to GDB's thread list.
1873 If we leave it up to WFI to do this, bad things will happen. */
1874
1875 if (in_thread_list (currthread) && is_exited (currthread))
1876 {
1877 /* We're seeing an event on a thread id we knew had exited.
1878 This has to be a new thread reusing the old id. Add it. */
1879 remote_add_thread (currthread, running, executing);
1880 return;
1881 }
1882
1883 if (!in_thread_list (currthread))
1884 {
1885 struct inferior *inf = NULL;
1886 int pid = ptid_get_pid (currthread);
1887
1888 if (ptid_is_pid (inferior_ptid)
1889 && pid == ptid_get_pid (inferior_ptid))
1890 {
1891 /* inferior_ptid has no thread member yet. This can happen
1892 with the vAttach -> remote_wait,"TAAthread:" path if the
1893 stub doesn't support qC. This is the first stop reported
1894 after an attach, so this is the main thread. Update the
1895 ptid in the thread list. */
1896 if (in_thread_list (pid_to_ptid (pid)))
1897 thread_change_ptid (inferior_ptid, currthread);
1898 else
1899 {
1900 remote_add_thread (currthread, running, executing);
1901 inferior_ptid = currthread;
1902 }
1903 return;
1904 }
1905
1906 if (ptid_equal (magic_null_ptid, inferior_ptid))
1907 {
1908 /* inferior_ptid is not set yet. This can happen with the
1909 vRun -> remote_wait,"TAAthread:" path if the stub
1910 doesn't support qC. This is the first stop reported
1911 after an attach, so this is the main thread. Update the
1912 ptid in the thread list. */
1913 thread_change_ptid (inferior_ptid, currthread);
1914 return;
1915 }
1916
1917 /* When connecting to a target remote, or to a target
1918 extended-remote which already was debugging an inferior, we
1919 may not know about it yet. Add it before adding its child
1920 thread, so notifications are emitted in a sensible order. */
1921 if (!in_inferior_list (ptid_get_pid (currthread)))
1922 {
1923 struct remote_state *rs = get_remote_state ();
1924 int fake_pid_p = !remote_multi_process_p (rs);
1925
1926 inf = remote_add_inferior (fake_pid_p,
1927 ptid_get_pid (currthread), -1, 1);
1928 }
1929
1930 /* This is really a new thread. Add it. */
1931 remote_add_thread (currthread, running, executing);
1932
1933 /* If we found a new inferior, let the common code do whatever
1934 it needs to with it (e.g., read shared libraries, insert
1935 breakpoints), unless we're just setting up an all-stop
1936 connection. */
1937 if (inf != NULL)
1938 {
1939 struct remote_state *rs = get_remote_state ();
1940
1941 if (!rs->starting_up)
1942 notice_new_inferior (currthread, executing, 0);
1943 }
1944 }
1945}
1946
1947/* Return THREAD's private thread data, creating it if necessary. */
1948
1949static struct private_thread_info *
1950get_private_info_thread (struct thread_info *thread)
1951{
1952 gdb_assert (thread != NULL);
1953
1954 if (thread->priv == NULL)
1955 {
1956 struct private_thread_info *priv = XNEW (struct private_thread_info);
1957
1958 thread->private_dtor = free_private_thread_info;
1959 thread->priv = priv;
1960
1961 priv->core = -1;
1962 priv->extra = NULL;
1963 priv->name = NULL;
1964 priv->name = NULL;
1965 priv->last_resume_step = 0;
1966 priv->last_resume_sig = GDB_SIGNAL_0;
1967 priv->vcont_resumed = 0;
1968 priv->thread_handle = nullptr;
1969 }
1970
1971 return thread->priv;
1972}
1973
1974/* Return PTID's private thread data, creating it if necessary. */
1975
1976static struct private_thread_info *
1977get_private_info_ptid (ptid_t ptid)
1978{
1979 struct thread_info *info = find_thread_ptid (ptid);
1980
1981 return get_private_info_thread (info);
1982}
1983
1984/* Call this function as a result of
1985 1) A halt indication (T packet) containing a thread id
1986 2) A direct query of currthread
1987 3) Successful execution of set thread */
1988
1989static void
1990record_currthread (struct remote_state *rs, ptid_t currthread)
1991{
1992 rs->general_thread = currthread;
1993}
1994
1995/* If 'QPassSignals' is supported, tell the remote stub what signals
1996 it can simply pass through to the inferior without reporting. */
1997
1998static void
1999remote_pass_signals (struct target_ops *self,
2000 int numsigs, unsigned char *pass_signals)
2001{
2002 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2003 {
2004 char *pass_packet, *p;
2005 int count = 0, i;
2006 struct remote_state *rs = get_remote_state ();
2007
2008 gdb_assert (numsigs < 256);
2009 for (i = 0; i < numsigs; i++)
2010 {
2011 if (pass_signals[i])
2012 count++;
2013 }
2014 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2015 strcpy (pass_packet, "QPassSignals:");
2016 p = pass_packet + strlen (pass_packet);
2017 for (i = 0; i < numsigs; i++)
2018 {
2019 if (pass_signals[i])
2020 {
2021 if (i >= 16)
2022 *p++ = tohex (i >> 4);
2023 *p++ = tohex (i & 15);
2024 if (count)
2025 *p++ = ';';
2026 else
2027 break;
2028 count--;
2029 }
2030 }
2031 *p = 0;
2032 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2033 {
2034 putpkt (pass_packet);
2035 getpkt (&rs->buf, &rs->buf_size, 0);
2036 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2037 if (rs->last_pass_packet)
2038 xfree (rs->last_pass_packet);
2039 rs->last_pass_packet = pass_packet;
2040 }
2041 else
2042 xfree (pass_packet);
2043 }
2044}
2045
2046/* If 'QCatchSyscalls' is supported, tell the remote stub
2047 to report syscalls to GDB. */
2048
2049static int
2050remote_set_syscall_catchpoint (struct target_ops *self,
2051 int pid, int needed, int any_count,
2052 int table_size, int *table)
2053{
2054 const char *catch_packet;
2055 enum packet_result result;
2056 int n_sysno = 0;
2057
2058 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2059 {
2060 /* Not supported. */
2061 return 1;
2062 }
2063
2064 if (needed && !any_count)
2065 {
2066 int i;
2067
2068 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2069 for (i = 0; i < table_size; i++)
2070 {
2071 if (table[i] != 0)
2072 n_sysno++;
2073 }
2074 }
2075
2076 if (remote_debug)
2077 {
2078 fprintf_unfiltered (gdb_stdlog,
2079 "remote_set_syscall_catchpoint "
2080 "pid %d needed %d any_count %d n_sysno %d\n",
2081 pid, needed, any_count, n_sysno);
2082 }
2083
2084 gdb::unique_xmalloc_ptr<char> built_packet;
2085 if (needed)
2086 {
2087 /* Prepare a packet with the sysno list, assuming max 8+1
2088 characters for a sysno. If the resulting packet size is too
2089 big, fallback on the non-selective packet. */
2090 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2091
2092 built_packet.reset ((char *) xmalloc (maxpktsz));
2093 strcpy (built_packet.get (), "QCatchSyscalls:1");
2094 if (!any_count)
2095 {
2096 int i;
2097 char *p;
2098
2099 p = built_packet.get ();
2100 p += strlen (p);
2101
2102 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2103 for (i = 0; i < table_size; i++)
2104 {
2105 if (table[i] != 0)
2106 p += xsnprintf (p, built_packet.get () + maxpktsz - p,
2107 ";%x", i);
2108 }
2109 }
2110 if (strlen (built_packet.get ()) > get_remote_packet_size ())
2111 {
2112 /* catch_packet too big. Fallback to less efficient
2113 non selective mode, with GDB doing the filtering. */
2114 catch_packet = "QCatchSyscalls:1";
2115 }
2116 else
2117 catch_packet = built_packet.get ();
2118 }
2119 else
2120 catch_packet = "QCatchSyscalls:0";
2121
2122 struct remote_state *rs = get_remote_state ();
2123
2124 putpkt (catch_packet);
2125 getpkt (&rs->buf, &rs->buf_size, 0);
2126 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2127 if (result == PACKET_OK)
2128 return 0;
2129 else
2130 return -1;
2131}
2132
2133/* If 'QProgramSignals' is supported, tell the remote stub what
2134 signals it should pass through to the inferior when detaching. */
2135
2136static void
2137remote_program_signals (struct target_ops *self,
2138 int numsigs, unsigned char *signals)
2139{
2140 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2141 {
2142 char *packet, *p;
2143 int count = 0, i;
2144 struct remote_state *rs = get_remote_state ();
2145
2146 gdb_assert (numsigs < 256);
2147 for (i = 0; i < numsigs; i++)
2148 {
2149 if (signals[i])
2150 count++;
2151 }
2152 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2153 strcpy (packet, "QProgramSignals:");
2154 p = packet + strlen (packet);
2155 for (i = 0; i < numsigs; i++)
2156 {
2157 if (signal_pass_state (i))
2158 {
2159 if (i >= 16)
2160 *p++ = tohex (i >> 4);
2161 *p++ = tohex (i & 15);
2162 if (count)
2163 *p++ = ';';
2164 else
2165 break;
2166 count--;
2167 }
2168 }
2169 *p = 0;
2170 if (!rs->last_program_signals_packet
2171 || strcmp (rs->last_program_signals_packet, packet) != 0)
2172 {
2173 putpkt (packet);
2174 getpkt (&rs->buf, &rs->buf_size, 0);
2175 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2176 xfree (rs->last_program_signals_packet);
2177 rs->last_program_signals_packet = packet;
2178 }
2179 else
2180 xfree (packet);
2181 }
2182}
2183
2184/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2185 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2186 thread. If GEN is set, set the general thread, if not, then set
2187 the step/continue thread. */
2188static void
2189set_thread (ptid_t ptid, int gen)
2190{
2191 struct remote_state *rs = get_remote_state ();
2192 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2193 char *buf = rs->buf;
2194 char *endbuf = rs->buf + get_remote_packet_size ();
2195
2196 if (ptid_equal (state, ptid))
2197 return;
2198
2199 *buf++ = 'H';
2200 *buf++ = gen ? 'g' : 'c';
2201 if (ptid_equal (ptid, magic_null_ptid))
2202 xsnprintf (buf, endbuf - buf, "0");
2203 else if (ptid_equal (ptid, any_thread_ptid))
2204 xsnprintf (buf, endbuf - buf, "0");
2205 else if (ptid_equal (ptid, minus_one_ptid))
2206 xsnprintf (buf, endbuf - buf, "-1");
2207 else
2208 write_ptid (buf, endbuf, ptid);
2209 putpkt (rs->buf);
2210 getpkt (&rs->buf, &rs->buf_size, 0);
2211 if (gen)
2212 rs->general_thread = ptid;
2213 else
2214 rs->continue_thread = ptid;
2215}
2216
2217static void
2218set_general_thread (ptid_t ptid)
2219{
2220 set_thread (ptid, 1);
2221}
2222
2223static void
2224set_continue_thread (ptid_t ptid)
2225{
2226 set_thread (ptid, 0);
2227}
2228
2229/* Change the remote current process. Which thread within the process
2230 ends up selected isn't important, as long as it is the same process
2231 as what INFERIOR_PTID points to.
2232
2233 This comes from that fact that there is no explicit notion of
2234 "selected process" in the protocol. The selected process for
2235 general operations is the process the selected general thread
2236 belongs to. */
2237
2238static void
2239set_general_process (void)
2240{
2241 struct remote_state *rs = get_remote_state ();
2242
2243 /* If the remote can't handle multiple processes, don't bother. */
2244 if (!remote_multi_process_p (rs))
2245 return;
2246
2247 /* We only need to change the remote current thread if it's pointing
2248 at some other process. */
2249 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2250 set_general_thread (inferior_ptid);
2251}
2252
2253\f
2254/* Return nonzero if this is the main thread that we made up ourselves
2255 to model non-threaded targets as single-threaded. */
2256
2257static int
2258remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2259{
2260 if (ptid_equal (ptid, magic_null_ptid))
2261 /* The main thread is always alive. */
2262 return 1;
2263
2264 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2265 /* The main thread is always alive. This can happen after a
2266 vAttach, if the remote side doesn't support
2267 multi-threading. */
2268 return 1;
2269
2270 return 0;
2271}
2272
2273/* Return nonzero if the thread PTID is still alive on the remote
2274 system. */
2275
2276static int
2277remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2278{
2279 struct remote_state *rs = get_remote_state ();
2280 char *p, *endp;
2281
2282 /* Check if this is a thread that we made up ourselves to model
2283 non-threaded targets as single-threaded. */
2284 if (remote_thread_always_alive (ops, ptid))
2285 return 1;
2286
2287 p = rs->buf;
2288 endp = rs->buf + get_remote_packet_size ();
2289
2290 *p++ = 'T';
2291 write_ptid (p, endp, ptid);
2292
2293 putpkt (rs->buf);
2294 getpkt (&rs->buf, &rs->buf_size, 0);
2295 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2296}
2297
2298/* Return a pointer to a thread name if we know it and NULL otherwise.
2299 The thread_info object owns the memory for the name. */
2300
2301static const char *
2302remote_thread_name (struct target_ops *ops, struct thread_info *info)
2303{
2304 if (info->priv != NULL)
2305 return info->priv->name;
2306
2307 return NULL;
2308}
2309
2310/* About these extended threadlist and threadinfo packets. They are
2311 variable length packets but, the fields within them are often fixed
2312 length. They are redundent enough to send over UDP as is the
2313 remote protocol in general. There is a matching unit test module
2314 in libstub. */
2315
2316/* WARNING: This threadref data structure comes from the remote O.S.,
2317 libstub protocol encoding, and remote.c. It is not particularly
2318 changable. */
2319
2320/* Right now, the internal structure is int. We want it to be bigger.
2321 Plan to fix this. */
2322
2323typedef int gdb_threadref; /* Internal GDB thread reference. */
2324
2325/* gdb_ext_thread_info is an internal GDB data structure which is
2326 equivalent to the reply of the remote threadinfo packet. */
2327
2328struct gdb_ext_thread_info
2329 {
2330 threadref threadid; /* External form of thread reference. */
2331 int active; /* Has state interesting to GDB?
2332 regs, stack. */
2333 char display[256]; /* Brief state display, name,
2334 blocked/suspended. */
2335 char shortname[32]; /* To be used to name threads. */
2336 char more_display[256]; /* Long info, statistics, queue depth,
2337 whatever. */
2338 };
2339
2340/* The volume of remote transfers can be limited by submitting
2341 a mask containing bits specifying the desired information.
2342 Use a union of these values as the 'selection' parameter to
2343 get_thread_info. FIXME: Make these TAG names more thread specific. */
2344
2345#define TAG_THREADID 1
2346#define TAG_EXISTS 2
2347#define TAG_DISPLAY 4
2348#define TAG_THREADNAME 8
2349#define TAG_MOREDISPLAY 16
2350
2351#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2352
2353static char *unpack_nibble (char *buf, int *val);
2354
2355static char *unpack_byte (char *buf, int *value);
2356
2357static char *pack_int (char *buf, int value);
2358
2359static char *unpack_int (char *buf, int *value);
2360
2361static char *unpack_string (char *src, char *dest, int length);
2362
2363static char *pack_threadid (char *pkt, threadref *id);
2364
2365static char *unpack_threadid (char *inbuf, threadref *id);
2366
2367void int_to_threadref (threadref *id, int value);
2368
2369static int threadref_to_int (threadref *ref);
2370
2371static void copy_threadref (threadref *dest, threadref *src);
2372
2373static int threadmatch (threadref *dest, threadref *src);
2374
2375static char *pack_threadinfo_request (char *pkt, int mode,
2376 threadref *id);
2377
2378static int remote_unpack_thread_info_response (char *pkt,
2379 threadref *expectedref,
2380 struct gdb_ext_thread_info
2381 *info);
2382
2383
2384static int remote_get_threadinfo (threadref *threadid,
2385 int fieldset, /*TAG mask */
2386 struct gdb_ext_thread_info *info);
2387
2388static char *pack_threadlist_request (char *pkt, int startflag,
2389 int threadcount,
2390 threadref *nextthread);
2391
2392static int parse_threadlist_response (char *pkt,
2393 int result_limit,
2394 threadref *original_echo,
2395 threadref *resultlist,
2396 int *doneflag);
2397
2398static int remote_get_threadlist (int startflag,
2399 threadref *nextthread,
2400 int result_limit,
2401 int *done,
2402 int *result_count,
2403 threadref *threadlist);
2404
2405typedef int (*rmt_thread_action) (threadref *ref, void *context);
2406
2407static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2408 void *context, int looplimit);
2409
2410static int remote_newthread_step (threadref *ref, void *context);
2411
2412
2413/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2414 buffer we're allowed to write to. Returns
2415 BUF+CHARACTERS_WRITTEN. */
2416
2417static char *
2418write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2419{
2420 int pid, tid;
2421 struct remote_state *rs = get_remote_state ();
2422
2423 if (remote_multi_process_p (rs))
2424 {
2425 pid = ptid_get_pid (ptid);
2426 if (pid < 0)
2427 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2428 else
2429 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2430 }
2431 tid = ptid_get_lwp (ptid);
2432 if (tid < 0)
2433 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2434 else
2435 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2436
2437 return buf;
2438}
2439
2440/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2441 last parsed char. Returns null_ptid if no thread id is found, and
2442 throws an error if the thread id has an invalid format. */
2443
2444static ptid_t
2445read_ptid (const char *buf, const char **obuf)
2446{
2447 const char *p = buf;
2448 const char *pp;
2449 ULONGEST pid = 0, tid = 0;
2450
2451 if (*p == 'p')
2452 {
2453 /* Multi-process ptid. */
2454 pp = unpack_varlen_hex (p + 1, &pid);
2455 if (*pp != '.')
2456 error (_("invalid remote ptid: %s"), p);
2457
2458 p = pp;
2459 pp = unpack_varlen_hex (p + 1, &tid);
2460 if (obuf)
2461 *obuf = pp;
2462 return ptid_build (pid, tid, 0);
2463 }
2464
2465 /* No multi-process. Just a tid. */
2466 pp = unpack_varlen_hex (p, &tid);
2467
2468 /* Return null_ptid when no thread id is found. */
2469 if (p == pp)
2470 {
2471 if (obuf)
2472 *obuf = pp;
2473 return null_ptid;
2474 }
2475
2476 /* Since the stub is not sending a process id, then default to
2477 what's in inferior_ptid, unless it's null at this point. If so,
2478 then since there's no way to know the pid of the reported
2479 threads, use the magic number. */
2480 if (ptid_equal (inferior_ptid, null_ptid))
2481 pid = ptid_get_pid (magic_null_ptid);
2482 else
2483 pid = ptid_get_pid (inferior_ptid);
2484
2485 if (obuf)
2486 *obuf = pp;
2487 return ptid_build (pid, tid, 0);
2488}
2489
2490static int
2491stubhex (int ch)
2492{
2493 if (ch >= 'a' && ch <= 'f')
2494 return ch - 'a' + 10;
2495 if (ch >= '0' && ch <= '9')
2496 return ch - '0';
2497 if (ch >= 'A' && ch <= 'F')
2498 return ch - 'A' + 10;
2499 return -1;
2500}
2501
2502static int
2503stub_unpack_int (char *buff, int fieldlength)
2504{
2505 int nibble;
2506 int retval = 0;
2507
2508 while (fieldlength)
2509 {
2510 nibble = stubhex (*buff++);
2511 retval |= nibble;
2512 fieldlength--;
2513 if (fieldlength)
2514 retval = retval << 4;
2515 }
2516 return retval;
2517}
2518
2519static char *
2520unpack_nibble (char *buf, int *val)
2521{
2522 *val = fromhex (*buf++);
2523 return buf;
2524}
2525
2526static char *
2527unpack_byte (char *buf, int *value)
2528{
2529 *value = stub_unpack_int (buf, 2);
2530 return buf + 2;
2531}
2532
2533static char *
2534pack_int (char *buf, int value)
2535{
2536 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2537 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2538 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2539 buf = pack_hex_byte (buf, (value & 0xff));
2540 return buf;
2541}
2542
2543static char *
2544unpack_int (char *buf, int *value)
2545{
2546 *value = stub_unpack_int (buf, 8);
2547 return buf + 8;
2548}
2549
2550#if 0 /* Currently unused, uncomment when needed. */
2551static char *pack_string (char *pkt, char *string);
2552
2553static char *
2554pack_string (char *pkt, char *string)
2555{
2556 char ch;
2557 int len;
2558
2559 len = strlen (string);
2560 if (len > 200)
2561 len = 200; /* Bigger than most GDB packets, junk??? */
2562 pkt = pack_hex_byte (pkt, len);
2563 while (len-- > 0)
2564 {
2565 ch = *string++;
2566 if ((ch == '\0') || (ch == '#'))
2567 ch = '*'; /* Protect encapsulation. */
2568 *pkt++ = ch;
2569 }
2570 return pkt;
2571}
2572#endif /* 0 (unused) */
2573
2574static char *
2575unpack_string (char *src, char *dest, int length)
2576{
2577 while (length--)
2578 *dest++ = *src++;
2579 *dest = '\0';
2580 return src;
2581}
2582
2583static char *
2584pack_threadid (char *pkt, threadref *id)
2585{
2586 char *limit;
2587 unsigned char *altid;
2588
2589 altid = (unsigned char *) id;
2590 limit = pkt + BUF_THREAD_ID_SIZE;
2591 while (pkt < limit)
2592 pkt = pack_hex_byte (pkt, *altid++);
2593 return pkt;
2594}
2595
2596
2597static char *
2598unpack_threadid (char *inbuf, threadref *id)
2599{
2600 char *altref;
2601 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2602 int x, y;
2603
2604 altref = (char *) id;
2605
2606 while (inbuf < limit)
2607 {
2608 x = stubhex (*inbuf++);
2609 y = stubhex (*inbuf++);
2610 *altref++ = (x << 4) | y;
2611 }
2612 return inbuf;
2613}
2614
2615/* Externally, threadrefs are 64 bits but internally, they are still
2616 ints. This is due to a mismatch of specifications. We would like
2617 to use 64bit thread references internally. This is an adapter
2618 function. */
2619
2620void
2621int_to_threadref (threadref *id, int value)
2622{
2623 unsigned char *scan;
2624
2625 scan = (unsigned char *) id;
2626 {
2627 int i = 4;
2628 while (i--)
2629 *scan++ = 0;
2630 }
2631 *scan++ = (value >> 24) & 0xff;
2632 *scan++ = (value >> 16) & 0xff;
2633 *scan++ = (value >> 8) & 0xff;
2634 *scan++ = (value & 0xff);
2635}
2636
2637static int
2638threadref_to_int (threadref *ref)
2639{
2640 int i, value = 0;
2641 unsigned char *scan;
2642
2643 scan = *ref;
2644 scan += 4;
2645 i = 4;
2646 while (i-- > 0)
2647 value = (value << 8) | ((*scan++) & 0xff);
2648 return value;
2649}
2650
2651static void
2652copy_threadref (threadref *dest, threadref *src)
2653{
2654 int i;
2655 unsigned char *csrc, *cdest;
2656
2657 csrc = (unsigned char *) src;
2658 cdest = (unsigned char *) dest;
2659 i = 8;
2660 while (i--)
2661 *cdest++ = *csrc++;
2662}
2663
2664static int
2665threadmatch (threadref *dest, threadref *src)
2666{
2667 /* Things are broken right now, so just assume we got a match. */
2668#if 0
2669 unsigned char *srcp, *destp;
2670 int i, result;
2671 srcp = (char *) src;
2672 destp = (char *) dest;
2673
2674 result = 1;
2675 while (i-- > 0)
2676 result &= (*srcp++ == *destp++) ? 1 : 0;
2677 return result;
2678#endif
2679 return 1;
2680}
2681
2682/*
2683 threadid:1, # always request threadid
2684 context_exists:2,
2685 display:4,
2686 unique_name:8,
2687 more_display:16
2688 */
2689
2690/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2691
2692static char *
2693pack_threadinfo_request (char *pkt, int mode, threadref *id)
2694{
2695 *pkt++ = 'q'; /* Info Query */
2696 *pkt++ = 'P'; /* process or thread info */
2697 pkt = pack_int (pkt, mode); /* mode */
2698 pkt = pack_threadid (pkt, id); /* threadid */
2699 *pkt = '\0'; /* terminate */
2700 return pkt;
2701}
2702
2703/* These values tag the fields in a thread info response packet. */
2704/* Tagging the fields allows us to request specific fields and to
2705 add more fields as time goes by. */
2706
2707#define TAG_THREADID 1 /* Echo the thread identifier. */
2708#define TAG_EXISTS 2 /* Is this process defined enough to
2709 fetch registers and its stack? */
2710#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2711#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2712#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2713 the process. */
2714
2715static int
2716remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2717 struct gdb_ext_thread_info *info)
2718{
2719 struct remote_state *rs = get_remote_state ();
2720 int mask, length;
2721 int tag;
2722 threadref ref;
2723 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2724 int retval = 1;
2725
2726 /* info->threadid = 0; FIXME: implement zero_threadref. */
2727 info->active = 0;
2728 info->display[0] = '\0';
2729 info->shortname[0] = '\0';
2730 info->more_display[0] = '\0';
2731
2732 /* Assume the characters indicating the packet type have been
2733 stripped. */
2734 pkt = unpack_int (pkt, &mask); /* arg mask */
2735 pkt = unpack_threadid (pkt, &ref);
2736
2737 if (mask == 0)
2738 warning (_("Incomplete response to threadinfo request."));
2739 if (!threadmatch (&ref, expectedref))
2740 { /* This is an answer to a different request. */
2741 warning (_("ERROR RMT Thread info mismatch."));
2742 return 0;
2743 }
2744 copy_threadref (&info->threadid, &ref);
2745
2746 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2747
2748 /* Packets are terminated with nulls. */
2749 while ((pkt < limit) && mask && *pkt)
2750 {
2751 pkt = unpack_int (pkt, &tag); /* tag */
2752 pkt = unpack_byte (pkt, &length); /* length */
2753 if (!(tag & mask)) /* Tags out of synch with mask. */
2754 {
2755 warning (_("ERROR RMT: threadinfo tag mismatch."));
2756 retval = 0;
2757 break;
2758 }
2759 if (tag == TAG_THREADID)
2760 {
2761 if (length != 16)
2762 {
2763 warning (_("ERROR RMT: length of threadid is not 16."));
2764 retval = 0;
2765 break;
2766 }
2767 pkt = unpack_threadid (pkt, &ref);
2768 mask = mask & ~TAG_THREADID;
2769 continue;
2770 }
2771 if (tag == TAG_EXISTS)
2772 {
2773 info->active = stub_unpack_int (pkt, length);
2774 pkt += length;
2775 mask = mask & ~(TAG_EXISTS);
2776 if (length > 8)
2777 {
2778 warning (_("ERROR RMT: 'exists' length too long."));
2779 retval = 0;
2780 break;
2781 }
2782 continue;
2783 }
2784 if (tag == TAG_THREADNAME)
2785 {
2786 pkt = unpack_string (pkt, &info->shortname[0], length);
2787 mask = mask & ~TAG_THREADNAME;
2788 continue;
2789 }
2790 if (tag == TAG_DISPLAY)
2791 {
2792 pkt = unpack_string (pkt, &info->display[0], length);
2793 mask = mask & ~TAG_DISPLAY;
2794 continue;
2795 }
2796 if (tag == TAG_MOREDISPLAY)
2797 {
2798 pkt = unpack_string (pkt, &info->more_display[0], length);
2799 mask = mask & ~TAG_MOREDISPLAY;
2800 continue;
2801 }
2802 warning (_("ERROR RMT: unknown thread info tag."));
2803 break; /* Not a tag we know about. */
2804 }
2805 return retval;
2806}
2807
2808static int
2809remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2810 struct gdb_ext_thread_info *info)
2811{
2812 struct remote_state *rs = get_remote_state ();
2813 int result;
2814
2815 pack_threadinfo_request (rs->buf, fieldset, threadid);
2816 putpkt (rs->buf);
2817 getpkt (&rs->buf, &rs->buf_size, 0);
2818
2819 if (rs->buf[0] == '\0')
2820 return 0;
2821
2822 result = remote_unpack_thread_info_response (rs->buf + 2,
2823 threadid, info);
2824 return result;
2825}
2826
2827/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2828
2829static char *
2830pack_threadlist_request (char *pkt, int startflag, int threadcount,
2831 threadref *nextthread)
2832{
2833 *pkt++ = 'q'; /* info query packet */
2834 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2835 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2836 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2837 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2838 *pkt = '\0';
2839 return pkt;
2840}
2841
2842/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2843
2844static int
2845parse_threadlist_response (char *pkt, int result_limit,
2846 threadref *original_echo, threadref *resultlist,
2847 int *doneflag)
2848{
2849 struct remote_state *rs = get_remote_state ();
2850 char *limit;
2851 int count, resultcount, done;
2852
2853 resultcount = 0;
2854 /* Assume the 'q' and 'M chars have been stripped. */
2855 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2856 /* done parse past here */
2857 pkt = unpack_byte (pkt, &count); /* count field */
2858 pkt = unpack_nibble (pkt, &done);
2859 /* The first threadid is the argument threadid. */
2860 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2861 while ((count-- > 0) && (pkt < limit))
2862 {
2863 pkt = unpack_threadid (pkt, resultlist++);
2864 if (resultcount++ >= result_limit)
2865 break;
2866 }
2867 if (doneflag)
2868 *doneflag = done;
2869 return resultcount;
2870}
2871
2872/* Fetch the next batch of threads from the remote. Returns -1 if the
2873 qL packet is not supported, 0 on error and 1 on success. */
2874
2875static int
2876remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2877 int *done, int *result_count, threadref *threadlist)
2878{
2879 struct remote_state *rs = get_remote_state ();
2880 int result = 1;
2881
2882 /* Trancate result limit to be smaller than the packet size. */
2883 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2884 >= get_remote_packet_size ())
2885 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2886
2887 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2888 putpkt (rs->buf);
2889 getpkt (&rs->buf, &rs->buf_size, 0);
2890 if (*rs->buf == '\0')
2891 {
2892 /* Packet not supported. */
2893 return -1;
2894 }
2895
2896 *result_count =
2897 parse_threadlist_response (rs->buf + 2, result_limit,
2898 &rs->echo_nextthread, threadlist, done);
2899
2900 if (!threadmatch (&rs->echo_nextthread, nextthread))
2901 {
2902 /* FIXME: This is a good reason to drop the packet. */
2903 /* Possably, there is a duplicate response. */
2904 /* Possabilities :
2905 retransmit immediatly - race conditions
2906 retransmit after timeout - yes
2907 exit
2908 wait for packet, then exit
2909 */
2910 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2911 return 0; /* I choose simply exiting. */
2912 }
2913 if (*result_count <= 0)
2914 {
2915 if (*done != 1)
2916 {
2917 warning (_("RMT ERROR : failed to get remote thread list."));
2918 result = 0;
2919 }
2920 return result; /* break; */
2921 }
2922 if (*result_count > result_limit)
2923 {
2924 *result_count = 0;
2925 warning (_("RMT ERROR: threadlist response longer than requested."));
2926 return 0;
2927 }
2928 return result;
2929}
2930
2931/* Fetch the list of remote threads, with the qL packet, and call
2932 STEPFUNCTION for each thread found. Stops iterating and returns 1
2933 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2934 STEPFUNCTION returns false. If the packet is not supported,
2935 returns -1. */
2936
2937static int
2938remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2939 int looplimit)
2940{
2941 struct remote_state *rs = get_remote_state ();
2942 int done, i, result_count;
2943 int startflag = 1;
2944 int result = 1;
2945 int loopcount = 0;
2946
2947 done = 0;
2948 while (!done)
2949 {
2950 if (loopcount++ > looplimit)
2951 {
2952 result = 0;
2953 warning (_("Remote fetch threadlist -infinite loop-."));
2954 break;
2955 }
2956 result = remote_get_threadlist (startflag, &rs->nextthread,
2957 MAXTHREADLISTRESULTS,
2958 &done, &result_count,
2959 rs->resultthreadlist);
2960 if (result <= 0)
2961 break;
2962 /* Clear for later iterations. */
2963 startflag = 0;
2964 /* Setup to resume next batch of thread references, set nextthread. */
2965 if (result_count >= 1)
2966 copy_threadref (&rs->nextthread,
2967 &rs->resultthreadlist[result_count - 1]);
2968 i = 0;
2969 while (result_count--)
2970 {
2971 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2972 {
2973 result = 0;
2974 break;
2975 }
2976 }
2977 }
2978 return result;
2979}
2980
2981/* A thread found on the remote target. */
2982
2983typedef struct thread_item
2984{
2985 /* The thread's PTID. */
2986 ptid_t ptid;
2987
2988 /* The thread's extra info. May be NULL. */
2989 char *extra;
2990
2991 /* The thread's name. May be NULL. */
2992 char *name;
2993
2994 /* The core the thread was running on. -1 if not known. */
2995 int core;
2996
2997 /* The thread handle associated with the thread. */
2998 gdb::byte_vector *thread_handle;
2999
3000} thread_item_t;
3001DEF_VEC_O(thread_item_t);
3002
3003/* Context passed around to the various methods listing remote
3004 threads. As new threads are found, they're added to the ITEMS
3005 vector. */
3006
3007struct threads_listing_context
3008{
3009 /* The threads found on the remote target. */
3010 VEC (thread_item_t) *items;
3011};
3012
3013/* Discard the contents of the constructed thread listing context. */
3014
3015static void
3016clear_threads_listing_context (void *p)
3017{
3018 struct threads_listing_context *context
3019 = (struct threads_listing_context *) p;
3020 int i;
3021 struct thread_item *item;
3022
3023 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3024 {
3025 xfree (item->extra);
3026 xfree (item->name);
3027 delete item->thread_handle;
3028 }
3029
3030 VEC_free (thread_item_t, context->items);
3031}
3032
3033/* Remove the thread specified as the related_pid field of WS
3034 from the CONTEXT list. */
3035
3036static void
3037threads_listing_context_remove (struct target_waitstatus *ws,
3038 struct threads_listing_context *context)
3039{
3040 struct thread_item *item;
3041 int i;
3042 ptid_t child_ptid = ws->value.related_pid;
3043
3044 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3045 {
3046 if (ptid_equal (item->ptid, child_ptid))
3047 {
3048 VEC_ordered_remove (thread_item_t, context->items, i);
3049 break;
3050 }
3051 }
3052}
3053
3054static int
3055remote_newthread_step (threadref *ref, void *data)
3056{
3057 struct threads_listing_context *context
3058 = (struct threads_listing_context *) data;
3059 struct thread_item item;
3060 int pid = ptid_get_pid (inferior_ptid);
3061
3062 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3063 item.core = -1;
3064 item.name = NULL;
3065 item.extra = NULL;
3066 item.thread_handle = nullptr;
3067
3068 VEC_safe_push (thread_item_t, context->items, &item);
3069
3070 return 1; /* continue iterator */
3071}
3072
3073#define CRAZY_MAX_THREADS 1000
3074
3075static ptid_t
3076remote_current_thread (ptid_t oldpid)
3077{
3078 struct remote_state *rs = get_remote_state ();
3079
3080 putpkt ("qC");
3081 getpkt (&rs->buf, &rs->buf_size, 0);
3082 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3083 {
3084 const char *obuf;
3085 ptid_t result;
3086
3087 result = read_ptid (&rs->buf[2], &obuf);
3088 if (*obuf != '\0' && remote_debug)
3089 fprintf_unfiltered (gdb_stdlog,
3090 "warning: garbage in qC reply\n");
3091
3092 return result;
3093 }
3094 else
3095 return oldpid;
3096}
3097
3098/* List remote threads using the deprecated qL packet. */
3099
3100static int
3101remote_get_threads_with_ql (struct target_ops *ops,
3102 struct threads_listing_context *context)
3103{
3104 if (remote_threadlist_iterator (remote_newthread_step, context,
3105 CRAZY_MAX_THREADS) >= 0)
3106 return 1;
3107
3108 return 0;
3109}
3110
3111#if defined(HAVE_LIBEXPAT)
3112
3113static void
3114start_thread (struct gdb_xml_parser *parser,
3115 const struct gdb_xml_element *element,
3116 void *user_data, VEC(gdb_xml_value_s) *attributes)
3117{
3118 struct threads_listing_context *data
3119 = (struct threads_listing_context *) user_data;
3120
3121 struct thread_item item;
3122 char *id;
3123 struct gdb_xml_value *attr;
3124
3125 id = (char *) xml_find_attribute (attributes, "id")->value;
3126 item.ptid = read_ptid (id, NULL);
3127
3128 attr = xml_find_attribute (attributes, "core");
3129 if (attr != NULL)
3130 item.core = *(ULONGEST *) attr->value;
3131 else
3132 item.core = -1;
3133
3134 attr = xml_find_attribute (attributes, "name");
3135 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3136
3137 attr = xml_find_attribute (attributes, "handle");
3138 if (attr != NULL)
3139 {
3140 item.thread_handle = new gdb::byte_vector
3141 (strlen ((const char *) attr->value) / 2);
3142 hex2bin ((const char *) attr->value, item.thread_handle->data (),
3143 item.thread_handle->size ());
3144 }
3145 else
3146 item.thread_handle = nullptr;
3147
3148 item.extra = 0;
3149
3150 VEC_safe_push (thread_item_t, data->items, &item);
3151}
3152
3153static void
3154end_thread (struct gdb_xml_parser *parser,
3155 const struct gdb_xml_element *element,
3156 void *user_data, const char *body_text)
3157{
3158 struct threads_listing_context *data
3159 = (struct threads_listing_context *) user_data;
3160
3161 if (body_text && *body_text)
3162 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3163}
3164
3165const struct gdb_xml_attribute thread_attributes[] = {
3166 { "id", GDB_XML_AF_NONE, NULL, NULL },
3167 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3168 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3169 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3170 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3171};
3172
3173const struct gdb_xml_element thread_children[] = {
3174 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3175};
3176
3177const struct gdb_xml_element threads_children[] = {
3178 { "thread", thread_attributes, thread_children,
3179 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3180 start_thread, end_thread },
3181 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3182};
3183
3184const struct gdb_xml_element threads_elements[] = {
3185 { "threads", NULL, threads_children,
3186 GDB_XML_EF_NONE, NULL, NULL },
3187 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3188};
3189
3190#endif
3191
3192/* List remote threads using qXfer:threads:read. */
3193
3194static int
3195remote_get_threads_with_qxfer (struct target_ops *ops,
3196 struct threads_listing_context *context)
3197{
3198#if defined(HAVE_LIBEXPAT)
3199 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3200 {
3201 gdb::unique_xmalloc_ptr<char> xml
3202 = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3203
3204 if (xml != NULL && *xml != '\0')
3205 {
3206 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3207 threads_elements, xml.get (), context);
3208 }
3209
3210 return 1;
3211 }
3212#endif
3213
3214 return 0;
3215}
3216
3217/* List remote threads using qfThreadInfo/qsThreadInfo. */
3218
3219static int
3220remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3221 struct threads_listing_context *context)
3222{
3223 struct remote_state *rs = get_remote_state ();
3224
3225 if (rs->use_threadinfo_query)
3226 {
3227 const char *bufp;
3228
3229 putpkt ("qfThreadInfo");
3230 getpkt (&rs->buf, &rs->buf_size, 0);
3231 bufp = rs->buf;
3232 if (bufp[0] != '\0') /* q packet recognized */
3233 {
3234 while (*bufp++ == 'm') /* reply contains one or more TID */
3235 {
3236 do
3237 {
3238 struct thread_item item;
3239
3240 item.ptid = read_ptid (bufp, &bufp);
3241 item.core = -1;
3242 item.name = NULL;
3243 item.extra = NULL;
3244 item.thread_handle = nullptr;
3245
3246 VEC_safe_push (thread_item_t, context->items, &item);
3247 }
3248 while (*bufp++ == ','); /* comma-separated list */
3249 putpkt ("qsThreadInfo");
3250 getpkt (&rs->buf, &rs->buf_size, 0);
3251 bufp = rs->buf;
3252 }
3253 return 1;
3254 }
3255 else
3256 {
3257 /* Packet not recognized. */
3258 rs->use_threadinfo_query = 0;
3259 }
3260 }
3261
3262 return 0;
3263}
3264
3265/* Implement the to_update_thread_list function for the remote
3266 targets. */
3267
3268static void
3269remote_update_thread_list (struct target_ops *ops)
3270{
3271 struct threads_listing_context context;
3272 struct cleanup *old_chain;
3273 int got_list = 0;
3274
3275 context.items = NULL;
3276 old_chain = make_cleanup (clear_threads_listing_context, &context);
3277
3278 /* We have a few different mechanisms to fetch the thread list. Try
3279 them all, starting with the most preferred one first, falling
3280 back to older methods. */
3281 if (remote_get_threads_with_qxfer (ops, &context)
3282 || remote_get_threads_with_qthreadinfo (ops, &context)
3283 || remote_get_threads_with_ql (ops, &context))
3284 {
3285 int i;
3286 struct thread_item *item;
3287 struct thread_info *tp, *tmp;
3288
3289 got_list = 1;
3290
3291 if (VEC_empty (thread_item_t, context.items)
3292 && remote_thread_always_alive (ops, inferior_ptid))
3293 {
3294 /* Some targets don't really support threads, but still
3295 reply an (empty) thread list in response to the thread
3296 listing packets, instead of replying "packet not
3297 supported". Exit early so we don't delete the main
3298 thread. */
3299 do_cleanups (old_chain);
3300 return;
3301 }
3302
3303 /* CONTEXT now holds the current thread list on the remote
3304 target end. Delete GDB-side threads no longer found on the
3305 target. */
3306 ALL_THREADS_SAFE (tp, tmp)
3307 {
3308 for (i = 0;
3309 VEC_iterate (thread_item_t, context.items, i, item);
3310 ++i)
3311 {
3312 if (ptid_equal (item->ptid, tp->ptid))
3313 break;
3314 }
3315
3316 if (i == VEC_length (thread_item_t, context.items))
3317 {
3318 /* Not found. */
3319 delete_thread (tp->ptid);
3320 }
3321 }
3322
3323 /* Remove any unreported fork child threads from CONTEXT so
3324 that we don't interfere with follow fork, which is where
3325 creation of such threads is handled. */
3326 remove_new_fork_children (&context);
3327
3328 /* And now add threads we don't know about yet to our list. */
3329 for (i = 0;
3330 VEC_iterate (thread_item_t, context.items, i, item);
3331 ++i)
3332 {
3333 if (!ptid_equal (item->ptid, null_ptid))
3334 {
3335 struct private_thread_info *info;
3336 /* In non-stop mode, we assume new found threads are
3337 executing until proven otherwise with a stop reply.
3338 In all-stop, we can only get here if all threads are
3339 stopped. */
3340 int executing = target_is_non_stop_p () ? 1 : 0;
3341
3342 remote_notice_new_inferior (item->ptid, executing);
3343
3344 info = get_private_info_ptid (item->ptid);
3345 info->core = item->core;
3346 info->extra = item->extra;
3347 item->extra = NULL;
3348 info->name = item->name;
3349 item->name = NULL;
3350 info->thread_handle = item->thread_handle;
3351 item->thread_handle = nullptr;
3352 }
3353 }
3354 }
3355
3356 if (!got_list)
3357 {
3358 /* If no thread listing method is supported, then query whether
3359 each known thread is alive, one by one, with the T packet.
3360 If the target doesn't support threads at all, then this is a
3361 no-op. See remote_thread_alive. */
3362 prune_threads ();
3363 }
3364
3365 do_cleanups (old_chain);
3366}
3367
3368/*
3369 * Collect a descriptive string about the given thread.
3370 * The target may say anything it wants to about the thread
3371 * (typically info about its blocked / runnable state, name, etc.).
3372 * This string will appear in the info threads display.
3373 *
3374 * Optional: targets are not required to implement this function.
3375 */
3376
3377static const char *
3378remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3379{
3380 struct remote_state *rs = get_remote_state ();
3381 int result;
3382 int set;
3383 threadref id;
3384 struct gdb_ext_thread_info threadinfo;
3385 static char display_buf[100]; /* arbitrary... */
3386 int n = 0; /* position in display_buf */
3387
3388 if (rs->remote_desc == 0) /* paranoia */
3389 internal_error (__FILE__, __LINE__,
3390 _("remote_threads_extra_info"));
3391
3392 if (ptid_equal (tp->ptid, magic_null_ptid)
3393 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3394 /* This is the main thread which was added by GDB. The remote
3395 server doesn't know about it. */
3396 return NULL;
3397
3398 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3399 {
3400 struct thread_info *info = find_thread_ptid (tp->ptid);
3401
3402 if (info && info->priv)
3403 return info->priv->extra;
3404 else
3405 return NULL;
3406 }
3407
3408 if (rs->use_threadextra_query)
3409 {
3410 char *b = rs->buf;
3411 char *endb = rs->buf + get_remote_packet_size ();
3412
3413 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3414 b += strlen (b);
3415 write_ptid (b, endb, tp->ptid);
3416
3417 putpkt (rs->buf);
3418 getpkt (&rs->buf, &rs->buf_size, 0);
3419 if (rs->buf[0] != 0)
3420 {
3421 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3422 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3423 display_buf [result] = '\0';
3424 return display_buf;
3425 }
3426 }
3427
3428 /* If the above query fails, fall back to the old method. */
3429 rs->use_threadextra_query = 0;
3430 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3431 | TAG_MOREDISPLAY | TAG_DISPLAY;
3432 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3433 if (remote_get_threadinfo (&id, set, &threadinfo))
3434 if (threadinfo.active)
3435 {
3436 if (*threadinfo.shortname)
3437 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3438 " Name: %s,", threadinfo.shortname);
3439 if (*threadinfo.display)
3440 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3441 " State: %s,", threadinfo.display);
3442 if (*threadinfo.more_display)
3443 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3444 " Priority: %s", threadinfo.more_display);
3445
3446 if (n > 0)
3447 {
3448 /* For purely cosmetic reasons, clear up trailing commas. */
3449 if (',' == display_buf[n-1])
3450 display_buf[n-1] = ' ';
3451 return display_buf;
3452 }
3453 }
3454 return NULL;
3455}
3456\f
3457
3458static int
3459remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3460 struct static_tracepoint_marker *marker)
3461{
3462 struct remote_state *rs = get_remote_state ();
3463 char *p = rs->buf;
3464
3465 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3466 p += strlen (p);
3467 p += hexnumstr (p, addr);
3468 putpkt (rs->buf);
3469 getpkt (&rs->buf, &rs->buf_size, 0);
3470 p = rs->buf;
3471
3472 if (*p == 'E')
3473 error (_("Remote failure reply: %s"), p);
3474
3475 if (*p++ == 'm')
3476 {
3477 parse_static_tracepoint_marker_definition (p, NULL, marker);
3478 return 1;
3479 }
3480
3481 return 0;
3482}
3483
3484static VEC(static_tracepoint_marker_p) *
3485remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3486 const char *strid)
3487{
3488 struct remote_state *rs = get_remote_state ();
3489 VEC(static_tracepoint_marker_p) *markers = NULL;
3490 struct static_tracepoint_marker *marker = NULL;
3491 struct cleanup *old_chain;
3492 const char *p;
3493
3494 /* Ask for a first packet of static tracepoint marker
3495 definition. */
3496 putpkt ("qTfSTM");
3497 getpkt (&rs->buf, &rs->buf_size, 0);
3498 p = rs->buf;
3499 if (*p == 'E')
3500 error (_("Remote failure reply: %s"), p);
3501
3502 old_chain = make_cleanup (free_current_marker, &marker);
3503
3504 while (*p++ == 'm')
3505 {
3506 if (marker == NULL)
3507 marker = XCNEW (struct static_tracepoint_marker);
3508
3509 do
3510 {
3511 parse_static_tracepoint_marker_definition (p, &p, marker);
3512
3513 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3514 {
3515 VEC_safe_push (static_tracepoint_marker_p,
3516 markers, marker);
3517 marker = NULL;
3518 }
3519 else
3520 {
3521 release_static_tracepoint_marker (marker);
3522 memset (marker, 0, sizeof (*marker));
3523 }
3524 }
3525 while (*p++ == ','); /* comma-separated list */
3526 /* Ask for another packet of static tracepoint definition. */
3527 putpkt ("qTsSTM");
3528 getpkt (&rs->buf, &rs->buf_size, 0);
3529 p = rs->buf;
3530 }
3531
3532 do_cleanups (old_chain);
3533 return markers;
3534}
3535
3536\f
3537/* Implement the to_get_ada_task_ptid function for the remote targets. */
3538
3539static ptid_t
3540remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3541{
3542 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3543}
3544\f
3545
3546/* Restart the remote side; this is an extended protocol operation. */
3547
3548static void
3549extended_remote_restart (void)
3550{
3551 struct remote_state *rs = get_remote_state ();
3552
3553 /* Send the restart command; for reasons I don't understand the
3554 remote side really expects a number after the "R". */
3555 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3556 putpkt (rs->buf);
3557
3558 remote_fileio_reset ();
3559}
3560\f
3561/* Clean up connection to a remote debugger. */
3562
3563static void
3564remote_close (struct target_ops *self)
3565{
3566 struct remote_state *rs = get_remote_state ();
3567
3568 if (rs->remote_desc == NULL)
3569 return; /* already closed */
3570
3571 /* Make sure we leave stdin registered in the event loop. */
3572 remote_terminal_ours (self);
3573
3574 serial_close (rs->remote_desc);
3575 rs->remote_desc = NULL;
3576
3577 /* We don't have a connection to the remote stub anymore. Get rid
3578 of all the inferiors and their threads we were controlling.
3579 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3580 will be unable to find the thread corresponding to (pid, 0, 0). */
3581 inferior_ptid = null_ptid;
3582 discard_all_inferiors ();
3583
3584 /* We are closing the remote target, so we should discard
3585 everything of this target. */
3586 discard_pending_stop_replies_in_queue (rs);
3587
3588 if (remote_async_inferior_event_token)
3589 delete_async_event_handler (&remote_async_inferior_event_token);
3590
3591 remote_notif_state_xfree (rs->notif_state);
3592
3593 trace_reset_local_state ();
3594}
3595
3596/* Query the remote side for the text, data and bss offsets. */
3597
3598static void
3599get_offsets (void)
3600{
3601 struct remote_state *rs = get_remote_state ();
3602 char *buf;
3603 char *ptr;
3604 int lose, num_segments = 0, do_sections, do_segments;
3605 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3606 struct section_offsets *offs;
3607 struct symfile_segment_data *data;
3608
3609 if (symfile_objfile == NULL)
3610 return;
3611
3612 putpkt ("qOffsets");
3613 getpkt (&rs->buf, &rs->buf_size, 0);
3614 buf = rs->buf;
3615
3616 if (buf[0] == '\000')
3617 return; /* Return silently. Stub doesn't support
3618 this command. */
3619 if (buf[0] == 'E')
3620 {
3621 warning (_("Remote failure reply: %s"), buf);
3622 return;
3623 }
3624
3625 /* Pick up each field in turn. This used to be done with scanf, but
3626 scanf will make trouble if CORE_ADDR size doesn't match
3627 conversion directives correctly. The following code will work
3628 with any size of CORE_ADDR. */
3629 text_addr = data_addr = bss_addr = 0;
3630 ptr = buf;
3631 lose = 0;
3632
3633 if (startswith (ptr, "Text="))
3634 {
3635 ptr += 5;
3636 /* Don't use strtol, could lose on big values. */
3637 while (*ptr && *ptr != ';')
3638 text_addr = (text_addr << 4) + fromhex (*ptr++);
3639
3640 if (startswith (ptr, ";Data="))
3641 {
3642 ptr += 6;
3643 while (*ptr && *ptr != ';')
3644 data_addr = (data_addr << 4) + fromhex (*ptr++);
3645 }
3646 else
3647 lose = 1;
3648
3649 if (!lose && startswith (ptr, ";Bss="))
3650 {
3651 ptr += 5;
3652 while (*ptr && *ptr != ';')
3653 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3654
3655 if (bss_addr != data_addr)
3656 warning (_("Target reported unsupported offsets: %s"), buf);
3657 }
3658 else
3659 lose = 1;
3660 }
3661 else if (startswith (ptr, "TextSeg="))
3662 {
3663 ptr += 8;
3664 /* Don't use strtol, could lose on big values. */
3665 while (*ptr && *ptr != ';')
3666 text_addr = (text_addr << 4) + fromhex (*ptr++);
3667 num_segments = 1;
3668
3669 if (startswith (ptr, ";DataSeg="))
3670 {
3671 ptr += 9;
3672 while (*ptr && *ptr != ';')
3673 data_addr = (data_addr << 4) + fromhex (*ptr++);
3674 num_segments++;
3675 }
3676 }
3677 else
3678 lose = 1;
3679
3680 if (lose)
3681 error (_("Malformed response to offset query, %s"), buf);
3682 else if (*ptr != '\0')
3683 warning (_("Target reported unsupported offsets: %s"), buf);
3684
3685 offs = ((struct section_offsets *)
3686 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3687 memcpy (offs, symfile_objfile->section_offsets,
3688 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3689
3690 data = get_symfile_segment_data (symfile_objfile->obfd);
3691 do_segments = (data != NULL);
3692 do_sections = num_segments == 0;
3693
3694 if (num_segments > 0)
3695 {
3696 segments[0] = text_addr;
3697 segments[1] = data_addr;
3698 }
3699 /* If we have two segments, we can still try to relocate everything
3700 by assuming that the .text and .data offsets apply to the whole
3701 text and data segments. Convert the offsets given in the packet
3702 to base addresses for symfile_map_offsets_to_segments. */
3703 else if (data && data->num_segments == 2)
3704 {
3705 segments[0] = data->segment_bases[0] + text_addr;
3706 segments[1] = data->segment_bases[1] + data_addr;
3707 num_segments = 2;
3708 }
3709 /* If the object file has only one segment, assume that it is text
3710 rather than data; main programs with no writable data are rare,
3711 but programs with no code are useless. Of course the code might
3712 have ended up in the data segment... to detect that we would need
3713 the permissions here. */
3714 else if (data && data->num_segments == 1)
3715 {
3716 segments[0] = data->segment_bases[0] + text_addr;
3717 num_segments = 1;
3718 }
3719 /* There's no way to relocate by segment. */
3720 else
3721 do_segments = 0;
3722
3723 if (do_segments)
3724 {
3725 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3726 offs, num_segments, segments);
3727
3728 if (ret == 0 && !do_sections)
3729 error (_("Can not handle qOffsets TextSeg "
3730 "response with this symbol file"));
3731
3732 if (ret > 0)
3733 do_sections = 0;
3734 }
3735
3736 if (data)
3737 free_symfile_segment_data (data);
3738
3739 if (do_sections)
3740 {
3741 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3742
3743 /* This is a temporary kludge to force data and bss to use the
3744 same offsets because that's what nlmconv does now. The real
3745 solution requires changes to the stub and remote.c that I
3746 don't have time to do right now. */
3747
3748 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3749 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3750 }
3751
3752 objfile_relocate (symfile_objfile, offs);
3753}
3754
3755/* Send interrupt_sequence to remote target. */
3756static void
3757send_interrupt_sequence (void)
3758{
3759 struct remote_state *rs = get_remote_state ();
3760
3761 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3762 remote_serial_write ("\x03", 1);
3763 else if (interrupt_sequence_mode == interrupt_sequence_break)
3764 serial_send_break (rs->remote_desc);
3765 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3766 {
3767 serial_send_break (rs->remote_desc);
3768 remote_serial_write ("g", 1);
3769 }
3770 else
3771 internal_error (__FILE__, __LINE__,
3772 _("Invalid value for interrupt_sequence_mode: %s."),
3773 interrupt_sequence_mode);
3774}
3775
3776
3777/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3778 and extract the PTID. Returns NULL_PTID if not found. */
3779
3780static ptid_t
3781stop_reply_extract_thread (char *stop_reply)
3782{
3783 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3784 {
3785 const char *p;
3786
3787 /* Txx r:val ; r:val (...) */
3788 p = &stop_reply[3];
3789
3790 /* Look for "register" named "thread". */
3791 while (*p != '\0')
3792 {
3793 const char *p1;
3794
3795 p1 = strchr (p, ':');
3796 if (p1 == NULL)
3797 return null_ptid;
3798
3799 if (strncmp (p, "thread", p1 - p) == 0)
3800 return read_ptid (++p1, &p);
3801
3802 p1 = strchr (p, ';');
3803 if (p1 == NULL)
3804 return null_ptid;
3805 p1++;
3806
3807 p = p1;
3808 }
3809 }
3810
3811 return null_ptid;
3812}
3813
3814/* Determine the remote side's current thread. If we have a stop
3815 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3816 "thread" register we can extract the current thread from. If not,
3817 ask the remote which is the current thread with qC. The former
3818 method avoids a roundtrip. */
3819
3820static ptid_t
3821get_current_thread (char *wait_status)
3822{
3823 ptid_t ptid = null_ptid;
3824
3825 /* Note we don't use remote_parse_stop_reply as that makes use of
3826 the target architecture, which we haven't yet fully determined at
3827 this point. */
3828 if (wait_status != NULL)
3829 ptid = stop_reply_extract_thread (wait_status);
3830 if (ptid_equal (ptid, null_ptid))
3831 ptid = remote_current_thread (inferior_ptid);
3832
3833 return ptid;
3834}
3835
3836/* Query the remote target for which is the current thread/process,
3837 add it to our tables, and update INFERIOR_PTID. The caller is
3838 responsible for setting the state such that the remote end is ready
3839 to return the current thread.
3840
3841 This function is called after handling the '?' or 'vRun' packets,
3842 whose response is a stop reply from which we can also try
3843 extracting the thread. If the target doesn't support the explicit
3844 qC query, we infer the current thread from that stop reply, passed
3845 in in WAIT_STATUS, which may be NULL. */
3846
3847static void
3848add_current_inferior_and_thread (char *wait_status)
3849{
3850 struct remote_state *rs = get_remote_state ();
3851 int fake_pid_p = 0;
3852
3853 inferior_ptid = null_ptid;
3854
3855 /* Now, if we have thread information, update inferior_ptid. */
3856 ptid_t curr_ptid = get_current_thread (wait_status);
3857
3858 if (curr_ptid != null_ptid)
3859 {
3860 if (!remote_multi_process_p (rs))
3861 fake_pid_p = 1;
3862 }
3863 else
3864 {
3865 /* Without this, some commands which require an active target
3866 (such as kill) won't work. This variable serves (at least)
3867 double duty as both the pid of the target process (if it has
3868 such), and as a flag indicating that a target is active. */
3869 curr_ptid = magic_null_ptid;
3870 fake_pid_p = 1;
3871 }
3872
3873 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
3874
3875 /* Add the main thread and switch to it. Don't try reading
3876 registers yet, since we haven't fetched the target description
3877 yet. */
3878 thread_info *tp = add_thread_silent (curr_ptid);
3879 switch_to_thread_no_regs (tp);
3880}
3881
3882/* Print info about a thread that was found already stopped on
3883 connection. */
3884
3885static void
3886print_one_stopped_thread (struct thread_info *thread)
3887{
3888 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3889
3890 switch_to_thread (thread->ptid);
3891 stop_pc = get_frame_pc (get_current_frame ());
3892 set_current_sal_from_frame (get_current_frame ());
3893
3894 thread->suspend.waitstatus_pending_p = 0;
3895
3896 if (ws->kind == TARGET_WAITKIND_STOPPED)
3897 {
3898 enum gdb_signal sig = ws->value.sig;
3899
3900 if (signal_print_state (sig))
3901 observer_notify_signal_received (sig);
3902 }
3903 observer_notify_normal_stop (NULL, 1);
3904}
3905
3906/* Process all initial stop replies the remote side sent in response
3907 to the ? packet. These indicate threads that were already stopped
3908 on initial connection. We mark these threads as stopped and print
3909 their current frame before giving the user the prompt. */
3910
3911static void
3912process_initial_stop_replies (int from_tty)
3913{
3914 int pending_stop_replies = stop_reply_queue_length ();
3915 struct inferior *inf;
3916 struct thread_info *thread;
3917 struct thread_info *selected = NULL;
3918 struct thread_info *lowest_stopped = NULL;
3919 struct thread_info *first = NULL;
3920
3921 /* Consume the initial pending events. */
3922 while (pending_stop_replies-- > 0)
3923 {
3924 ptid_t waiton_ptid = minus_one_ptid;
3925 ptid_t event_ptid;
3926 struct target_waitstatus ws;
3927 int ignore_event = 0;
3928 struct thread_info *thread;
3929
3930 memset (&ws, 0, sizeof (ws));
3931 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3932 if (remote_debug)
3933 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3934
3935 switch (ws.kind)
3936 {
3937 case TARGET_WAITKIND_IGNORE:
3938 case TARGET_WAITKIND_NO_RESUMED:
3939 case TARGET_WAITKIND_SIGNALLED:
3940 case TARGET_WAITKIND_EXITED:
3941 /* We shouldn't see these, but if we do, just ignore. */
3942 if (remote_debug)
3943 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3944 ignore_event = 1;
3945 break;
3946
3947 case TARGET_WAITKIND_EXECD:
3948 xfree (ws.value.execd_pathname);
3949 break;
3950 default:
3951 break;
3952 }
3953
3954 if (ignore_event)
3955 continue;
3956
3957 thread = find_thread_ptid (event_ptid);
3958
3959 if (ws.kind == TARGET_WAITKIND_STOPPED)
3960 {
3961 enum gdb_signal sig = ws.value.sig;
3962
3963 /* Stubs traditionally report SIGTRAP as initial signal,
3964 instead of signal 0. Suppress it. */
3965 if (sig == GDB_SIGNAL_TRAP)
3966 sig = GDB_SIGNAL_0;
3967 thread->suspend.stop_signal = sig;
3968 ws.value.sig = sig;
3969 }
3970
3971 thread->suspend.waitstatus = ws;
3972
3973 if (ws.kind != TARGET_WAITKIND_STOPPED
3974 || ws.value.sig != GDB_SIGNAL_0)
3975 thread->suspend.waitstatus_pending_p = 1;
3976
3977 set_executing (event_ptid, 0);
3978 set_running (event_ptid, 0);
3979 thread->priv->vcont_resumed = 0;
3980 }
3981
3982 /* "Notice" the new inferiors before anything related to
3983 registers/memory. */
3984 ALL_INFERIORS (inf)
3985 {
3986 if (inf->pid == 0)
3987 continue;
3988
3989 inf->needs_setup = 1;
3990
3991 if (non_stop)
3992 {
3993 thread = any_live_thread_of_process (inf->pid);
3994 notice_new_inferior (thread->ptid,
3995 thread->state == THREAD_RUNNING,
3996 from_tty);
3997 }
3998 }
3999
4000 /* If all-stop on top of non-stop, pause all threads. Note this
4001 records the threads' stop pc, so must be done after "noticing"
4002 the inferiors. */
4003 if (!non_stop)
4004 {
4005 stop_all_threads ();
4006
4007 /* If all threads of an inferior were already stopped, we
4008 haven't setup the inferior yet. */
4009 ALL_INFERIORS (inf)
4010 {
4011 if (inf->pid == 0)
4012 continue;
4013
4014 if (inf->needs_setup)
4015 {
4016 thread = any_live_thread_of_process (inf->pid);
4017 switch_to_thread_no_regs (thread);
4018 setup_inferior (0);
4019 }
4020 }
4021 }
4022
4023 /* Now go over all threads that are stopped, and print their current
4024 frame. If all-stop, then if there's a signalled thread, pick
4025 that as current. */
4026 ALL_NON_EXITED_THREADS (thread)
4027 {
4028 if (first == NULL)
4029 first = thread;
4030
4031 if (!non_stop)
4032 set_running (thread->ptid, 0);
4033 else if (thread->state != THREAD_STOPPED)
4034 continue;
4035
4036 if (selected == NULL
4037 && thread->suspend.waitstatus_pending_p)
4038 selected = thread;
4039
4040 if (lowest_stopped == NULL
4041 || thread->inf->num < lowest_stopped->inf->num
4042 || thread->per_inf_num < lowest_stopped->per_inf_num)
4043 lowest_stopped = thread;
4044
4045 if (non_stop)
4046 print_one_stopped_thread (thread);
4047 }
4048
4049 /* In all-stop, we only print the status of one thread, and leave
4050 others with their status pending. */
4051 if (!non_stop)
4052 {
4053 thread = selected;
4054 if (thread == NULL)
4055 thread = lowest_stopped;
4056 if (thread == NULL)
4057 thread = first;
4058
4059 print_one_stopped_thread (thread);
4060 }
4061
4062 /* For "info program". */
4063 thread = inferior_thread ();
4064 if (thread->state == THREAD_STOPPED)
4065 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4066}
4067
4068/* Start the remote connection and sync state. */
4069
4070static void
4071remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4072{
4073 struct remote_state *rs = get_remote_state ();
4074 struct packet_config *noack_config;
4075 char *wait_status = NULL;
4076
4077 /* Signal other parts that we're going through the initial setup,
4078 and so things may not be stable yet. E.g., we don't try to
4079 install tracepoints until we've relocated symbols. Also, a
4080 Ctrl-C before we're connected and synced up can't interrupt the
4081 target. Instead, it offers to drop the (potentially wedged)
4082 connection. */
4083 rs->starting_up = 1;
4084
4085 QUIT;
4086
4087 if (interrupt_on_connect)
4088 send_interrupt_sequence ();
4089
4090 /* Ack any packet which the remote side has already sent. */
4091 remote_serial_write ("+", 1);
4092
4093 /* The first packet we send to the target is the optional "supported
4094 packets" request. If the target can answer this, it will tell us
4095 which later probes to skip. */
4096 remote_query_supported ();
4097
4098 /* If the stub wants to get a QAllow, compose one and send it. */
4099 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4100 remote_set_permissions (target);
4101
4102 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4103 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4104 as a reply to known packet. For packet "vFile:setfs:" it is an
4105 invalid reply and GDB would return error in
4106 remote_hostio_set_filesystem, making remote files access impossible.
4107 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4108 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4109 {
4110 const char v_mustreplyempty[] = "vMustReplyEmpty";
4111
4112 putpkt (v_mustreplyempty);
4113 getpkt (&rs->buf, &rs->buf_size, 0);
4114 if (strcmp (rs->buf, "OK") == 0)
4115 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4116 else if (strcmp (rs->buf, "") != 0)
4117 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4118 rs->buf);
4119 }
4120
4121 /* Next, we possibly activate noack mode.
4122
4123 If the QStartNoAckMode packet configuration is set to AUTO,
4124 enable noack mode if the stub reported a wish for it with
4125 qSupported.
4126
4127 If set to TRUE, then enable noack mode even if the stub didn't
4128 report it in qSupported. If the stub doesn't reply OK, the
4129 session ends with an error.
4130
4131 If FALSE, then don't activate noack mode, regardless of what the
4132 stub claimed should be the default with qSupported. */
4133
4134 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4135 if (packet_config_support (noack_config) != PACKET_DISABLE)
4136 {
4137 putpkt ("QStartNoAckMode");
4138 getpkt (&rs->buf, &rs->buf_size, 0);
4139 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4140 rs->noack_mode = 1;
4141 }
4142
4143 if (extended_p)
4144 {
4145 /* Tell the remote that we are using the extended protocol. */
4146 putpkt ("!");
4147 getpkt (&rs->buf, &rs->buf_size, 0);
4148 }
4149
4150 /* Let the target know which signals it is allowed to pass down to
4151 the program. */
4152 update_signals_program_target ();
4153
4154 /* Next, if the target can specify a description, read it. We do
4155 this before anything involving memory or registers. */
4156 target_find_description ();
4157
4158 /* Next, now that we know something about the target, update the
4159 address spaces in the program spaces. */
4160 update_address_spaces ();
4161
4162 /* On OSs where the list of libraries is global to all
4163 processes, we fetch them early. */
4164 if (gdbarch_has_global_solist (target_gdbarch ()))
4165 solib_add (NULL, from_tty, auto_solib_add);
4166
4167 if (target_is_non_stop_p ())
4168 {
4169 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4170 error (_("Non-stop mode requested, but remote "
4171 "does not support non-stop"));
4172
4173 putpkt ("QNonStop:1");
4174 getpkt (&rs->buf, &rs->buf_size, 0);
4175
4176 if (strcmp (rs->buf, "OK") != 0)
4177 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4178
4179 /* Find about threads and processes the stub is already
4180 controlling. We default to adding them in the running state.
4181 The '?' query below will then tell us about which threads are
4182 stopped. */
4183 remote_update_thread_list (target);
4184 }
4185 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4186 {
4187 /* Don't assume that the stub can operate in all-stop mode.
4188 Request it explicitly. */
4189 putpkt ("QNonStop:0");
4190 getpkt (&rs->buf, &rs->buf_size, 0);
4191
4192 if (strcmp (rs->buf, "OK") != 0)
4193 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4194 }
4195
4196 /* Upload TSVs regardless of whether the target is running or not. The
4197 remote stub, such as GDBserver, may have some predefined or builtin
4198 TSVs, even if the target is not running. */
4199 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4200 {
4201 struct uploaded_tsv *uploaded_tsvs = NULL;
4202
4203 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4204 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4205 }
4206
4207 /* Check whether the target is running now. */
4208 putpkt ("?");
4209 getpkt (&rs->buf, &rs->buf_size, 0);
4210
4211 if (!target_is_non_stop_p ())
4212 {
4213 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4214 {
4215 if (!extended_p)
4216 error (_("The target is not running (try extended-remote?)"));
4217
4218 /* We're connected, but not running. Drop out before we
4219 call start_remote. */
4220 rs->starting_up = 0;
4221 return;
4222 }
4223 else
4224 {
4225 /* Save the reply for later. */
4226 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4227 strcpy (wait_status, rs->buf);
4228 }
4229
4230 /* Fetch thread list. */
4231 target_update_thread_list ();
4232
4233 /* Let the stub know that we want it to return the thread. */
4234 set_continue_thread (minus_one_ptid);
4235
4236 if (thread_count () == 0)
4237 {
4238 /* Target has no concept of threads at all. GDB treats
4239 non-threaded target as single-threaded; add a main
4240 thread. */
4241 add_current_inferior_and_thread (wait_status);
4242 }
4243 else
4244 {
4245 /* We have thread information; select the thread the target
4246 says should be current. If we're reconnecting to a
4247 multi-threaded program, this will ideally be the thread
4248 that last reported an event before GDB disconnected. */
4249 inferior_ptid = get_current_thread (wait_status);
4250 if (ptid_equal (inferior_ptid, null_ptid))
4251 {
4252 /* Odd... The target was able to list threads, but not
4253 tell us which thread was current (no "thread"
4254 register in T stop reply?). Just pick the first
4255 thread in the thread list then. */
4256
4257 if (remote_debug)
4258 fprintf_unfiltered (gdb_stdlog,
4259 "warning: couldn't determine remote "
4260 "current thread; picking first in list.\n");
4261
4262 inferior_ptid = thread_list->ptid;
4263 }
4264 }
4265
4266 /* init_wait_for_inferior should be called before get_offsets in order
4267 to manage `inserted' flag in bp loc in a correct state.
4268 breakpoint_init_inferior, called from init_wait_for_inferior, set
4269 `inserted' flag to 0, while before breakpoint_re_set, called from
4270 start_remote, set `inserted' flag to 1. In the initialization of
4271 inferior, breakpoint_init_inferior should be called first, and then
4272 breakpoint_re_set can be called. If this order is broken, state of
4273 `inserted' flag is wrong, and cause some problems on breakpoint
4274 manipulation. */
4275 init_wait_for_inferior ();
4276
4277 get_offsets (); /* Get text, data & bss offsets. */
4278
4279 /* If we could not find a description using qXfer, and we know
4280 how to do it some other way, try again. This is not
4281 supported for non-stop; it could be, but it is tricky if
4282 there are no stopped threads when we connect. */
4283 if (remote_read_description_p (target)
4284 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4285 {
4286 target_clear_description ();
4287 target_find_description ();
4288 }
4289
4290 /* Use the previously fetched status. */
4291 gdb_assert (wait_status != NULL);
4292 strcpy (rs->buf, wait_status);
4293 rs->cached_wait_status = 1;
4294
4295 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4296 }
4297 else
4298 {
4299 /* Clear WFI global state. Do this before finding about new
4300 threads and inferiors, and setting the current inferior.
4301 Otherwise we would clear the proceed status of the current
4302 inferior when we want its stop_soon state to be preserved
4303 (see notice_new_inferior). */
4304 init_wait_for_inferior ();
4305
4306 /* In non-stop, we will either get an "OK", meaning that there
4307 are no stopped threads at this time; or, a regular stop
4308 reply. In the latter case, there may be more than one thread
4309 stopped --- we pull them all out using the vStopped
4310 mechanism. */
4311 if (strcmp (rs->buf, "OK") != 0)
4312 {
4313 struct notif_client *notif = &notif_client_stop;
4314
4315 /* remote_notif_get_pending_replies acks this one, and gets
4316 the rest out. */
4317 rs->notif_state->pending_event[notif_client_stop.id]
4318 = remote_notif_parse (notif, rs->buf);
4319 remote_notif_get_pending_events (notif);
4320 }
4321
4322 if (thread_count () == 0)
4323 {
4324 if (!extended_p)
4325 error (_("The target is not running (try extended-remote?)"));
4326
4327 /* We're connected, but not running. Drop out before we
4328 call start_remote. */
4329 rs->starting_up = 0;
4330 return;
4331 }
4332
4333 /* In non-stop mode, any cached wait status will be stored in
4334 the stop reply queue. */
4335 gdb_assert (wait_status == NULL);
4336
4337 /* Report all signals during attach/startup. */
4338 remote_pass_signals (target, 0, NULL);
4339
4340 /* If there are already stopped threads, mark them stopped and
4341 report their stops before giving the prompt to the user. */
4342 process_initial_stop_replies (from_tty);
4343
4344 if (target_can_async_p ())
4345 target_async (1);
4346 }
4347
4348 /* If we connected to a live target, do some additional setup. */
4349 if (target_has_execution)
4350 {
4351 if (symfile_objfile) /* No use without a symbol-file. */
4352 remote_check_symbols ();
4353 }
4354
4355 /* Possibly the target has been engaged in a trace run started
4356 previously; find out where things are at. */
4357 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4358 {
4359 struct uploaded_tp *uploaded_tps = NULL;
4360
4361 if (current_trace_status ()->running)
4362 printf_filtered (_("Trace is already running on the target.\n"));
4363
4364 remote_upload_tracepoints (target, &uploaded_tps);
4365
4366 merge_uploaded_tracepoints (&uploaded_tps);
4367 }
4368
4369 /* Possibly the target has been engaged in a btrace record started
4370 previously; find out where things are at. */
4371 remote_btrace_maybe_reopen ();
4372
4373 /* The thread and inferior lists are now synchronized with the
4374 target, our symbols have been relocated, and we're merged the
4375 target's tracepoints with ours. We're done with basic start
4376 up. */
4377 rs->starting_up = 0;
4378
4379 /* Maybe breakpoints are global and need to be inserted now. */
4380 if (breakpoints_should_be_inserted_now ())
4381 insert_breakpoints ();
4382}
4383
4384/* Open a connection to a remote debugger.
4385 NAME is the filename used for communication. */
4386
4387static void
4388remote_open (const char *name, int from_tty)
4389{
4390 remote_open_1 (name, from_tty, &remote_ops, 0);
4391}
4392
4393/* Open a connection to a remote debugger using the extended
4394 remote gdb protocol. NAME is the filename used for communication. */
4395
4396static void
4397extended_remote_open (const char *name, int from_tty)
4398{
4399 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4400}
4401
4402/* Reset all packets back to "unknown support". Called when opening a
4403 new connection to a remote target. */
4404
4405static void
4406reset_all_packet_configs_support (void)
4407{
4408 int i;
4409
4410 for (i = 0; i < PACKET_MAX; i++)
4411 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4412}
4413
4414/* Initialize all packet configs. */
4415
4416static void
4417init_all_packet_configs (void)
4418{
4419 int i;
4420
4421 for (i = 0; i < PACKET_MAX; i++)
4422 {
4423 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4424 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4425 }
4426}
4427
4428/* Symbol look-up. */
4429
4430static void
4431remote_check_symbols (void)
4432{
4433 struct remote_state *rs = get_remote_state ();
4434 char *msg, *reply, *tmp;
4435 int end;
4436 long reply_size;
4437 struct cleanup *old_chain;
4438
4439 /* The remote side has no concept of inferiors that aren't running
4440 yet, it only knows about running processes. If we're connected
4441 but our current inferior is not running, we should not invite the
4442 remote target to request symbol lookups related to its
4443 (unrelated) current process. */
4444 if (!target_has_execution)
4445 return;
4446
4447 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4448 return;
4449
4450 /* Make sure the remote is pointing at the right process. Note
4451 there's no way to select "no process". */
4452 set_general_process ();
4453
4454 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4455 because we need both at the same time. */
4456 msg = (char *) xmalloc (get_remote_packet_size ());
4457 old_chain = make_cleanup (xfree, msg);
4458 reply = (char *) xmalloc (get_remote_packet_size ());
4459 make_cleanup (free_current_contents, &reply);
4460 reply_size = get_remote_packet_size ();
4461
4462 /* Invite target to request symbol lookups. */
4463
4464 putpkt ("qSymbol::");
4465 getpkt (&reply, &reply_size, 0);
4466 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4467
4468 while (startswith (reply, "qSymbol:"))
4469 {
4470 struct bound_minimal_symbol sym;
4471
4472 tmp = &reply[8];
4473 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4474 msg[end] = '\0';
4475 sym = lookup_minimal_symbol (msg, NULL, NULL);
4476 if (sym.minsym == NULL)
4477 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4478 else
4479 {
4480 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4481 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4482
4483 /* If this is a function address, return the start of code
4484 instead of any data function descriptor. */
4485 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4486 sym_addr,
4487 &current_target);
4488
4489 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4490 phex_nz (sym_addr, addr_size), &reply[8]);
4491 }
4492
4493 putpkt (msg);
4494 getpkt (&reply, &reply_size, 0);
4495 }
4496
4497 do_cleanups (old_chain);
4498}
4499
4500static struct serial *
4501remote_serial_open (const char *name)
4502{
4503 static int udp_warning = 0;
4504
4505 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4506 of in ser-tcp.c, because it is the remote protocol assuming that the
4507 serial connection is reliable and not the serial connection promising
4508 to be. */
4509 if (!udp_warning && startswith (name, "udp:"))
4510 {
4511 warning (_("The remote protocol may be unreliable over UDP.\n"
4512 "Some events may be lost, rendering further debugging "
4513 "impossible."));
4514 udp_warning = 1;
4515 }
4516
4517 return serial_open (name);
4518}
4519
4520/* Inform the target of our permission settings. The permission flags
4521 work without this, but if the target knows the settings, it can do
4522 a couple things. First, it can add its own check, to catch cases
4523 that somehow manage to get by the permissions checks in target
4524 methods. Second, if the target is wired to disallow particular
4525 settings (for instance, a system in the field that is not set up to
4526 be able to stop at a breakpoint), it can object to any unavailable
4527 permissions. */
4528
4529void
4530remote_set_permissions (struct target_ops *self)
4531{
4532 struct remote_state *rs = get_remote_state ();
4533
4534 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4535 "WriteReg:%x;WriteMem:%x;"
4536 "InsertBreak:%x;InsertTrace:%x;"
4537 "InsertFastTrace:%x;Stop:%x",
4538 may_write_registers, may_write_memory,
4539 may_insert_breakpoints, may_insert_tracepoints,
4540 may_insert_fast_tracepoints, may_stop);
4541 putpkt (rs->buf);
4542 getpkt (&rs->buf, &rs->buf_size, 0);
4543
4544 /* If the target didn't like the packet, warn the user. Do not try
4545 to undo the user's settings, that would just be maddening. */
4546 if (strcmp (rs->buf, "OK") != 0)
4547 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4548}
4549
4550/* This type describes each known response to the qSupported
4551 packet. */
4552struct protocol_feature
4553{
4554 /* The name of this protocol feature. */
4555 const char *name;
4556
4557 /* The default for this protocol feature. */
4558 enum packet_support default_support;
4559
4560 /* The function to call when this feature is reported, or after
4561 qSupported processing if the feature is not supported.
4562 The first argument points to this structure. The second
4563 argument indicates whether the packet requested support be
4564 enabled, disabled, or probed (or the default, if this function
4565 is being called at the end of processing and this feature was
4566 not reported). The third argument may be NULL; if not NULL, it
4567 is a NUL-terminated string taken from the packet following
4568 this feature's name and an equals sign. */
4569 void (*func) (const struct protocol_feature *, enum packet_support,
4570 const char *);
4571
4572 /* The corresponding packet for this feature. Only used if
4573 FUNC is remote_supported_packet. */
4574 int packet;
4575};
4576
4577static void
4578remote_supported_packet (const struct protocol_feature *feature,
4579 enum packet_support support,
4580 const char *argument)
4581{
4582 if (argument)
4583 {
4584 warning (_("Remote qSupported response supplied an unexpected value for"
4585 " \"%s\"."), feature->name);
4586 return;
4587 }
4588
4589 remote_protocol_packets[feature->packet].support = support;
4590}
4591
4592static void
4593remote_packet_size (const struct protocol_feature *feature,
4594 enum packet_support support, const char *value)
4595{
4596 struct remote_state *rs = get_remote_state ();
4597
4598 int packet_size;
4599 char *value_end;
4600
4601 if (support != PACKET_ENABLE)
4602 return;
4603
4604 if (value == NULL || *value == '\0')
4605 {
4606 warning (_("Remote target reported \"%s\" without a size."),
4607 feature->name);
4608 return;
4609 }
4610
4611 errno = 0;
4612 packet_size = strtol (value, &value_end, 16);
4613 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4614 {
4615 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4616 feature->name, value);
4617 return;
4618 }
4619
4620 /* Record the new maximum packet size. */
4621 rs->explicit_packet_size = packet_size;
4622}
4623
4624static const struct protocol_feature remote_protocol_features[] = {
4625 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4626 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4627 PACKET_qXfer_auxv },
4628 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4629 PACKET_qXfer_exec_file },
4630 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4631 PACKET_qXfer_features },
4632 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4633 PACKET_qXfer_libraries },
4634 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4635 PACKET_qXfer_libraries_svr4 },
4636 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4637 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4638 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4639 PACKET_qXfer_memory_map },
4640 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4641 PACKET_qXfer_spu_read },
4642 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4643 PACKET_qXfer_spu_write },
4644 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4645 PACKET_qXfer_osdata },
4646 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4647 PACKET_qXfer_threads },
4648 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4649 PACKET_qXfer_traceframe_info },
4650 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4651 PACKET_QPassSignals },
4652 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4653 PACKET_QCatchSyscalls },
4654 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4655 PACKET_QProgramSignals },
4656 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4657 PACKET_QSetWorkingDir },
4658 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4659 PACKET_QStartupWithShell },
4660 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4661 PACKET_QEnvironmentHexEncoded },
4662 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4663 PACKET_QEnvironmentReset },
4664 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4665 PACKET_QEnvironmentUnset },
4666 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4667 PACKET_QStartNoAckMode },
4668 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4669 PACKET_multiprocess_feature },
4670 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4671 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4672 PACKET_qXfer_siginfo_read },
4673 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4674 PACKET_qXfer_siginfo_write },
4675 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4676 PACKET_ConditionalTracepoints },
4677 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4678 PACKET_ConditionalBreakpoints },
4679 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4680 PACKET_BreakpointCommands },
4681 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4682 PACKET_FastTracepoints },
4683 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4684 PACKET_StaticTracepoints },
4685 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4686 PACKET_InstallInTrace},
4687 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4688 PACKET_DisconnectedTracing_feature },
4689 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4690 PACKET_bc },
4691 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4692 PACKET_bs },
4693 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4694 PACKET_TracepointSource },
4695 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4696 PACKET_QAllow },
4697 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4698 PACKET_EnableDisableTracepoints_feature },
4699 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4700 PACKET_qXfer_fdpic },
4701 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4702 PACKET_qXfer_uib },
4703 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4704 PACKET_QDisableRandomization },
4705 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4706 { "QTBuffer:size", PACKET_DISABLE,
4707 remote_supported_packet, PACKET_QTBuffer_size},
4708 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4709 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4710 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4711 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4712 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4713 PACKET_qXfer_btrace },
4714 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4715 PACKET_qXfer_btrace_conf },
4716 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4717 PACKET_Qbtrace_conf_bts_size },
4718 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4719 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4720 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4721 PACKET_fork_event_feature },
4722 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4723 PACKET_vfork_event_feature },
4724 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4725 PACKET_exec_event_feature },
4726 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4727 PACKET_Qbtrace_conf_pt_size },
4728 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4729 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4730 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4731};
4732
4733static char *remote_support_xml;
4734
4735/* Register string appended to "xmlRegisters=" in qSupported query. */
4736
4737void
4738register_remote_support_xml (const char *xml)
4739{
4740#if defined(HAVE_LIBEXPAT)
4741 if (remote_support_xml == NULL)
4742 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4743 else
4744 {
4745 char *copy = xstrdup (remote_support_xml + 13);
4746 char *p = strtok (copy, ",");
4747
4748 do
4749 {
4750 if (strcmp (p, xml) == 0)
4751 {
4752 /* already there */
4753 xfree (copy);
4754 return;
4755 }
4756 }
4757 while ((p = strtok (NULL, ",")) != NULL);
4758 xfree (copy);
4759
4760 remote_support_xml = reconcat (remote_support_xml,
4761 remote_support_xml, ",", xml,
4762 (char *) NULL);
4763 }
4764#endif
4765}
4766
4767static char *
4768remote_query_supported_append (char *msg, const char *append)
4769{
4770 if (msg)
4771 return reconcat (msg, msg, ";", append, (char *) NULL);
4772 else
4773 return xstrdup (append);
4774}
4775
4776static void
4777remote_query_supported (void)
4778{
4779 struct remote_state *rs = get_remote_state ();
4780 char *next;
4781 int i;
4782 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4783
4784 /* The packet support flags are handled differently for this packet
4785 than for most others. We treat an error, a disabled packet, and
4786 an empty response identically: any features which must be reported
4787 to be used will be automatically disabled. An empty buffer
4788 accomplishes this, since that is also the representation for a list
4789 containing no features. */
4790
4791 rs->buf[0] = 0;
4792 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4793 {
4794 char *q = NULL;
4795 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4796
4797 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4798 q = remote_query_supported_append (q, "multiprocess+");
4799
4800 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4801 q = remote_query_supported_append (q, "swbreak+");
4802 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4803 q = remote_query_supported_append (q, "hwbreak+");
4804
4805 q = remote_query_supported_append (q, "qRelocInsn+");
4806
4807 if (packet_set_cmd_state (PACKET_fork_event_feature)
4808 != AUTO_BOOLEAN_FALSE)
4809 q = remote_query_supported_append (q, "fork-events+");
4810 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4811 != AUTO_BOOLEAN_FALSE)
4812 q = remote_query_supported_append (q, "vfork-events+");
4813 if (packet_set_cmd_state (PACKET_exec_event_feature)
4814 != AUTO_BOOLEAN_FALSE)
4815 q = remote_query_supported_append (q, "exec-events+");
4816
4817 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4818 q = remote_query_supported_append (q, "vContSupported+");
4819
4820 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4821 q = remote_query_supported_append (q, "QThreadEvents+");
4822
4823 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4824 q = remote_query_supported_append (q, "no-resumed+");
4825
4826 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4827 the qSupported:xmlRegisters=i386 handling. */
4828 if (remote_support_xml != NULL)
4829 q = remote_query_supported_append (q, remote_support_xml);
4830
4831 q = reconcat (q, "qSupported:", q, (char *) NULL);
4832 putpkt (q);
4833
4834 do_cleanups (old_chain);
4835
4836 getpkt (&rs->buf, &rs->buf_size, 0);
4837
4838 /* If an error occured, warn, but do not return - just reset the
4839 buffer to empty and go on to disable features. */
4840 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4841 == PACKET_ERROR)
4842 {
4843 warning (_("Remote failure reply: %s"), rs->buf);
4844 rs->buf[0] = 0;
4845 }
4846 }
4847
4848 memset (seen, 0, sizeof (seen));
4849
4850 next = rs->buf;
4851 while (*next)
4852 {
4853 enum packet_support is_supported;
4854 char *p, *end, *name_end, *value;
4855
4856 /* First separate out this item from the rest of the packet. If
4857 there's another item after this, we overwrite the separator
4858 (terminated strings are much easier to work with). */
4859 p = next;
4860 end = strchr (p, ';');
4861 if (end == NULL)
4862 {
4863 end = p + strlen (p);
4864 next = end;
4865 }
4866 else
4867 {
4868 *end = '\0';
4869 next = end + 1;
4870
4871 if (end == p)
4872 {
4873 warning (_("empty item in \"qSupported\" response"));
4874 continue;
4875 }
4876 }
4877
4878 name_end = strchr (p, '=');
4879 if (name_end)
4880 {
4881 /* This is a name=value entry. */
4882 is_supported = PACKET_ENABLE;
4883 value = name_end + 1;
4884 *name_end = '\0';
4885 }
4886 else
4887 {
4888 value = NULL;
4889 switch (end[-1])
4890 {
4891 case '+':
4892 is_supported = PACKET_ENABLE;
4893 break;
4894
4895 case '-':
4896 is_supported = PACKET_DISABLE;
4897 break;
4898
4899 case '?':
4900 is_supported = PACKET_SUPPORT_UNKNOWN;
4901 break;
4902
4903 default:
4904 warning (_("unrecognized item \"%s\" "
4905 "in \"qSupported\" response"), p);
4906 continue;
4907 }
4908 end[-1] = '\0';
4909 }
4910
4911 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4912 if (strcmp (remote_protocol_features[i].name, p) == 0)
4913 {
4914 const struct protocol_feature *feature;
4915
4916 seen[i] = 1;
4917 feature = &remote_protocol_features[i];
4918 feature->func (feature, is_supported, value);
4919 break;
4920 }
4921 }
4922
4923 /* If we increased the packet size, make sure to increase the global
4924 buffer size also. We delay this until after parsing the entire
4925 qSupported packet, because this is the same buffer we were
4926 parsing. */
4927 if (rs->buf_size < rs->explicit_packet_size)
4928 {
4929 rs->buf_size = rs->explicit_packet_size;
4930 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4931 }
4932
4933 /* Handle the defaults for unmentioned features. */
4934 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4935 if (!seen[i])
4936 {
4937 const struct protocol_feature *feature;
4938
4939 feature = &remote_protocol_features[i];
4940 feature->func (feature, feature->default_support, NULL);
4941 }
4942}
4943
4944/* Serial QUIT handler for the remote serial descriptor.
4945
4946 Defers handling a Ctrl-C until we're done with the current
4947 command/response packet sequence, unless:
4948
4949 - We're setting up the connection. Don't send a remote interrupt
4950 request, as we're not fully synced yet. Quit immediately
4951 instead.
4952
4953 - The target has been resumed in the foreground
4954 (target_terminal::is_ours is false) with a synchronous resume
4955 packet, and we're blocked waiting for the stop reply, thus a
4956 Ctrl-C should be immediately sent to the target.
4957
4958 - We get a second Ctrl-C while still within the same serial read or
4959 write. In that case the serial is seemingly wedged --- offer to
4960 quit/disconnect.
4961
4962 - We see a second Ctrl-C without target response, after having
4963 previously interrupted the target. In that case the target/stub
4964 is probably wedged --- offer to quit/disconnect.
4965*/
4966
4967static void
4968remote_serial_quit_handler (void)
4969{
4970 struct remote_state *rs = get_remote_state ();
4971
4972 if (check_quit_flag ())
4973 {
4974 /* If we're starting up, we're not fully synced yet. Quit
4975 immediately. */
4976 if (rs->starting_up)
4977 quit ();
4978 else if (rs->got_ctrlc_during_io)
4979 {
4980 if (query (_("The target is not responding to GDB commands.\n"
4981 "Stop debugging it? ")))
4982 remote_unpush_and_throw ();
4983 }
4984 /* If ^C has already been sent once, offer to disconnect. */
4985 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
4986 interrupt_query ();
4987 /* All-stop protocol, and blocked waiting for stop reply. Send
4988 an interrupt request. */
4989 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
4990 target_interrupt (inferior_ptid);
4991 else
4992 rs->got_ctrlc_during_io = 1;
4993 }
4994}
4995
4996/* Remove any of the remote.c targets from target stack. Upper targets depend
4997 on it so remove them first. */
4998
4999static void
5000remote_unpush_target (void)
5001{
5002 pop_all_targets_at_and_above (process_stratum);
5003}
5004
5005static void
5006remote_unpush_and_throw (void)
5007{
5008 remote_unpush_target ();
5009 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5010}
5011
5012static void
5013remote_open_1 (const char *name, int from_tty,
5014 struct target_ops *target, int extended_p)
5015{
5016 struct remote_state *rs = get_remote_state ();
5017
5018 if (name == 0)
5019 error (_("To open a remote debug connection, you need to specify what\n"
5020 "serial device is attached to the remote system\n"
5021 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5022
5023 /* See FIXME above. */
5024 if (!target_async_permitted)
5025 wait_forever_enabled_p = 1;
5026
5027 /* If we're connected to a running target, target_preopen will kill it.
5028 Ask this question first, before target_preopen has a chance to kill
5029 anything. */
5030 if (rs->remote_desc != NULL && !have_inferiors ())
5031 {
5032 if (from_tty
5033 && !query (_("Already connected to a remote target. Disconnect? ")))
5034 error (_("Still connected."));
5035 }
5036
5037 /* Here the possibly existing remote target gets unpushed. */
5038 target_preopen (from_tty);
5039
5040 /* Make sure we send the passed signals list the next time we resume. */
5041 xfree (rs->last_pass_packet);
5042 rs->last_pass_packet = NULL;
5043
5044 /* Make sure we send the program signals list the next time we
5045 resume. */
5046 xfree (rs->last_program_signals_packet);
5047 rs->last_program_signals_packet = NULL;
5048
5049 remote_fileio_reset ();
5050 reopen_exec_file ();
5051 reread_symbols ();
5052
5053 rs->remote_desc = remote_serial_open (name);
5054 if (!rs->remote_desc)
5055 perror_with_name (name);
5056
5057 if (baud_rate != -1)
5058 {
5059 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5060 {
5061 /* The requested speed could not be set. Error out to
5062 top level after closing remote_desc. Take care to
5063 set remote_desc to NULL to avoid closing remote_desc
5064 more than once. */
5065 serial_close (rs->remote_desc);
5066 rs->remote_desc = NULL;
5067 perror_with_name (name);
5068 }
5069 }
5070
5071 serial_setparity (rs->remote_desc, serial_parity);
5072 serial_raw (rs->remote_desc);
5073
5074 /* If there is something sitting in the buffer we might take it as a
5075 response to a command, which would be bad. */
5076 serial_flush_input (rs->remote_desc);
5077
5078 if (from_tty)
5079 {
5080 puts_filtered ("Remote debugging using ");
5081 puts_filtered (name);
5082 puts_filtered ("\n");
5083 }
5084 push_target (target); /* Switch to using remote target now. */
5085
5086 /* Register extra event sources in the event loop. */
5087 remote_async_inferior_event_token
5088 = create_async_event_handler (remote_async_inferior_event_handler,
5089 NULL);
5090 rs->notif_state = remote_notif_state_allocate ();
5091
5092 /* Reset the target state; these things will be queried either by
5093 remote_query_supported or as they are needed. */
5094 reset_all_packet_configs_support ();
5095 rs->cached_wait_status = 0;
5096 rs->explicit_packet_size = 0;
5097 rs->noack_mode = 0;
5098 rs->extended = extended_p;
5099 rs->waiting_for_stop_reply = 0;
5100 rs->ctrlc_pending_p = 0;
5101 rs->got_ctrlc_during_io = 0;
5102
5103 rs->general_thread = not_sent_ptid;
5104 rs->continue_thread = not_sent_ptid;
5105 rs->remote_traceframe_number = -1;
5106
5107 rs->last_resume_exec_dir = EXEC_FORWARD;
5108
5109 /* Probe for ability to use "ThreadInfo" query, as required. */
5110 rs->use_threadinfo_query = 1;
5111 rs->use_threadextra_query = 1;
5112
5113 readahead_cache_invalidate ();
5114
5115 if (target_async_permitted)
5116 {
5117 /* FIXME: cagney/1999-09-23: During the initial connection it is
5118 assumed that the target is already ready and able to respond to
5119 requests. Unfortunately remote_start_remote() eventually calls
5120 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5121 around this. Eventually a mechanism that allows
5122 wait_for_inferior() to expect/get timeouts will be
5123 implemented. */
5124 wait_forever_enabled_p = 0;
5125 }
5126
5127 /* First delete any symbols previously loaded from shared libraries. */
5128 no_shared_libraries (NULL, 0);
5129
5130 /* Start afresh. */
5131 init_thread_list ();
5132
5133 /* Start the remote connection. If error() or QUIT, discard this
5134 target (we'd otherwise be in an inconsistent state) and then
5135 propogate the error on up the exception chain. This ensures that
5136 the caller doesn't stumble along blindly assuming that the
5137 function succeeded. The CLI doesn't have this problem but other
5138 UI's, such as MI do.
5139
5140 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5141 this function should return an error indication letting the
5142 caller restore the previous state. Unfortunately the command
5143 ``target remote'' is directly wired to this function making that
5144 impossible. On a positive note, the CLI side of this problem has
5145 been fixed - the function set_cmd_context() makes it possible for
5146 all the ``target ....'' commands to share a common callback
5147 function. See cli-dump.c. */
5148 {
5149
5150 TRY
5151 {
5152 remote_start_remote (from_tty, target, extended_p);
5153 }
5154 CATCH (ex, RETURN_MASK_ALL)
5155 {
5156 /* Pop the partially set up target - unless something else did
5157 already before throwing the exception. */
5158 if (rs->remote_desc != NULL)
5159 remote_unpush_target ();
5160 if (target_async_permitted)
5161 wait_forever_enabled_p = 1;
5162 throw_exception (ex);
5163 }
5164 END_CATCH
5165 }
5166
5167 remote_btrace_reset ();
5168
5169 if (target_async_permitted)
5170 wait_forever_enabled_p = 1;
5171}
5172
5173/* Detach the specified process. */
5174
5175static void
5176remote_detach_pid (int pid)
5177{
5178 struct remote_state *rs = get_remote_state ();
5179
5180 if (remote_multi_process_p (rs))
5181 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5182 else
5183 strcpy (rs->buf, "D");
5184
5185 putpkt (rs->buf);
5186 getpkt (&rs->buf, &rs->buf_size, 0);
5187
5188 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5189 ;
5190 else if (rs->buf[0] == '\0')
5191 error (_("Remote doesn't know how to detach"));
5192 else
5193 error (_("Can't detach process."));
5194}
5195
5196/* This detaches a program to which we previously attached, using
5197 inferior_ptid to identify the process. After this is done, GDB
5198 can be used to debug some other program. We better not have left
5199 any breakpoints in the target program or it'll die when it hits
5200 one. */
5201
5202static void
5203remote_detach_1 (const char *args, int from_tty)
5204{
5205 int pid = ptid_get_pid (inferior_ptid);
5206 struct remote_state *rs = get_remote_state ();
5207 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5208 int is_fork_parent;
5209
5210 if (args)
5211 error (_("Argument given to \"detach\" when remotely debugging."));
5212
5213 if (!target_has_execution)
5214 error (_("No process to detach from."));
5215
5216 target_announce_detach (from_tty);
5217
5218 /* Tell the remote target to detach. */
5219 remote_detach_pid (pid);
5220
5221 /* Exit only if this is the only active inferior. */
5222 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5223 puts_filtered (_("Ending remote debugging.\n"));
5224
5225 /* Check to see if we are detaching a fork parent. Note that if we
5226 are detaching a fork child, tp == NULL. */
5227 is_fork_parent = (tp != NULL
5228 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5229
5230 /* If doing detach-on-fork, we don't mourn, because that will delete
5231 breakpoints that should be available for the followed inferior. */
5232 if (!is_fork_parent)
5233 target_mourn_inferior (inferior_ptid);
5234 else
5235 {
5236 inferior_ptid = null_ptid;
5237 detach_inferior (pid);
5238 }
5239}
5240
5241static void
5242remote_detach (struct target_ops *ops, const char *args, int from_tty)
5243{
5244 remote_detach_1 (args, from_tty);
5245}
5246
5247static void
5248extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5249{
5250 remote_detach_1 (args, from_tty);
5251}
5252
5253/* Target follow-fork function for remote targets. On entry, and
5254 at return, the current inferior is the fork parent.
5255
5256 Note that although this is currently only used for extended-remote,
5257 it is named remote_follow_fork in anticipation of using it for the
5258 remote target as well. */
5259
5260static int
5261remote_follow_fork (struct target_ops *ops, int follow_child,
5262 int detach_fork)
5263{
5264 struct remote_state *rs = get_remote_state ();
5265 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5266
5267 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5268 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5269 {
5270 /* When following the parent and detaching the child, we detach
5271 the child here. For the case of following the child and
5272 detaching the parent, the detach is done in the target-
5273 independent follow fork code in infrun.c. We can't use
5274 target_detach when detaching an unfollowed child because
5275 the client side doesn't know anything about the child. */
5276 if (detach_fork && !follow_child)
5277 {
5278 /* Detach the fork child. */
5279 ptid_t child_ptid;
5280 pid_t child_pid;
5281
5282 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5283 child_pid = ptid_get_pid (child_ptid);
5284
5285 remote_detach_pid (child_pid);
5286 detach_inferior (child_pid);
5287 }
5288 }
5289 return 0;
5290}
5291
5292/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5293 in the program space of the new inferior. On entry and at return the
5294 current inferior is the exec'ing inferior. INF is the new exec'd
5295 inferior, which may be the same as the exec'ing inferior unless
5296 follow-exec-mode is "new". */
5297
5298static void
5299remote_follow_exec (struct target_ops *ops,
5300 struct inferior *inf, char *execd_pathname)
5301{
5302 /* We know that this is a target file name, so if it has the "target:"
5303 prefix we strip it off before saving it in the program space. */
5304 if (is_target_filename (execd_pathname))
5305 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5306
5307 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5308}
5309
5310/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5311
5312static void
5313remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5314{
5315 if (args)
5316 error (_("Argument given to \"disconnect\" when remotely debugging."));
5317
5318 /* Make sure we unpush even the extended remote targets. Calling
5319 target_mourn_inferior won't unpush, and remote_mourn won't
5320 unpush if there is more than one inferior left. */
5321 unpush_target (target);
5322 generic_mourn_inferior ();
5323
5324 if (from_tty)
5325 puts_filtered ("Ending remote debugging.\n");
5326}
5327
5328/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5329 be chatty about it. */
5330
5331static void
5332extended_remote_attach (struct target_ops *target, const char *args,
5333 int from_tty)
5334{
5335 struct remote_state *rs = get_remote_state ();
5336 int pid;
5337 char *wait_status = NULL;
5338
5339 pid = parse_pid_to_attach (args);
5340
5341 /* Remote PID can be freely equal to getpid, do not check it here the same
5342 way as in other targets. */
5343
5344 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5345 error (_("This target does not support attaching to a process"));
5346
5347 if (from_tty)
5348 {
5349 char *exec_file = get_exec_file (0);
5350
5351 if (exec_file)
5352 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5353 target_pid_to_str (pid_to_ptid (pid)));
5354 else
5355 printf_unfiltered (_("Attaching to %s\n"),
5356 target_pid_to_str (pid_to_ptid (pid)));
5357
5358 gdb_flush (gdb_stdout);
5359 }
5360
5361 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5362 putpkt (rs->buf);
5363 getpkt (&rs->buf, &rs->buf_size, 0);
5364
5365 switch (packet_ok (rs->buf,
5366 &remote_protocol_packets[PACKET_vAttach]))
5367 {
5368 case PACKET_OK:
5369 if (!target_is_non_stop_p ())
5370 {
5371 /* Save the reply for later. */
5372 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5373 strcpy (wait_status, rs->buf);
5374 }
5375 else if (strcmp (rs->buf, "OK") != 0)
5376 error (_("Attaching to %s failed with: %s"),
5377 target_pid_to_str (pid_to_ptid (pid)),
5378 rs->buf);
5379 break;
5380 case PACKET_UNKNOWN:
5381 error (_("This target does not support attaching to a process"));
5382 default:
5383 error (_("Attaching to %s failed"),
5384 target_pid_to_str (pid_to_ptid (pid)));
5385 }
5386
5387 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5388
5389 inferior_ptid = pid_to_ptid (pid);
5390
5391 if (target_is_non_stop_p ())
5392 {
5393 struct thread_info *thread;
5394
5395 /* Get list of threads. */
5396 remote_update_thread_list (target);
5397
5398 thread = first_thread_of_process (pid);
5399 if (thread)
5400 inferior_ptid = thread->ptid;
5401 else
5402 inferior_ptid = pid_to_ptid (pid);
5403
5404 /* Invalidate our notion of the remote current thread. */
5405 record_currthread (rs, minus_one_ptid);
5406 }
5407 else
5408 {
5409 /* Now, if we have thread information, update inferior_ptid. */
5410 inferior_ptid = remote_current_thread (inferior_ptid);
5411
5412 /* Add the main thread to the thread list. */
5413 add_thread_silent (inferior_ptid);
5414 }
5415
5416 /* Next, if the target can specify a description, read it. We do
5417 this before anything involving memory or registers. */
5418 target_find_description ();
5419
5420 if (!target_is_non_stop_p ())
5421 {
5422 /* Use the previously fetched status. */
5423 gdb_assert (wait_status != NULL);
5424
5425 if (target_can_async_p ())
5426 {
5427 struct notif_event *reply
5428 = remote_notif_parse (&notif_client_stop, wait_status);
5429
5430 push_stop_reply ((struct stop_reply *) reply);
5431
5432 target_async (1);
5433 }
5434 else
5435 {
5436 gdb_assert (wait_status != NULL);
5437 strcpy (rs->buf, wait_status);
5438 rs->cached_wait_status = 1;
5439 }
5440 }
5441 else
5442 gdb_assert (wait_status == NULL);
5443}
5444
5445/* Implementation of the to_post_attach method. */
5446
5447static void
5448extended_remote_post_attach (struct target_ops *ops, int pid)
5449{
5450 /* Get text, data & bss offsets. */
5451 get_offsets ();
5452
5453 /* In certain cases GDB might not have had the chance to start
5454 symbol lookup up until now. This could happen if the debugged
5455 binary is not using shared libraries, the vsyscall page is not
5456 present (on Linux) and the binary itself hadn't changed since the
5457 debugging process was started. */
5458 if (symfile_objfile != NULL)
5459 remote_check_symbols();
5460}
5461
5462\f
5463/* Check for the availability of vCont. This function should also check
5464 the response. */
5465
5466static void
5467remote_vcont_probe (struct remote_state *rs)
5468{
5469 char *buf;
5470
5471 strcpy (rs->buf, "vCont?");
5472 putpkt (rs->buf);
5473 getpkt (&rs->buf, &rs->buf_size, 0);
5474 buf = rs->buf;
5475
5476 /* Make sure that the features we assume are supported. */
5477 if (startswith (buf, "vCont"))
5478 {
5479 char *p = &buf[5];
5480 int support_c, support_C;
5481
5482 rs->supports_vCont.s = 0;
5483 rs->supports_vCont.S = 0;
5484 support_c = 0;
5485 support_C = 0;
5486 rs->supports_vCont.t = 0;
5487 rs->supports_vCont.r = 0;
5488 while (p && *p == ';')
5489 {
5490 p++;
5491 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5492 rs->supports_vCont.s = 1;
5493 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5494 rs->supports_vCont.S = 1;
5495 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5496 support_c = 1;
5497 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5498 support_C = 1;
5499 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5500 rs->supports_vCont.t = 1;
5501 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5502 rs->supports_vCont.r = 1;
5503
5504 p = strchr (p, ';');
5505 }
5506
5507 /* If c, and C are not all supported, we can't use vCont. Clearing
5508 BUF will make packet_ok disable the packet. */
5509 if (!support_c || !support_C)
5510 buf[0] = 0;
5511 }
5512
5513 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5514}
5515
5516/* Helper function for building "vCont" resumptions. Write a
5517 resumption to P. ENDP points to one-passed-the-end of the buffer
5518 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5519 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5520 resumed thread should be single-stepped and/or signalled. If PTID
5521 equals minus_one_ptid, then all threads are resumed; if PTID
5522 represents a process, then all threads of the process are resumed;
5523 the thread to be stepped and/or signalled is given in the global
5524 INFERIOR_PTID. */
5525
5526static char *
5527append_resumption (char *p, char *endp,
5528 ptid_t ptid, int step, enum gdb_signal siggnal)
5529{
5530 struct remote_state *rs = get_remote_state ();
5531
5532 if (step && siggnal != GDB_SIGNAL_0)
5533 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5534 else if (step
5535 /* GDB is willing to range step. */
5536 && use_range_stepping
5537 /* Target supports range stepping. */
5538 && rs->supports_vCont.r
5539 /* We don't currently support range stepping multiple
5540 threads with a wildcard (though the protocol allows it,
5541 so stubs shouldn't make an active effort to forbid
5542 it). */
5543 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5544 {
5545 struct thread_info *tp;
5546
5547 if (ptid_equal (ptid, minus_one_ptid))
5548 {
5549 /* If we don't know about the target thread's tid, then
5550 we're resuming magic_null_ptid (see caller). */
5551 tp = find_thread_ptid (magic_null_ptid);
5552 }
5553 else
5554 tp = find_thread_ptid (ptid);
5555 gdb_assert (tp != NULL);
5556
5557 if (tp->control.may_range_step)
5558 {
5559 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5560
5561 p += xsnprintf (p, endp - p, ";r%s,%s",
5562 phex_nz (tp->control.step_range_start,
5563 addr_size),
5564 phex_nz (tp->control.step_range_end,
5565 addr_size));
5566 }
5567 else
5568 p += xsnprintf (p, endp - p, ";s");
5569 }
5570 else if (step)
5571 p += xsnprintf (p, endp - p, ";s");
5572 else if (siggnal != GDB_SIGNAL_0)
5573 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5574 else
5575 p += xsnprintf (p, endp - p, ";c");
5576
5577 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5578 {
5579 ptid_t nptid;
5580
5581 /* All (-1) threads of process. */
5582 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5583
5584 p += xsnprintf (p, endp - p, ":");
5585 p = write_ptid (p, endp, nptid);
5586 }
5587 else if (!ptid_equal (ptid, minus_one_ptid))
5588 {
5589 p += xsnprintf (p, endp - p, ":");
5590 p = write_ptid (p, endp, ptid);
5591 }
5592
5593 return p;
5594}
5595
5596/* Clear the thread's private info on resume. */
5597
5598static void
5599resume_clear_thread_private_info (struct thread_info *thread)
5600{
5601 if (thread->priv != NULL)
5602 {
5603 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5604 thread->priv->watch_data_address = 0;
5605 }
5606}
5607
5608/* Append a vCont continue-with-signal action for threads that have a
5609 non-zero stop signal. */
5610
5611static char *
5612append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5613{
5614 struct thread_info *thread;
5615
5616 ALL_NON_EXITED_THREADS (thread)
5617 if (ptid_match (thread->ptid, ptid)
5618 && !ptid_equal (inferior_ptid, thread->ptid)
5619 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5620 {
5621 p = append_resumption (p, endp, thread->ptid,
5622 0, thread->suspend.stop_signal);
5623 thread->suspend.stop_signal = GDB_SIGNAL_0;
5624 resume_clear_thread_private_info (thread);
5625 }
5626
5627 return p;
5628}
5629
5630/* Set the target running, using the packets that use Hc
5631 (c/s/C/S). */
5632
5633static void
5634remote_resume_with_hc (struct target_ops *ops,
5635 ptid_t ptid, int step, enum gdb_signal siggnal)
5636{
5637 struct remote_state *rs = get_remote_state ();
5638 struct thread_info *thread;
5639 char *buf;
5640
5641 rs->last_sent_signal = siggnal;
5642 rs->last_sent_step = step;
5643
5644 /* The c/s/C/S resume packets use Hc, so set the continue
5645 thread. */
5646 if (ptid_equal (ptid, minus_one_ptid))
5647 set_continue_thread (any_thread_ptid);
5648 else
5649 set_continue_thread (ptid);
5650
5651 ALL_NON_EXITED_THREADS (thread)
5652 resume_clear_thread_private_info (thread);
5653
5654 buf = rs->buf;
5655 if (execution_direction == EXEC_REVERSE)
5656 {
5657 /* We don't pass signals to the target in reverse exec mode. */
5658 if (info_verbose && siggnal != GDB_SIGNAL_0)
5659 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5660 siggnal);
5661
5662 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5663 error (_("Remote reverse-step not supported."));
5664 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5665 error (_("Remote reverse-continue not supported."));
5666
5667 strcpy (buf, step ? "bs" : "bc");
5668 }
5669 else if (siggnal != GDB_SIGNAL_0)
5670 {
5671 buf[0] = step ? 'S' : 'C';
5672 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5673 buf[2] = tohex (((int) siggnal) & 0xf);
5674 buf[3] = '\0';
5675 }
5676 else
5677 strcpy (buf, step ? "s" : "c");
5678
5679 putpkt (buf);
5680}
5681
5682/* Resume the remote inferior by using a "vCont" packet. The thread
5683 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5684 resumed thread should be single-stepped and/or signalled. If PTID
5685 equals minus_one_ptid, then all threads are resumed; the thread to
5686 be stepped and/or signalled is given in the global INFERIOR_PTID.
5687 This function returns non-zero iff it resumes the inferior.
5688
5689 This function issues a strict subset of all possible vCont commands
5690 at the moment. */
5691
5692static int
5693remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5694{
5695 struct remote_state *rs = get_remote_state ();
5696 char *p;
5697 char *endp;
5698
5699 /* No reverse execution actions defined for vCont. */
5700 if (execution_direction == EXEC_REVERSE)
5701 return 0;
5702
5703 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5704 remote_vcont_probe (rs);
5705
5706 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5707 return 0;
5708
5709 p = rs->buf;
5710 endp = rs->buf + get_remote_packet_size ();
5711
5712 /* If we could generate a wider range of packets, we'd have to worry
5713 about overflowing BUF. Should there be a generic
5714 "multi-part-packet" packet? */
5715
5716 p += xsnprintf (p, endp - p, "vCont");
5717
5718 if (ptid_equal (ptid, magic_null_ptid))
5719 {
5720 /* MAGIC_NULL_PTID means that we don't have any active threads,
5721 so we don't have any TID numbers the inferior will
5722 understand. Make sure to only send forms that do not specify
5723 a TID. */
5724 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5725 }
5726 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5727 {
5728 /* Resume all threads (of all processes, or of a single
5729 process), with preference for INFERIOR_PTID. This assumes
5730 inferior_ptid belongs to the set of all threads we are about
5731 to resume. */
5732 if (step || siggnal != GDB_SIGNAL_0)
5733 {
5734 /* Step inferior_ptid, with or without signal. */
5735 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5736 }
5737
5738 /* Also pass down any pending signaled resumption for other
5739 threads not the current. */
5740 p = append_pending_thread_resumptions (p, endp, ptid);
5741
5742 /* And continue others without a signal. */
5743 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5744 }
5745 else
5746 {
5747 /* Scheduler locking; resume only PTID. */
5748 append_resumption (p, endp, ptid, step, siggnal);
5749 }
5750
5751 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5752 putpkt (rs->buf);
5753
5754 if (target_is_non_stop_p ())
5755 {
5756 /* In non-stop, the stub replies to vCont with "OK". The stop
5757 reply will be reported asynchronously by means of a `%Stop'
5758 notification. */
5759 getpkt (&rs->buf, &rs->buf_size, 0);
5760 if (strcmp (rs->buf, "OK") != 0)
5761 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5762 }
5763
5764 return 1;
5765}
5766
5767/* Tell the remote machine to resume. */
5768
5769static void
5770remote_resume (struct target_ops *ops,
5771 ptid_t ptid, int step, enum gdb_signal siggnal)
5772{
5773 struct remote_state *rs = get_remote_state ();
5774
5775 /* When connected in non-stop mode, the core resumes threads
5776 individually. Resuming remote threads directly in target_resume
5777 would thus result in sending one packet per thread. Instead, to
5778 minimize roundtrip latency, here we just store the resume
5779 request; the actual remote resumption will be done in
5780 target_commit_resume / remote_commit_resume, where we'll be able
5781 to do vCont action coalescing. */
5782 if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5783 {
5784 struct private_thread_info *remote_thr;
5785
5786 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5787 remote_thr = get_private_info_ptid (inferior_ptid);
5788 else
5789 remote_thr = get_private_info_ptid (ptid);
5790 remote_thr->last_resume_step = step;
5791 remote_thr->last_resume_sig = siggnal;
5792 return;
5793 }
5794
5795 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5796 (explained in remote-notif.c:handle_notification) so
5797 remote_notif_process is not called. We need find a place where
5798 it is safe to start a 'vNotif' sequence. It is good to do it
5799 before resuming inferior, because inferior was stopped and no RSP
5800 traffic at that moment. */
5801 if (!target_is_non_stop_p ())
5802 remote_notif_process (rs->notif_state, &notif_client_stop);
5803
5804 rs->last_resume_exec_dir = execution_direction;
5805
5806 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
5807 if (!remote_resume_with_vcont (ptid, step, siggnal))
5808 remote_resume_with_hc (ops, ptid, step, siggnal);
5809
5810 /* We are about to start executing the inferior, let's register it
5811 with the event loop. NOTE: this is the one place where all the
5812 execution commands end up. We could alternatively do this in each
5813 of the execution commands in infcmd.c. */
5814 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5815 into infcmd.c in order to allow inferior function calls to work
5816 NOT asynchronously. */
5817 if (target_can_async_p ())
5818 target_async (1);
5819
5820 /* We've just told the target to resume. The remote server will
5821 wait for the inferior to stop, and then send a stop reply. In
5822 the mean time, we can't start another command/query ourselves
5823 because the stub wouldn't be ready to process it. This applies
5824 only to the base all-stop protocol, however. In non-stop (which
5825 only supports vCont), the stub replies with an "OK", and is
5826 immediate able to process further serial input. */
5827 if (!target_is_non_stop_p ())
5828 rs->waiting_for_stop_reply = 1;
5829}
5830
5831static void check_pending_events_prevent_wildcard_vcont
5832 (int *may_global_wildcard_vcont);
5833static int is_pending_fork_parent_thread (struct thread_info *thread);
5834
5835/* Private per-inferior info for target remote processes. */
5836
5837struct private_inferior
5838{
5839 /* Whether we can send a wildcard vCont for this process. */
5840 int may_wildcard_vcont;
5841};
5842
5843/* Structure used to track the construction of a vCont packet in the
5844 outgoing packet buffer. This is used to send multiple vCont
5845 packets if we have more actions than would fit a single packet. */
5846
5847struct vcont_builder
5848{
5849 /* Pointer to the first action. P points here if no action has been
5850 appended yet. */
5851 char *first_action;
5852
5853 /* Where the next action will be appended. */
5854 char *p;
5855
5856 /* The end of the buffer. Must never write past this. */
5857 char *endp;
5858};
5859
5860/* Prepare the outgoing buffer for a new vCont packet. */
5861
5862static void
5863vcont_builder_restart (struct vcont_builder *builder)
5864{
5865 struct remote_state *rs = get_remote_state ();
5866
5867 builder->p = rs->buf;
5868 builder->endp = rs->buf + get_remote_packet_size ();
5869 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5870 builder->first_action = builder->p;
5871}
5872
5873/* If the vCont packet being built has any action, send it to the
5874 remote end. */
5875
5876static void
5877vcont_builder_flush (struct vcont_builder *builder)
5878{
5879 struct remote_state *rs;
5880
5881 if (builder->p == builder->first_action)
5882 return;
5883
5884 rs = get_remote_state ();
5885 putpkt (rs->buf);
5886 getpkt (&rs->buf, &rs->buf_size, 0);
5887 if (strcmp (rs->buf, "OK") != 0)
5888 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5889}
5890
5891/* The largest action is range-stepping, with its two addresses. This
5892 is more than sufficient. If a new, bigger action is created, it'll
5893 quickly trigger a failed assertion in append_resumption (and we'll
5894 just bump this). */
5895#define MAX_ACTION_SIZE 200
5896
5897/* Append a new vCont action in the outgoing packet being built. If
5898 the action doesn't fit the packet along with previous actions, push
5899 what we've got so far to the remote end and start over a new vCont
5900 packet (with the new action). */
5901
5902static void
5903vcont_builder_push_action (struct vcont_builder *builder,
5904 ptid_t ptid, int step, enum gdb_signal siggnal)
5905{
5906 char buf[MAX_ACTION_SIZE + 1];
5907 char *endp;
5908 size_t rsize;
5909
5910 endp = append_resumption (buf, buf + sizeof (buf),
5911 ptid, step, siggnal);
5912
5913 /* Check whether this new action would fit in the vCont packet along
5914 with previous actions. If not, send what we've got so far and
5915 start a new vCont packet. */
5916 rsize = endp - buf;
5917 if (rsize > builder->endp - builder->p)
5918 {
5919 vcont_builder_flush (builder);
5920 vcont_builder_restart (builder);
5921
5922 /* Should now fit. */
5923 gdb_assert (rsize <= builder->endp - builder->p);
5924 }
5925
5926 memcpy (builder->p, buf, rsize);
5927 builder->p += rsize;
5928 *builder->p = '\0';
5929}
5930
5931/* to_commit_resume implementation. */
5932
5933static void
5934remote_commit_resume (struct target_ops *ops)
5935{
5936 struct remote_state *rs = get_remote_state ();
5937 struct inferior *inf;
5938 struct thread_info *tp;
5939 int any_process_wildcard;
5940 int may_global_wildcard_vcont;
5941 struct vcont_builder vcont_builder;
5942
5943 /* If connected in all-stop mode, we'd send the remote resume
5944 request directly from remote_resume. Likewise if
5945 reverse-debugging, as there are no defined vCont actions for
5946 reverse execution. */
5947 if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5948 return;
5949
5950 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5951 instead of resuming all threads of each process individually.
5952 However, if any thread of a process must remain halted, we can't
5953 send wildcard resumes and must send one action per thread.
5954
5955 Care must be taken to not resume threads/processes the server
5956 side already told us are stopped, but the core doesn't know about
5957 yet, because the events are still in the vStopped notification
5958 queue. For example:
5959
5960 #1 => vCont s:p1.1;c
5961 #2 <= OK
5962 #3 <= %Stopped T05 p1.1
5963 #4 => vStopped
5964 #5 <= T05 p1.2
5965 #6 => vStopped
5966 #7 <= OK
5967 #8 (infrun handles the stop for p1.1 and continues stepping)
5968 #9 => vCont s:p1.1;c
5969
5970 The last vCont above would resume thread p1.2 by mistake, because
5971 the server has no idea that the event for p1.2 had not been
5972 handled yet.
5973
5974 The server side must similarly ignore resume actions for the
5975 thread that has a pending %Stopped notification (and any other
5976 threads with events pending), until GDB acks the notification
5977 with vStopped. Otherwise, e.g., the following case is
5978 mishandled:
5979
5980 #1 => g (or any other packet)
5981 #2 <= [registers]
5982 #3 <= %Stopped T05 p1.2
5983 #4 => vCont s:p1.1;c
5984 #5 <= OK
5985
5986 Above, the server must not resume thread p1.2. GDB can't know
5987 that p1.2 stopped until it acks the %Stopped notification, and
5988 since from GDB's perspective all threads should be running, it
5989 sends a "c" action.
5990
5991 Finally, special care must also be given to handling fork/vfork
5992 events. A (v)fork event actually tells us that two processes
5993 stopped -- the parent and the child. Until we follow the fork,
5994 we must not resume the child. Therefore, if we have a pending
5995 fork follow, we must not send a global wildcard resume action
5996 (vCont;c). We can still send process-wide wildcards though. */
5997
5998 /* Start by assuming a global wildcard (vCont;c) is possible. */
5999 may_global_wildcard_vcont = 1;
6000
6001 /* And assume every process is individually wildcard-able too. */
6002 ALL_NON_EXITED_INFERIORS (inf)
6003 {
6004 if (inf->priv == NULL)
6005 inf->priv = XNEW (struct private_inferior);
6006 inf->priv->may_wildcard_vcont = 1;
6007 }
6008
6009 /* Check for any pending events (not reported or processed yet) and
6010 disable process and global wildcard resumes appropriately. */
6011 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6012
6013 ALL_NON_EXITED_THREADS (tp)
6014 {
6015 /* If a thread of a process is not meant to be resumed, then we
6016 can't wildcard that process. */
6017 if (!tp->executing)
6018 {
6019 tp->inf->priv->may_wildcard_vcont = 0;
6020
6021 /* And if we can't wildcard a process, we can't wildcard
6022 everything either. */
6023 may_global_wildcard_vcont = 0;
6024 continue;
6025 }
6026
6027 /* If a thread is the parent of an unfollowed fork, then we
6028 can't do a global wildcard, as that would resume the fork
6029 child. */
6030 if (is_pending_fork_parent_thread (tp))
6031 may_global_wildcard_vcont = 0;
6032 }
6033
6034 /* Now let's build the vCont packet(s). Actions must be appended
6035 from narrower to wider scopes (thread -> process -> global). If
6036 we end up with too many actions for a single packet vcont_builder
6037 flushes the current vCont packet to the remote side and starts a
6038 new one. */
6039 vcont_builder_restart (&vcont_builder);
6040
6041 /* Threads first. */
6042 ALL_NON_EXITED_THREADS (tp)
6043 {
6044 struct private_thread_info *remote_thr = tp->priv;
6045
6046 if (!tp->executing || remote_thr->vcont_resumed)
6047 continue;
6048
6049 gdb_assert (!thread_is_in_step_over_chain (tp));
6050
6051 if (!remote_thr->last_resume_step
6052 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6053 && tp->inf->priv->may_wildcard_vcont)
6054 {
6055 /* We'll send a wildcard resume instead. */
6056 remote_thr->vcont_resumed = 1;
6057 continue;
6058 }
6059
6060 vcont_builder_push_action (&vcont_builder, tp->ptid,
6061 remote_thr->last_resume_step,
6062 remote_thr->last_resume_sig);
6063 remote_thr->vcont_resumed = 1;
6064 }
6065
6066 /* Now check whether we can send any process-wide wildcard. This is
6067 to avoid sending a global wildcard in the case nothing is
6068 supposed to be resumed. */
6069 any_process_wildcard = 0;
6070
6071 ALL_NON_EXITED_INFERIORS (inf)
6072 {
6073 if (inf->priv->may_wildcard_vcont)
6074 {
6075 any_process_wildcard = 1;
6076 break;
6077 }
6078 }
6079
6080 if (any_process_wildcard)
6081 {
6082 /* If all processes are wildcard-able, then send a single "c"
6083 action, otherwise, send an "all (-1) threads of process"
6084 continue action for each running process, if any. */
6085 if (may_global_wildcard_vcont)
6086 {
6087 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6088 0, GDB_SIGNAL_0);
6089 }
6090 else
6091 {
6092 ALL_NON_EXITED_INFERIORS (inf)
6093 {
6094 if (inf->priv->may_wildcard_vcont)
6095 {
6096 vcont_builder_push_action (&vcont_builder,
6097 pid_to_ptid (inf->pid),
6098 0, GDB_SIGNAL_0);
6099 }
6100 }
6101 }
6102 }
6103
6104 vcont_builder_flush (&vcont_builder);
6105}
6106
6107\f
6108
6109/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6110 thread, all threads of a remote process, or all threads of all
6111 processes. */
6112
6113static void
6114remote_stop_ns (ptid_t ptid)
6115{
6116 struct remote_state *rs = get_remote_state ();
6117 char *p = rs->buf;
6118 char *endp = rs->buf + get_remote_packet_size ();
6119
6120 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6121 remote_vcont_probe (rs);
6122
6123 if (!rs->supports_vCont.t)
6124 error (_("Remote server does not support stopping threads"));
6125
6126 if (ptid_equal (ptid, minus_one_ptid)
6127 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6128 p += xsnprintf (p, endp - p, "vCont;t");
6129 else
6130 {
6131 ptid_t nptid;
6132
6133 p += xsnprintf (p, endp - p, "vCont;t:");
6134
6135 if (ptid_is_pid (ptid))
6136 /* All (-1) threads of process. */
6137 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6138 else
6139 {
6140 /* Small optimization: if we already have a stop reply for
6141 this thread, no use in telling the stub we want this
6142 stopped. */
6143 if (peek_stop_reply (ptid))
6144 return;
6145
6146 nptid = ptid;
6147 }
6148
6149 write_ptid (p, endp, nptid);
6150 }
6151
6152 /* In non-stop, we get an immediate OK reply. The stop reply will
6153 come in asynchronously by notification. */
6154 putpkt (rs->buf);
6155 getpkt (&rs->buf, &rs->buf_size, 0);
6156 if (strcmp (rs->buf, "OK") != 0)
6157 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6158}
6159
6160/* All-stop version of target_interrupt. Sends a break or a ^C to
6161 interrupt the remote target. It is undefined which thread of which
6162 process reports the interrupt. */
6163
6164static void
6165remote_interrupt_as (void)
6166{
6167 struct remote_state *rs = get_remote_state ();
6168
6169 rs->ctrlc_pending_p = 1;
6170
6171 /* If the inferior is stopped already, but the core didn't know
6172 about it yet, just ignore the request. The cached wait status
6173 will be collected in remote_wait. */
6174 if (rs->cached_wait_status)
6175 return;
6176
6177 /* Send interrupt_sequence to remote target. */
6178 send_interrupt_sequence ();
6179}
6180
6181/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6182 the remote target. It is undefined which thread of which process
6183 reports the interrupt. Throws an error if the packet is not
6184 supported by the server. */
6185
6186static void
6187remote_interrupt_ns (void)
6188{
6189 struct remote_state *rs = get_remote_state ();
6190 char *p = rs->buf;
6191 char *endp = rs->buf + get_remote_packet_size ();
6192
6193 xsnprintf (p, endp - p, "vCtrlC");
6194
6195 /* In non-stop, we get an immediate OK reply. The stop reply will
6196 come in asynchronously by notification. */
6197 putpkt (rs->buf);
6198 getpkt (&rs->buf, &rs->buf_size, 0);
6199
6200 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6201 {
6202 case PACKET_OK:
6203 break;
6204 case PACKET_UNKNOWN:
6205 error (_("No support for interrupting the remote target."));
6206 case PACKET_ERROR:
6207 error (_("Interrupting target failed: %s"), rs->buf);
6208 }
6209}
6210
6211/* Implement the to_stop function for the remote targets. */
6212
6213static void
6214remote_stop (struct target_ops *self, ptid_t ptid)
6215{
6216 if (remote_debug)
6217 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6218
6219 if (target_is_non_stop_p ())
6220 remote_stop_ns (ptid);
6221 else
6222 {
6223 /* We don't currently have a way to transparently pause the
6224 remote target in all-stop mode. Interrupt it instead. */
6225 remote_interrupt_as ();
6226 }
6227}
6228
6229/* Implement the to_interrupt function for the remote targets. */
6230
6231static void
6232remote_interrupt (struct target_ops *self, ptid_t ptid)
6233{
6234 struct remote_state *rs = get_remote_state ();
6235
6236 if (remote_debug)
6237 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6238
6239 if (target_is_non_stop_p ())
6240 remote_interrupt_ns ();
6241 else
6242 remote_interrupt_as ();
6243}
6244
6245/* Implement the to_pass_ctrlc function for the remote targets. */
6246
6247static void
6248remote_pass_ctrlc (struct target_ops *self)
6249{
6250 struct remote_state *rs = get_remote_state ();
6251
6252 if (remote_debug)
6253 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6254
6255 /* If we're starting up, we're not fully synced yet. Quit
6256 immediately. */
6257 if (rs->starting_up)
6258 quit ();
6259 /* If ^C has already been sent once, offer to disconnect. */
6260 else if (rs->ctrlc_pending_p)
6261 interrupt_query ();
6262 else
6263 target_interrupt (inferior_ptid);
6264}
6265
6266/* Ask the user what to do when an interrupt is received. */
6267
6268static void
6269interrupt_query (void)
6270{
6271 struct remote_state *rs = get_remote_state ();
6272
6273 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6274 {
6275 if (query (_("The target is not responding to interrupt requests.\n"
6276 "Stop debugging it? ")))
6277 {
6278 remote_unpush_target ();
6279 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6280 }
6281 }
6282 else
6283 {
6284 if (query (_("Interrupted while waiting for the program.\n"
6285 "Give up waiting? ")))
6286 quit ();
6287 }
6288}
6289
6290/* Enable/disable target terminal ownership. Most targets can use
6291 terminal groups to control terminal ownership. Remote targets are
6292 different in that explicit transfer of ownership to/from GDB/target
6293 is required. */
6294
6295static void
6296remote_terminal_inferior (struct target_ops *self)
6297{
6298 /* NOTE: At this point we could also register our selves as the
6299 recipient of all input. Any characters typed could then be
6300 passed on down to the target. */
6301}
6302
6303static void
6304remote_terminal_ours (struct target_ops *self)
6305{
6306}
6307
6308static void
6309remote_console_output (char *msg)
6310{
6311 char *p;
6312
6313 for (p = msg; p[0] && p[1]; p += 2)
6314 {
6315 char tb[2];
6316 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6317
6318 tb[0] = c;
6319 tb[1] = 0;
6320 fputs_unfiltered (tb, gdb_stdtarg);
6321 }
6322 gdb_flush (gdb_stdtarg);
6323}
6324
6325DEF_VEC_O(cached_reg_t);
6326
6327typedef struct stop_reply
6328{
6329 struct notif_event base;
6330
6331 /* The identifier of the thread about this event */
6332 ptid_t ptid;
6333
6334 /* The remote state this event is associated with. When the remote
6335 connection, represented by a remote_state object, is closed,
6336 all the associated stop_reply events should be released. */
6337 struct remote_state *rs;
6338
6339 struct target_waitstatus ws;
6340
6341 /* The architecture associated with the expedited registers. */
6342 gdbarch *arch;
6343
6344 /* Expedited registers. This makes remote debugging a bit more
6345 efficient for those targets that provide critical registers as
6346 part of their normal status mechanism (as another roundtrip to
6347 fetch them is avoided). */
6348 VEC(cached_reg_t) *regcache;
6349
6350 enum target_stop_reason stop_reason;
6351
6352 CORE_ADDR watch_data_address;
6353
6354 int core;
6355} *stop_reply_p;
6356
6357DECLARE_QUEUE_P (stop_reply_p);
6358DEFINE_QUEUE_P (stop_reply_p);
6359/* The list of already fetched and acknowledged stop events. This
6360 queue is used for notification Stop, and other notifications
6361 don't need queue for their events, because the notification events
6362 of Stop can't be consumed immediately, so that events should be
6363 queued first, and be consumed by remote_wait_{ns,as} one per
6364 time. Other notifications can consume their events immediately,
6365 so queue is not needed for them. */
6366static QUEUE (stop_reply_p) *stop_reply_queue;
6367
6368static void
6369stop_reply_xfree (struct stop_reply *r)
6370{
6371 notif_event_xfree ((struct notif_event *) r);
6372}
6373
6374/* Return the length of the stop reply queue. */
6375
6376static int
6377stop_reply_queue_length (void)
6378{
6379 return QUEUE_length (stop_reply_p, stop_reply_queue);
6380}
6381
6382static void
6383remote_notif_stop_parse (struct notif_client *self, char *buf,
6384 struct notif_event *event)
6385{
6386 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6387}
6388
6389static void
6390remote_notif_stop_ack (struct notif_client *self, char *buf,
6391 struct notif_event *event)
6392{
6393 struct stop_reply *stop_reply = (struct stop_reply *) event;
6394
6395 /* acknowledge */
6396 putpkt (self->ack_command);
6397
6398 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6399 /* We got an unknown stop reply. */
6400 error (_("Unknown stop reply"));
6401
6402 push_stop_reply (stop_reply);
6403}
6404
6405static int
6406remote_notif_stop_can_get_pending_events (struct notif_client *self)
6407{
6408 /* We can't get pending events in remote_notif_process for
6409 notification stop, and we have to do this in remote_wait_ns
6410 instead. If we fetch all queued events from stub, remote stub
6411 may exit and we have no chance to process them back in
6412 remote_wait_ns. */
6413 mark_async_event_handler (remote_async_inferior_event_token);
6414 return 0;
6415}
6416
6417static void
6418stop_reply_dtr (struct notif_event *event)
6419{
6420 struct stop_reply *r = (struct stop_reply *) event;
6421 cached_reg_t *reg;
6422 int ix;
6423
6424 for (ix = 0;
6425 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6426 ix++)
6427 xfree (reg->data);
6428
6429 VEC_free (cached_reg_t, r->regcache);
6430}
6431
6432static struct notif_event *
6433remote_notif_stop_alloc_reply (void)
6434{
6435 /* We cast to a pointer to the "base class". */
6436 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6437
6438 r->dtr = stop_reply_dtr;
6439
6440 return r;
6441}
6442
6443/* A client of notification Stop. */
6444
6445struct notif_client notif_client_stop =
6446{
6447 "Stop",
6448 "vStopped",
6449 remote_notif_stop_parse,
6450 remote_notif_stop_ack,
6451 remote_notif_stop_can_get_pending_events,
6452 remote_notif_stop_alloc_reply,
6453 REMOTE_NOTIF_STOP,
6454};
6455
6456/* A parameter to pass data in and out. */
6457
6458struct queue_iter_param
6459{
6460 void *input;
6461 struct stop_reply *output;
6462};
6463
6464/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6465 the pid of the process that owns the threads we want to check, or
6466 -1 if we want to check all threads. */
6467
6468static int
6469is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6470 ptid_t thread_ptid)
6471{
6472 if (ws->kind == TARGET_WAITKIND_FORKED
6473 || ws->kind == TARGET_WAITKIND_VFORKED)
6474 {
6475 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6476 return 1;
6477 }
6478
6479 return 0;
6480}
6481
6482/* Return the thread's pending status used to determine whether the
6483 thread is a fork parent stopped at a fork event. */
6484
6485static struct target_waitstatus *
6486thread_pending_fork_status (struct thread_info *thread)
6487{
6488 if (thread->suspend.waitstatus_pending_p)
6489 return &thread->suspend.waitstatus;
6490 else
6491 return &thread->pending_follow;
6492}
6493
6494/* Determine if THREAD is a pending fork parent thread. */
6495
6496static int
6497is_pending_fork_parent_thread (struct thread_info *thread)
6498{
6499 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6500 int pid = -1;
6501
6502 return is_pending_fork_parent (ws, pid, thread->ptid);
6503}
6504
6505/* Check whether EVENT is a fork event, and if it is, remove the
6506 fork child from the context list passed in DATA. */
6507
6508static int
6509remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6510 QUEUE_ITER (stop_reply_p) *iter,
6511 stop_reply_p event,
6512 void *data)
6513{
6514 struct queue_iter_param *param = (struct queue_iter_param *) data;
6515 struct threads_listing_context *context
6516 = (struct threads_listing_context *) param->input;
6517
6518 if (event->ws.kind == TARGET_WAITKIND_FORKED
6519 || event->ws.kind == TARGET_WAITKIND_VFORKED
6520 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6521 threads_listing_context_remove (&event->ws, context);
6522
6523 return 1;
6524}
6525
6526/* If CONTEXT contains any fork child threads that have not been
6527 reported yet, remove them from the CONTEXT list. If such a
6528 thread exists it is because we are stopped at a fork catchpoint
6529 and have not yet called follow_fork, which will set up the
6530 host-side data structures for the new process. */
6531
6532static void
6533remove_new_fork_children (struct threads_listing_context *context)
6534{
6535 struct thread_info * thread;
6536 int pid = -1;
6537 struct notif_client *notif = &notif_client_stop;
6538 struct queue_iter_param param;
6539
6540 /* For any threads stopped at a fork event, remove the corresponding
6541 fork child threads from the CONTEXT list. */
6542 ALL_NON_EXITED_THREADS (thread)
6543 {
6544 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6545
6546 if (is_pending_fork_parent (ws, pid, thread->ptid))
6547 {
6548 threads_listing_context_remove (ws, context);
6549 }
6550 }
6551
6552 /* Check for any pending fork events (not reported or processed yet)
6553 in process PID and remove those fork child threads from the
6554 CONTEXT list as well. */
6555 remote_notif_get_pending_events (notif);
6556 param.input = context;
6557 param.output = NULL;
6558 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6559 remove_child_of_pending_fork, &param);
6560}
6561
6562/* Check whether EVENT would prevent a global or process wildcard
6563 vCont action. */
6564
6565static int
6566check_pending_event_prevents_wildcard_vcont_callback
6567 (QUEUE (stop_reply_p) *q,
6568 QUEUE_ITER (stop_reply_p) *iter,
6569 stop_reply_p event,
6570 void *data)
6571{
6572 struct inferior *inf;
6573 int *may_global_wildcard_vcont = (int *) data;
6574
6575 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6576 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6577 return 1;
6578
6579 if (event->ws.kind == TARGET_WAITKIND_FORKED
6580 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6581 *may_global_wildcard_vcont = 0;
6582
6583 inf = find_inferior_ptid (event->ptid);
6584
6585 /* This may be the first time we heard about this process.
6586 Regardless, we must not do a global wildcard resume, otherwise
6587 we'd resume this process too. */
6588 *may_global_wildcard_vcont = 0;
6589 if (inf != NULL)
6590 inf->priv->may_wildcard_vcont = 0;
6591
6592 return 1;
6593}
6594
6595/* Check whether any event pending in the vStopped queue would prevent
6596 a global or process wildcard vCont action. Clear
6597 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6598 and clear the event inferior's may_wildcard_vcont flag if we can't
6599 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6600
6601static void
6602check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6603{
6604 struct notif_client *notif = &notif_client_stop;
6605
6606 remote_notif_get_pending_events (notif);
6607 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6608 check_pending_event_prevents_wildcard_vcont_callback,
6609 may_global_wildcard);
6610}
6611
6612/* Remove stop replies in the queue if its pid is equal to the given
6613 inferior's pid. */
6614
6615static int
6616remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6617 QUEUE_ITER (stop_reply_p) *iter,
6618 stop_reply_p event,
6619 void *data)
6620{
6621 struct queue_iter_param *param = (struct queue_iter_param *) data;
6622 struct inferior *inf = (struct inferior *) param->input;
6623
6624 if (ptid_get_pid (event->ptid) == inf->pid)
6625 {
6626 stop_reply_xfree (event);
6627 QUEUE_remove_elem (stop_reply_p, q, iter);
6628 }
6629
6630 return 1;
6631}
6632
6633/* Discard all pending stop replies of inferior INF. */
6634
6635static void
6636discard_pending_stop_replies (struct inferior *inf)
6637{
6638 struct queue_iter_param param;
6639 struct stop_reply *reply;
6640 struct remote_state *rs = get_remote_state ();
6641 struct remote_notif_state *rns = rs->notif_state;
6642
6643 /* This function can be notified when an inferior exists. When the
6644 target is not remote, the notification state is NULL. */
6645 if (rs->remote_desc == NULL)
6646 return;
6647
6648 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6649
6650 /* Discard the in-flight notification. */
6651 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6652 {
6653 stop_reply_xfree (reply);
6654 rns->pending_event[notif_client_stop.id] = NULL;
6655 }
6656
6657 param.input = inf;
6658 param.output = NULL;
6659 /* Discard the stop replies we have already pulled with
6660 vStopped. */
6661 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6662 remove_stop_reply_for_inferior, &param);
6663}
6664
6665/* If its remote state is equal to the given remote state,
6666 remove EVENT from the stop reply queue. */
6667
6668static int
6669remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6670 QUEUE_ITER (stop_reply_p) *iter,
6671 stop_reply_p event,
6672 void *data)
6673{
6674 struct queue_iter_param *param = (struct queue_iter_param *) data;
6675 struct remote_state *rs = (struct remote_state *) param->input;
6676
6677 if (event->rs == rs)
6678 {
6679 stop_reply_xfree (event);
6680 QUEUE_remove_elem (stop_reply_p, q, iter);
6681 }
6682
6683 return 1;
6684}
6685
6686/* Discard the stop replies for RS in stop_reply_queue. */
6687
6688static void
6689discard_pending_stop_replies_in_queue (struct remote_state *rs)
6690{
6691 struct queue_iter_param param;
6692
6693 param.input = rs;
6694 param.output = NULL;
6695 /* Discard the stop replies we have already pulled with
6696 vStopped. */
6697 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6698 remove_stop_reply_of_remote_state, &param);
6699}
6700
6701/* A parameter to pass data in and out. */
6702
6703static int
6704remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6705 QUEUE_ITER (stop_reply_p) *iter,
6706 stop_reply_p event,
6707 void *data)
6708{
6709 struct queue_iter_param *param = (struct queue_iter_param *) data;
6710 ptid_t *ptid = (ptid_t *) param->input;
6711
6712 if (ptid_match (event->ptid, *ptid))
6713 {
6714 param->output = event;
6715 QUEUE_remove_elem (stop_reply_p, q, iter);
6716 return 0;
6717 }
6718
6719 return 1;
6720}
6721
6722/* Remove the first reply in 'stop_reply_queue' which matches
6723 PTID. */
6724
6725static struct stop_reply *
6726remote_notif_remove_queued_reply (ptid_t ptid)
6727{
6728 struct queue_iter_param param;
6729
6730 param.input = &ptid;
6731 param.output = NULL;
6732
6733 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6734 remote_notif_remove_once_on_match, &param);
6735 if (notif_debug)
6736 fprintf_unfiltered (gdb_stdlog,
6737 "notif: discard queued event: 'Stop' in %s\n",
6738 target_pid_to_str (ptid));
6739
6740 return param.output;
6741}
6742
6743/* Look for a queued stop reply belonging to PTID. If one is found,
6744 remove it from the queue, and return it. Returns NULL if none is
6745 found. If there are still queued events left to process, tell the
6746 event loop to get back to target_wait soon. */
6747
6748static struct stop_reply *
6749queued_stop_reply (ptid_t ptid)
6750{
6751 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6752
6753 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6754 /* There's still at least an event left. */
6755 mark_async_event_handler (remote_async_inferior_event_token);
6756
6757 return r;
6758}
6759
6760/* Push a fully parsed stop reply in the stop reply queue. Since we
6761 know that we now have at least one queued event left to pass to the
6762 core side, tell the event loop to get back to target_wait soon. */
6763
6764static void
6765push_stop_reply (struct stop_reply *new_event)
6766{
6767 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6768
6769 if (notif_debug)
6770 fprintf_unfiltered (gdb_stdlog,
6771 "notif: push 'Stop' %s to queue %d\n",
6772 target_pid_to_str (new_event->ptid),
6773 QUEUE_length (stop_reply_p,
6774 stop_reply_queue));
6775
6776 mark_async_event_handler (remote_async_inferior_event_token);
6777}
6778
6779static int
6780stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6781 QUEUE_ITER (stop_reply_p) *iter,
6782 struct stop_reply *event,
6783 void *data)
6784{
6785 ptid_t *ptid = (ptid_t *) data;
6786
6787 return !(ptid_equal (*ptid, event->ptid)
6788 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6789}
6790
6791/* Returns true if we have a stop reply for PTID. */
6792
6793static int
6794peek_stop_reply (ptid_t ptid)
6795{
6796 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6797 stop_reply_match_ptid_and_ws, &ptid);
6798}
6799
6800/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6801 starting with P and ending with PEND matches PREFIX. */
6802
6803static int
6804strprefix (const char *p, const char *pend, const char *prefix)
6805{
6806 for ( ; p < pend; p++, prefix++)
6807 if (*p != *prefix)
6808 return 0;
6809 return *prefix == '\0';
6810}
6811
6812/* Parse the stop reply in BUF. Either the function succeeds, and the
6813 result is stored in EVENT, or throws an error. */
6814
6815static void
6816remote_parse_stop_reply (char *buf, struct stop_reply *event)
6817{
6818 remote_arch_state *rsa = NULL;
6819 ULONGEST addr;
6820 const char *p;
6821 int skipregs = 0;
6822
6823 event->ptid = null_ptid;
6824 event->rs = get_remote_state ();
6825 event->ws.kind = TARGET_WAITKIND_IGNORE;
6826 event->ws.value.integer = 0;
6827 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6828 event->regcache = NULL;
6829 event->core = -1;
6830
6831 switch (buf[0])
6832 {
6833 case 'T': /* Status with PC, SP, FP, ... */
6834 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6835 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6836 ss = signal number
6837 n... = register number
6838 r... = register contents
6839 */
6840
6841 p = &buf[3]; /* after Txx */
6842 while (*p)
6843 {
6844 const char *p1;
6845 int fieldsize;
6846
6847 p1 = strchr (p, ':');
6848 if (p1 == NULL)
6849 error (_("Malformed packet(a) (missing colon): %s\n\
6850Packet: '%s'\n"),
6851 p, buf);
6852 if (p == p1)
6853 error (_("Malformed packet(a) (missing register number): %s\n\
6854Packet: '%s'\n"),
6855 p, buf);
6856
6857 /* Some "registers" are actually extended stop information.
6858 Note if you're adding a new entry here: GDB 7.9 and
6859 earlier assume that all register "numbers" that start
6860 with an hex digit are real register numbers. Make sure
6861 the server only sends such a packet if it knows the
6862 client understands it. */
6863
6864 if (strprefix (p, p1, "thread"))
6865 event->ptid = read_ptid (++p1, &p);
6866 else if (strprefix (p, p1, "syscall_entry"))
6867 {
6868 ULONGEST sysno;
6869
6870 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6871 p = unpack_varlen_hex (++p1, &sysno);
6872 event->ws.value.syscall_number = (int) sysno;
6873 }
6874 else if (strprefix (p, p1, "syscall_return"))
6875 {
6876 ULONGEST sysno;
6877
6878 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6879 p = unpack_varlen_hex (++p1, &sysno);
6880 event->ws.value.syscall_number = (int) sysno;
6881 }
6882 else if (strprefix (p, p1, "watch")
6883 || strprefix (p, p1, "rwatch")
6884 || strprefix (p, p1, "awatch"))
6885 {
6886 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6887 p = unpack_varlen_hex (++p1, &addr);
6888 event->watch_data_address = (CORE_ADDR) addr;
6889 }
6890 else if (strprefix (p, p1, "swbreak"))
6891 {
6892 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6893
6894 /* Make sure the stub doesn't forget to indicate support
6895 with qSupported. */
6896 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6897 error (_("Unexpected swbreak stop reason"));
6898
6899 /* The value part is documented as "must be empty",
6900 though we ignore it, in case we ever decide to make
6901 use of it in a backward compatible way. */
6902 p = strchrnul (p1 + 1, ';');
6903 }
6904 else if (strprefix (p, p1, "hwbreak"))
6905 {
6906 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6907
6908 /* Make sure the stub doesn't forget to indicate support
6909 with qSupported. */
6910 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6911 error (_("Unexpected hwbreak stop reason"));
6912
6913 /* See above. */
6914 p = strchrnul (p1 + 1, ';');
6915 }
6916 else if (strprefix (p, p1, "library"))
6917 {
6918 event->ws.kind = TARGET_WAITKIND_LOADED;
6919 p = strchrnul (p1 + 1, ';');
6920 }
6921 else if (strprefix (p, p1, "replaylog"))
6922 {
6923 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6924 /* p1 will indicate "begin" or "end", but it makes
6925 no difference for now, so ignore it. */
6926 p = strchrnul (p1 + 1, ';');
6927 }
6928 else if (strprefix (p, p1, "core"))
6929 {
6930 ULONGEST c;
6931
6932 p = unpack_varlen_hex (++p1, &c);
6933 event->core = c;
6934 }
6935 else if (strprefix (p, p1, "fork"))
6936 {
6937 event->ws.value.related_pid = read_ptid (++p1, &p);
6938 event->ws.kind = TARGET_WAITKIND_FORKED;
6939 }
6940 else if (strprefix (p, p1, "vfork"))
6941 {
6942 event->ws.value.related_pid = read_ptid (++p1, &p);
6943 event->ws.kind = TARGET_WAITKIND_VFORKED;
6944 }
6945 else if (strprefix (p, p1, "vforkdone"))
6946 {
6947 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6948 p = strchrnul (p1 + 1, ';');
6949 }
6950 else if (strprefix (p, p1, "exec"))
6951 {
6952 ULONGEST ignored;
6953 char pathname[PATH_MAX];
6954 int pathlen;
6955
6956 /* Determine the length of the execd pathname. */
6957 p = unpack_varlen_hex (++p1, &ignored);
6958 pathlen = (p - p1) / 2;
6959
6960 /* Save the pathname for event reporting and for
6961 the next run command. */
6962 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6963 pathname[pathlen] = '\0';
6964
6965 /* This is freed during event handling. */
6966 event->ws.value.execd_pathname = xstrdup (pathname);
6967 event->ws.kind = TARGET_WAITKIND_EXECD;
6968
6969 /* Skip the registers included in this packet, since
6970 they may be for an architecture different from the
6971 one used by the original program. */
6972 skipregs = 1;
6973 }
6974 else if (strprefix (p, p1, "create"))
6975 {
6976 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6977 p = strchrnul (p1 + 1, ';');
6978 }
6979 else
6980 {
6981 ULONGEST pnum;
6982 const char *p_temp;
6983
6984 if (skipregs)
6985 {
6986 p = strchrnul (p1 + 1, ';');
6987 p++;
6988 continue;
6989 }
6990
6991 /* Maybe a real ``P'' register number. */
6992 p_temp = unpack_varlen_hex (p, &pnum);
6993 /* If the first invalid character is the colon, we got a
6994 register number. Otherwise, it's an unknown stop
6995 reason. */
6996 if (p_temp == p1)
6997 {
6998 /* If we haven't parsed the event's thread yet, find
6999 it now, in order to find the architecture of the
7000 reported expedited registers. */
7001 if (event->ptid == null_ptid)
7002 {
7003 const char *thr = strstr (p1 + 1, ";thread:");
7004 if (thr != NULL)
7005 event->ptid = read_ptid (thr + strlen (";thread:"),
7006 NULL);
7007 else
7008 event->ptid = magic_null_ptid;
7009 }
7010
7011 if (rsa == NULL)
7012 {
7013 inferior *inf = (event->ptid == null_ptid
7014 ? NULL
7015 : find_inferior_ptid (event->ptid));
7016 /* If this is the first time we learn anything
7017 about this process, skip the registers
7018 included in this packet, since we don't yet
7019 know which architecture to use to parse them.
7020 We'll determine the architecture later when
7021 we process the stop reply and retrieve the
7022 target description, via
7023 remote_notice_new_inferior ->
7024 post_create_inferior. */
7025 if (inf == NULL)
7026 {
7027 p = strchrnul (p1 + 1, ';');
7028 p++;
7029 continue;
7030 }
7031
7032 event->arch = inf->gdbarch;
7033 rsa = get_remote_arch_state (event->arch);
7034 }
7035
7036 packet_reg *reg
7037 = packet_reg_from_pnum (event->arch, rsa, pnum);
7038 cached_reg_t cached_reg;
7039
7040 if (reg == NULL)
7041 error (_("Remote sent bad register number %s: %s\n\
7042Packet: '%s'\n"),
7043 hex_string (pnum), p, buf);
7044
7045 cached_reg.num = reg->regnum;
7046 cached_reg.data = (gdb_byte *)
7047 xmalloc (register_size (event->arch, reg->regnum));
7048
7049 p = p1 + 1;
7050 fieldsize = hex2bin (p, cached_reg.data,
7051 register_size (event->arch, reg->regnum));
7052 p += 2 * fieldsize;
7053 if (fieldsize < register_size (event->arch, reg->regnum))
7054 warning (_("Remote reply is too short: %s"), buf);
7055
7056 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7057 }
7058 else
7059 {
7060 /* Not a number. Silently skip unknown optional
7061 info. */
7062 p = strchrnul (p1 + 1, ';');
7063 }
7064 }
7065
7066 if (*p != ';')
7067 error (_("Remote register badly formatted: %s\nhere: %s"),
7068 buf, p);
7069 ++p;
7070 }
7071
7072 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7073 break;
7074
7075 /* fall through */
7076 case 'S': /* Old style status, just signal only. */
7077 {
7078 int sig;
7079
7080 event->ws.kind = TARGET_WAITKIND_STOPPED;
7081 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7082 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7083 event->ws.value.sig = (enum gdb_signal) sig;
7084 else
7085 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7086 }
7087 break;
7088 case 'w': /* Thread exited. */
7089 {
7090 const char *p;
7091 ULONGEST value;
7092
7093 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7094 p = unpack_varlen_hex (&buf[1], &value);
7095 event->ws.value.integer = value;
7096 if (*p != ';')
7097 error (_("stop reply packet badly formatted: %s"), buf);
7098 event->ptid = read_ptid (++p, NULL);
7099 break;
7100 }
7101 case 'W': /* Target exited. */
7102 case 'X':
7103 {
7104 const char *p;
7105 int pid;
7106 ULONGEST value;
7107
7108 /* GDB used to accept only 2 hex chars here. Stubs should
7109 only send more if they detect GDB supports multi-process
7110 support. */
7111 p = unpack_varlen_hex (&buf[1], &value);
7112
7113 if (buf[0] == 'W')
7114 {
7115 /* The remote process exited. */
7116 event->ws.kind = TARGET_WAITKIND_EXITED;
7117 event->ws.value.integer = value;
7118 }
7119 else
7120 {
7121 /* The remote process exited with a signal. */
7122 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7123 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7124 event->ws.value.sig = (enum gdb_signal) value;
7125 else
7126 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7127 }
7128
7129 /* If no process is specified, assume inferior_ptid. */
7130 pid = ptid_get_pid (inferior_ptid);
7131 if (*p == '\0')
7132 ;
7133 else if (*p == ';')
7134 {
7135 p++;
7136
7137 if (*p == '\0')
7138 ;
7139 else if (startswith (p, "process:"))
7140 {
7141 ULONGEST upid;
7142
7143 p += sizeof ("process:") - 1;
7144 unpack_varlen_hex (p, &upid);
7145 pid = upid;
7146 }
7147 else
7148 error (_("unknown stop reply packet: %s"), buf);
7149 }
7150 else
7151 error (_("unknown stop reply packet: %s"), buf);
7152 event->ptid = pid_to_ptid (pid);
7153 }
7154 break;
7155 case 'N':
7156 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7157 event->ptid = minus_one_ptid;
7158 break;
7159 }
7160
7161 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7162 error (_("No process or thread specified in stop reply: %s"), buf);
7163}
7164
7165/* When the stub wants to tell GDB about a new notification reply, it
7166 sends a notification (%Stop, for example). Those can come it at
7167 any time, hence, we have to make sure that any pending
7168 putpkt/getpkt sequence we're making is finished, before querying
7169 the stub for more events with the corresponding ack command
7170 (vStopped, for example). E.g., if we started a vStopped sequence
7171 immediately upon receiving the notification, something like this
7172 could happen:
7173
7174 1.1) --> Hg 1
7175 1.2) <-- OK
7176 1.3) --> g
7177 1.4) <-- %Stop
7178 1.5) --> vStopped
7179 1.6) <-- (registers reply to step #1.3)
7180
7181 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7182 query.
7183
7184 To solve this, whenever we parse a %Stop notification successfully,
7185 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7186 doing whatever we were doing:
7187
7188 2.1) --> Hg 1
7189 2.2) <-- OK
7190 2.3) --> g
7191 2.4) <-- %Stop
7192 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7193 2.5) <-- (registers reply to step #2.3)
7194
7195 Eventualy after step #2.5, we return to the event loop, which
7196 notices there's an event on the
7197 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7198 associated callback --- the function below. At this point, we're
7199 always safe to start a vStopped sequence. :
7200
7201 2.6) --> vStopped
7202 2.7) <-- T05 thread:2
7203 2.8) --> vStopped
7204 2.9) --> OK
7205*/
7206
7207void
7208remote_notif_get_pending_events (struct notif_client *nc)
7209{
7210 struct remote_state *rs = get_remote_state ();
7211
7212 if (rs->notif_state->pending_event[nc->id] != NULL)
7213 {
7214 if (notif_debug)
7215 fprintf_unfiltered (gdb_stdlog,
7216 "notif: process: '%s' ack pending event\n",
7217 nc->name);
7218
7219 /* acknowledge */
7220 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7221 rs->notif_state->pending_event[nc->id] = NULL;
7222
7223 while (1)
7224 {
7225 getpkt (&rs->buf, &rs->buf_size, 0);
7226 if (strcmp (rs->buf, "OK") == 0)
7227 break;
7228 else
7229 remote_notif_ack (nc, rs->buf);
7230 }
7231 }
7232 else
7233 {
7234 if (notif_debug)
7235 fprintf_unfiltered (gdb_stdlog,
7236 "notif: process: '%s' no pending reply\n",
7237 nc->name);
7238 }
7239}
7240
7241/* Called when it is decided that STOP_REPLY holds the info of the
7242 event that is to be returned to the core. This function always
7243 destroys STOP_REPLY. */
7244
7245static ptid_t
7246process_stop_reply (struct stop_reply *stop_reply,
7247 struct target_waitstatus *status)
7248{
7249 ptid_t ptid;
7250
7251 *status = stop_reply->ws;
7252 ptid = stop_reply->ptid;
7253
7254 /* If no thread/process was reported by the stub, assume the current
7255 inferior. */
7256 if (ptid_equal (ptid, null_ptid))
7257 ptid = inferior_ptid;
7258
7259 if (status->kind != TARGET_WAITKIND_EXITED
7260 && status->kind != TARGET_WAITKIND_SIGNALLED
7261 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7262 {
7263 struct private_thread_info *remote_thr;
7264
7265 /* Expedited registers. */
7266 if (stop_reply->regcache)
7267 {
7268 struct regcache *regcache
7269 = get_thread_arch_regcache (ptid, stop_reply->arch);
7270 cached_reg_t *reg;
7271 int ix;
7272
7273 for (ix = 0;
7274 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7275 ix++)
7276 {
7277 regcache_raw_supply (regcache, reg->num, reg->data);
7278 xfree (reg->data);
7279 }
7280
7281 VEC_free (cached_reg_t, stop_reply->regcache);
7282 }
7283
7284 remote_notice_new_inferior (ptid, 0);
7285 remote_thr = get_private_info_ptid (ptid);
7286 remote_thr->core = stop_reply->core;
7287 remote_thr->stop_reason = stop_reply->stop_reason;
7288 remote_thr->watch_data_address = stop_reply->watch_data_address;
7289 remote_thr->vcont_resumed = 0;
7290 }
7291
7292 stop_reply_xfree (stop_reply);
7293 return ptid;
7294}
7295
7296/* The non-stop mode version of target_wait. */
7297
7298static ptid_t
7299remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7300{
7301 struct remote_state *rs = get_remote_state ();
7302 struct stop_reply *stop_reply;
7303 int ret;
7304 int is_notif = 0;
7305
7306 /* If in non-stop mode, get out of getpkt even if a
7307 notification is received. */
7308
7309 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7310 0 /* forever */, &is_notif);
7311 while (1)
7312 {
7313 if (ret != -1 && !is_notif)
7314 switch (rs->buf[0])
7315 {
7316 case 'E': /* Error of some sort. */
7317 /* We're out of sync with the target now. Did it continue
7318 or not? We can't tell which thread it was in non-stop,
7319 so just ignore this. */
7320 warning (_("Remote failure reply: %s"), rs->buf);
7321 break;
7322 case 'O': /* Console output. */
7323 remote_console_output (rs->buf + 1);
7324 break;
7325 default:
7326 warning (_("Invalid remote reply: %s"), rs->buf);
7327 break;
7328 }
7329
7330 /* Acknowledge a pending stop reply that may have arrived in the
7331 mean time. */
7332 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7333 remote_notif_get_pending_events (&notif_client_stop);
7334
7335 /* If indeed we noticed a stop reply, we're done. */
7336 stop_reply = queued_stop_reply (ptid);
7337 if (stop_reply != NULL)
7338 return process_stop_reply (stop_reply, status);
7339
7340 /* Still no event. If we're just polling for an event, then
7341 return to the event loop. */
7342 if (options & TARGET_WNOHANG)
7343 {
7344 status->kind = TARGET_WAITKIND_IGNORE;
7345 return minus_one_ptid;
7346 }
7347
7348 /* Otherwise do a blocking wait. */
7349 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7350 1 /* forever */, &is_notif);
7351 }
7352}
7353
7354/* Wait until the remote machine stops, then return, storing status in
7355 STATUS just as `wait' would. */
7356
7357static ptid_t
7358remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7359{
7360 struct remote_state *rs = get_remote_state ();
7361 ptid_t event_ptid = null_ptid;
7362 char *buf;
7363 struct stop_reply *stop_reply;
7364
7365 again:
7366
7367 status->kind = TARGET_WAITKIND_IGNORE;
7368 status->value.integer = 0;
7369
7370 stop_reply = queued_stop_reply (ptid);
7371 if (stop_reply != NULL)
7372 return process_stop_reply (stop_reply, status);
7373
7374 if (rs->cached_wait_status)
7375 /* Use the cached wait status, but only once. */
7376 rs->cached_wait_status = 0;
7377 else
7378 {
7379 int ret;
7380 int is_notif;
7381 int forever = ((options & TARGET_WNOHANG) == 0
7382 && wait_forever_enabled_p);
7383
7384 if (!rs->waiting_for_stop_reply)
7385 {
7386 status->kind = TARGET_WAITKIND_NO_RESUMED;
7387 return minus_one_ptid;
7388 }
7389
7390 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7391 _never_ wait for ever -> test on target_is_async_p().
7392 However, before we do that we need to ensure that the caller
7393 knows how to take the target into/out of async mode. */
7394 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7395 forever, &is_notif);
7396
7397 /* GDB gets a notification. Return to core as this event is
7398 not interesting. */
7399 if (ret != -1 && is_notif)
7400 return minus_one_ptid;
7401
7402 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7403 return minus_one_ptid;
7404 }
7405
7406 buf = rs->buf;
7407
7408 /* Assume that the target has acknowledged Ctrl-C unless we receive
7409 an 'F' or 'O' packet. */
7410 if (buf[0] != 'F' && buf[0] != 'O')
7411 rs->ctrlc_pending_p = 0;
7412
7413 switch (buf[0])
7414 {
7415 case 'E': /* Error of some sort. */
7416 /* We're out of sync with the target now. Did it continue or
7417 not? Not is more likely, so report a stop. */
7418 rs->waiting_for_stop_reply = 0;
7419
7420 warning (_("Remote failure reply: %s"), buf);
7421 status->kind = TARGET_WAITKIND_STOPPED;
7422 status->value.sig = GDB_SIGNAL_0;
7423 break;
7424 case 'F': /* File-I/O request. */
7425 /* GDB may access the inferior memory while handling the File-I/O
7426 request, but we don't want GDB accessing memory while waiting
7427 for a stop reply. See the comments in putpkt_binary. Set
7428 waiting_for_stop_reply to 0 temporarily. */
7429 rs->waiting_for_stop_reply = 0;
7430 remote_fileio_request (buf, rs->ctrlc_pending_p);
7431 rs->ctrlc_pending_p = 0;
7432 /* GDB handled the File-I/O request, and the target is running
7433 again. Keep waiting for events. */
7434 rs->waiting_for_stop_reply = 1;
7435 break;
7436 case 'N': case 'T': case 'S': case 'X': case 'W':
7437 {
7438 struct stop_reply *stop_reply;
7439
7440 /* There is a stop reply to handle. */
7441 rs->waiting_for_stop_reply = 0;
7442
7443 stop_reply
7444 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7445 rs->buf);
7446
7447 event_ptid = process_stop_reply (stop_reply, status);
7448 break;
7449 }
7450 case 'O': /* Console output. */
7451 remote_console_output (buf + 1);
7452 break;
7453 case '\0':
7454 if (rs->last_sent_signal != GDB_SIGNAL_0)
7455 {
7456 /* Zero length reply means that we tried 'S' or 'C' and the
7457 remote system doesn't support it. */
7458 target_terminal::ours_for_output ();
7459 printf_filtered
7460 ("Can't send signals to this remote system. %s not sent.\n",
7461 gdb_signal_to_name (rs->last_sent_signal));
7462 rs->last_sent_signal = GDB_SIGNAL_0;
7463 target_terminal::inferior ();
7464
7465 strcpy (buf, rs->last_sent_step ? "s" : "c");
7466 putpkt (buf);
7467 break;
7468 }
7469 /* else fallthrough */
7470 default:
7471 warning (_("Invalid remote reply: %s"), buf);
7472 break;
7473 }
7474
7475 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7476 return minus_one_ptid;
7477 else if (status->kind == TARGET_WAITKIND_IGNORE)
7478 {
7479 /* Nothing interesting happened. If we're doing a non-blocking
7480 poll, we're done. Otherwise, go back to waiting. */
7481 if (options & TARGET_WNOHANG)
7482 return minus_one_ptid;
7483 else
7484 goto again;
7485 }
7486 else if (status->kind != TARGET_WAITKIND_EXITED
7487 && status->kind != TARGET_WAITKIND_SIGNALLED)
7488 {
7489 if (!ptid_equal (event_ptid, null_ptid))
7490 record_currthread (rs, event_ptid);
7491 else
7492 event_ptid = inferior_ptid;
7493 }
7494 else
7495 /* A process exit. Invalidate our notion of current thread. */
7496 record_currthread (rs, minus_one_ptid);
7497
7498 return event_ptid;
7499}
7500
7501/* Wait until the remote machine stops, then return, storing status in
7502 STATUS just as `wait' would. */
7503
7504static ptid_t
7505remote_wait (struct target_ops *ops,
7506 ptid_t ptid, struct target_waitstatus *status, int options)
7507{
7508 ptid_t event_ptid;
7509
7510 if (target_is_non_stop_p ())
7511 event_ptid = remote_wait_ns (ptid, status, options);
7512 else
7513 event_ptid = remote_wait_as (ptid, status, options);
7514
7515 if (target_is_async_p ())
7516 {
7517 /* If there are are events left in the queue tell the event loop
7518 to return here. */
7519 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7520 mark_async_event_handler (remote_async_inferior_event_token);
7521 }
7522
7523 return event_ptid;
7524}
7525
7526/* Fetch a single register using a 'p' packet. */
7527
7528static int
7529fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7530{
7531 struct gdbarch *gdbarch = regcache->arch ();
7532 struct remote_state *rs = get_remote_state ();
7533 char *buf, *p;
7534 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7535 int i;
7536
7537 if (packet_support (PACKET_p) == PACKET_DISABLE)
7538 return 0;
7539
7540 if (reg->pnum == -1)
7541 return 0;
7542
7543 p = rs->buf;
7544 *p++ = 'p';
7545 p += hexnumstr (p, reg->pnum);
7546 *p++ = '\0';
7547 putpkt (rs->buf);
7548 getpkt (&rs->buf, &rs->buf_size, 0);
7549
7550 buf = rs->buf;
7551
7552 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7553 {
7554 case PACKET_OK:
7555 break;
7556 case PACKET_UNKNOWN:
7557 return 0;
7558 case PACKET_ERROR:
7559 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7560 gdbarch_register_name (regcache->arch (),
7561 reg->regnum),
7562 buf);
7563 }
7564
7565 /* If this register is unfetchable, tell the regcache. */
7566 if (buf[0] == 'x')
7567 {
7568 regcache_raw_supply (regcache, reg->regnum, NULL);
7569 return 1;
7570 }
7571
7572 /* Otherwise, parse and supply the value. */
7573 p = buf;
7574 i = 0;
7575 while (p[0] != 0)
7576 {
7577 if (p[1] == 0)
7578 error (_("fetch_register_using_p: early buf termination"));
7579
7580 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7581 p += 2;
7582 }
7583 regcache_raw_supply (regcache, reg->regnum, regp);
7584 return 1;
7585}
7586
7587/* Fetch the registers included in the target's 'g' packet. */
7588
7589static int
7590send_g_packet (void)
7591{
7592 struct remote_state *rs = get_remote_state ();
7593 int buf_len;
7594
7595 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7596 remote_send (&rs->buf, &rs->buf_size);
7597
7598 /* We can get out of synch in various cases. If the first character
7599 in the buffer is not a hex character, assume that has happened
7600 and try to fetch another packet to read. */
7601 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7602 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7603 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7604 && rs->buf[0] != 'x') /* New: unavailable register value. */
7605 {
7606 if (remote_debug)
7607 fprintf_unfiltered (gdb_stdlog,
7608 "Bad register packet; fetching a new packet\n");
7609 getpkt (&rs->buf, &rs->buf_size, 0);
7610 }
7611
7612 buf_len = strlen (rs->buf);
7613
7614 /* Sanity check the received packet. */
7615 if (buf_len % 2 != 0)
7616 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7617
7618 return buf_len / 2;
7619}
7620
7621static void
7622process_g_packet (struct regcache *regcache)
7623{
7624 struct gdbarch *gdbarch = regcache->arch ();
7625 struct remote_state *rs = get_remote_state ();
7626 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7627 int i, buf_len;
7628 char *p;
7629 char *regs;
7630
7631 buf_len = strlen (rs->buf);
7632
7633 /* Further sanity checks, with knowledge of the architecture. */
7634 if (buf_len > 2 * rsa->sizeof_g_packet)
7635 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7636 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7637
7638 /* Save the size of the packet sent to us by the target. It is used
7639 as a heuristic when determining the max size of packets that the
7640 target can safely receive. */
7641 if (rsa->actual_register_packet_size == 0)
7642 rsa->actual_register_packet_size = buf_len;
7643
7644 /* If this is smaller than we guessed the 'g' packet would be,
7645 update our records. A 'g' reply that doesn't include a register's
7646 value implies either that the register is not available, or that
7647 the 'p' packet must be used. */
7648 if (buf_len < 2 * rsa->sizeof_g_packet)
7649 {
7650 long sizeof_g_packet = buf_len / 2;
7651
7652 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7653 {
7654 long offset = rsa->regs[i].offset;
7655 long reg_size = register_size (gdbarch, i);
7656
7657 if (rsa->regs[i].pnum == -1)
7658 continue;
7659
7660 if (offset >= sizeof_g_packet)
7661 rsa->regs[i].in_g_packet = 0;
7662 else if (offset + reg_size > sizeof_g_packet)
7663 error (_("Truncated register %d in remote 'g' packet"), i);
7664 else
7665 rsa->regs[i].in_g_packet = 1;
7666 }
7667
7668 /* Looks valid enough, we can assume this is the correct length
7669 for a 'g' packet. It's important not to adjust
7670 rsa->sizeof_g_packet if we have truncated registers otherwise
7671 this "if" won't be run the next time the method is called
7672 with a packet of the same size and one of the internal errors
7673 below will trigger instead. */
7674 rsa->sizeof_g_packet = sizeof_g_packet;
7675 }
7676
7677 regs = (char *) alloca (rsa->sizeof_g_packet);
7678
7679 /* Unimplemented registers read as all bits zero. */
7680 memset (regs, 0, rsa->sizeof_g_packet);
7681
7682 /* Reply describes registers byte by byte, each byte encoded as two
7683 hex characters. Suck them all up, then supply them to the
7684 register cacheing/storage mechanism. */
7685
7686 p = rs->buf;
7687 for (i = 0; i < rsa->sizeof_g_packet; i++)
7688 {
7689 if (p[0] == 0 || p[1] == 0)
7690 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7691 internal_error (__FILE__, __LINE__,
7692 _("unexpected end of 'g' packet reply"));
7693
7694 if (p[0] == 'x' && p[1] == 'x')
7695 regs[i] = 0; /* 'x' */
7696 else
7697 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7698 p += 2;
7699 }
7700
7701 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7702 {
7703 struct packet_reg *r = &rsa->regs[i];
7704 long reg_size = register_size (gdbarch, i);
7705
7706 if (r->in_g_packet)
7707 {
7708 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7709 /* This shouldn't happen - we adjusted in_g_packet above. */
7710 internal_error (__FILE__, __LINE__,
7711 _("unexpected end of 'g' packet reply"));
7712 else if (rs->buf[r->offset * 2] == 'x')
7713 {
7714 gdb_assert (r->offset * 2 < strlen (rs->buf));
7715 /* The register isn't available, mark it as such (at
7716 the same time setting the value to zero). */
7717 regcache_raw_supply (regcache, r->regnum, NULL);
7718 }
7719 else
7720 regcache_raw_supply (regcache, r->regnum,
7721 regs + r->offset);
7722 }
7723 }
7724}
7725
7726static void
7727fetch_registers_using_g (struct regcache *regcache)
7728{
7729 send_g_packet ();
7730 process_g_packet (regcache);
7731}
7732
7733/* Make the remote selected traceframe match GDB's selected
7734 traceframe. */
7735
7736static void
7737set_remote_traceframe (void)
7738{
7739 int newnum;
7740 struct remote_state *rs = get_remote_state ();
7741
7742 if (rs->remote_traceframe_number == get_traceframe_number ())
7743 return;
7744
7745 /* Avoid recursion, remote_trace_find calls us again. */
7746 rs->remote_traceframe_number = get_traceframe_number ();
7747
7748 newnum = target_trace_find (tfind_number,
7749 get_traceframe_number (), 0, 0, NULL);
7750
7751 /* Should not happen. If it does, all bets are off. */
7752 if (newnum != get_traceframe_number ())
7753 warning (_("could not set remote traceframe"));
7754}
7755
7756static void
7757remote_fetch_registers (struct target_ops *ops,
7758 struct regcache *regcache, int regnum)
7759{
7760 struct gdbarch *gdbarch = regcache->arch ();
7761 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7762 int i;
7763
7764 set_remote_traceframe ();
7765 set_general_thread (regcache_get_ptid (regcache));
7766
7767 if (regnum >= 0)
7768 {
7769 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7770
7771 gdb_assert (reg != NULL);
7772
7773 /* If this register might be in the 'g' packet, try that first -
7774 we are likely to read more than one register. If this is the
7775 first 'g' packet, we might be overly optimistic about its
7776 contents, so fall back to 'p'. */
7777 if (reg->in_g_packet)
7778 {
7779 fetch_registers_using_g (regcache);
7780 if (reg->in_g_packet)
7781 return;
7782 }
7783
7784 if (fetch_register_using_p (regcache, reg))
7785 return;
7786
7787 /* This register is not available. */
7788 regcache_raw_supply (regcache, reg->regnum, NULL);
7789
7790 return;
7791 }
7792
7793 fetch_registers_using_g (regcache);
7794
7795 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7796 if (!rsa->regs[i].in_g_packet)
7797 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7798 {
7799 /* This register is not available. */
7800 regcache_raw_supply (regcache, i, NULL);
7801 }
7802}
7803
7804/* Prepare to store registers. Since we may send them all (using a
7805 'G' request), we have to read out the ones we don't want to change
7806 first. */
7807
7808static void
7809remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7810{
7811 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
7812 int i;
7813
7814 /* Make sure the entire registers array is valid. */
7815 switch (packet_support (PACKET_P))
7816 {
7817 case PACKET_DISABLE:
7818 case PACKET_SUPPORT_UNKNOWN:
7819 /* Make sure all the necessary registers are cached. */
7820 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
7821 if (rsa->regs[i].in_g_packet)
7822 regcache_raw_update (regcache, rsa->regs[i].regnum);
7823 break;
7824 case PACKET_ENABLE:
7825 break;
7826 }
7827}
7828
7829/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7830 packet was not recognized. */
7831
7832static int
7833store_register_using_P (const struct regcache *regcache,
7834 struct packet_reg *reg)
7835{
7836 struct gdbarch *gdbarch = regcache->arch ();
7837 struct remote_state *rs = get_remote_state ();
7838 /* Try storing a single register. */
7839 char *buf = rs->buf;
7840 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7841 char *p;
7842
7843 if (packet_support (PACKET_P) == PACKET_DISABLE)
7844 return 0;
7845
7846 if (reg->pnum == -1)
7847 return 0;
7848
7849 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7850 p = buf + strlen (buf);
7851 regcache_raw_collect (regcache, reg->regnum, regp);
7852 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7853 putpkt (rs->buf);
7854 getpkt (&rs->buf, &rs->buf_size, 0);
7855
7856 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7857 {
7858 case PACKET_OK:
7859 return 1;
7860 case PACKET_ERROR:
7861 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7862 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7863 case PACKET_UNKNOWN:
7864 return 0;
7865 default:
7866 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7867 }
7868}
7869
7870/* Store register REGNUM, or all registers if REGNUM == -1, from the
7871 contents of the register cache buffer. FIXME: ignores errors. */
7872
7873static void
7874store_registers_using_G (const struct regcache *regcache)
7875{
7876 struct remote_state *rs = get_remote_state ();
7877 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
7878 gdb_byte *regs;
7879 char *p;
7880
7881 /* Extract all the registers in the regcache copying them into a
7882 local buffer. */
7883 {
7884 int i;
7885
7886 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7887 memset (regs, 0, rsa->sizeof_g_packet);
7888 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
7889 {
7890 struct packet_reg *r = &rsa->regs[i];
7891
7892 if (r->in_g_packet)
7893 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7894 }
7895 }
7896
7897 /* Command describes registers byte by byte,
7898 each byte encoded as two hex characters. */
7899 p = rs->buf;
7900 *p++ = 'G';
7901 bin2hex (regs, p, rsa->sizeof_g_packet);
7902 putpkt (rs->buf);
7903 getpkt (&rs->buf, &rs->buf_size, 0);
7904 if (packet_check_result (rs->buf) == PACKET_ERROR)
7905 error (_("Could not write registers; remote failure reply '%s'"),
7906 rs->buf);
7907}
7908
7909/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7910 of the register cache buffer. FIXME: ignores errors. */
7911
7912static void
7913remote_store_registers (struct target_ops *ops,
7914 struct regcache *regcache, int regnum)
7915{
7916 struct gdbarch *gdbarch = regcache->arch ();
7917 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7918 int i;
7919
7920 set_remote_traceframe ();
7921 set_general_thread (regcache_get_ptid (regcache));
7922
7923 if (regnum >= 0)
7924 {
7925 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7926
7927 gdb_assert (reg != NULL);
7928
7929 /* Always prefer to store registers using the 'P' packet if
7930 possible; we often change only a small number of registers.
7931 Sometimes we change a larger number; we'd need help from a
7932 higher layer to know to use 'G'. */
7933 if (store_register_using_P (regcache, reg))
7934 return;
7935
7936 /* For now, don't complain if we have no way to write the
7937 register. GDB loses track of unavailable registers too
7938 easily. Some day, this may be an error. We don't have
7939 any way to read the register, either... */
7940 if (!reg->in_g_packet)
7941 return;
7942
7943 store_registers_using_G (regcache);
7944 return;
7945 }
7946
7947 store_registers_using_G (regcache);
7948
7949 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7950 if (!rsa->regs[i].in_g_packet)
7951 if (!store_register_using_P (regcache, &rsa->regs[i]))
7952 /* See above for why we do not issue an error here. */
7953 continue;
7954}
7955\f
7956
7957/* Return the number of hex digits in num. */
7958
7959static int
7960hexnumlen (ULONGEST num)
7961{
7962 int i;
7963
7964 for (i = 0; num != 0; i++)
7965 num >>= 4;
7966
7967 return std::max (i, 1);
7968}
7969
7970/* Set BUF to the minimum number of hex digits representing NUM. */
7971
7972static int
7973hexnumstr (char *buf, ULONGEST num)
7974{
7975 int len = hexnumlen (num);
7976
7977 return hexnumnstr (buf, num, len);
7978}
7979
7980
7981/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7982
7983static int
7984hexnumnstr (char *buf, ULONGEST num, int width)
7985{
7986 int i;
7987
7988 buf[width] = '\0';
7989
7990 for (i = width - 1; i >= 0; i--)
7991 {
7992 buf[i] = "0123456789abcdef"[(num & 0xf)];
7993 num >>= 4;
7994 }
7995
7996 return width;
7997}
7998
7999/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8000
8001static CORE_ADDR
8002remote_address_masked (CORE_ADDR addr)
8003{
8004 unsigned int address_size = remote_address_size;
8005
8006 /* If "remoteaddresssize" was not set, default to target address size. */
8007 if (!address_size)
8008 address_size = gdbarch_addr_bit (target_gdbarch ());
8009
8010 if (address_size > 0
8011 && address_size < (sizeof (ULONGEST) * 8))
8012 {
8013 /* Only create a mask when that mask can safely be constructed
8014 in a ULONGEST variable. */
8015 ULONGEST mask = 1;
8016
8017 mask = (mask << address_size) - 1;
8018 addr &= mask;
8019 }
8020 return addr;
8021}
8022
8023/* Determine whether the remote target supports binary downloading.
8024 This is accomplished by sending a no-op memory write of zero length
8025 to the target at the specified address. It does not suffice to send
8026 the whole packet, since many stubs strip the eighth bit and
8027 subsequently compute a wrong checksum, which causes real havoc with
8028 remote_write_bytes.
8029
8030 NOTE: This can still lose if the serial line is not eight-bit
8031 clean. In cases like this, the user should clear "remote
8032 X-packet". */
8033
8034static void
8035check_binary_download (CORE_ADDR addr)
8036{
8037 struct remote_state *rs = get_remote_state ();
8038
8039 switch (packet_support (PACKET_X))
8040 {
8041 case PACKET_DISABLE:
8042 break;
8043 case PACKET_ENABLE:
8044 break;
8045 case PACKET_SUPPORT_UNKNOWN:
8046 {
8047 char *p;
8048
8049 p = rs->buf;
8050 *p++ = 'X';
8051 p += hexnumstr (p, (ULONGEST) addr);
8052 *p++ = ',';
8053 p += hexnumstr (p, (ULONGEST) 0);
8054 *p++ = ':';
8055 *p = '\0';
8056
8057 putpkt_binary (rs->buf, (int) (p - rs->buf));
8058 getpkt (&rs->buf, &rs->buf_size, 0);
8059
8060 if (rs->buf[0] == '\0')
8061 {
8062 if (remote_debug)
8063 fprintf_unfiltered (gdb_stdlog,
8064 "binary downloading NOT "
8065 "supported by target\n");
8066 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8067 }
8068 else
8069 {
8070 if (remote_debug)
8071 fprintf_unfiltered (gdb_stdlog,
8072 "binary downloading supported by target\n");
8073 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8074 }
8075 break;
8076 }
8077 }
8078}
8079
8080/* Helper function to resize the payload in order to try to get a good
8081 alignment. We try to write an amount of data such that the next write will
8082 start on an address aligned on REMOTE_ALIGN_WRITES. */
8083
8084static int
8085align_for_efficient_write (int todo, CORE_ADDR memaddr)
8086{
8087 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8088}
8089
8090/* Write memory data directly to the remote machine.
8091 This does not inform the data cache; the data cache uses this.
8092 HEADER is the starting part of the packet.
8093 MEMADDR is the address in the remote memory space.
8094 MYADDR is the address of the buffer in our space.
8095 LEN_UNITS is the number of addressable units to write.
8096 UNIT_SIZE is the length in bytes of an addressable unit.
8097 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8098 should send data as binary ('X'), or hex-encoded ('M').
8099
8100 The function creates packet of the form
8101 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8102
8103 where encoding of <DATA> is terminated by PACKET_FORMAT.
8104
8105 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8106 are omitted.
8107
8108 Return the transferred status, error or OK (an
8109 'enum target_xfer_status' value). Save the number of addressable units
8110 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8111
8112 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8113 exchange between gdb and the stub could look like (?? in place of the
8114 checksum):
8115
8116 -> $m1000,4#??
8117 <- aaaabbbbccccdddd
8118
8119 -> $M1000,3:eeeeffffeeee#??
8120 <- OK
8121
8122 -> $m1000,4#??
8123 <- eeeeffffeeeedddd */
8124
8125static enum target_xfer_status
8126remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8127 const gdb_byte *myaddr, ULONGEST len_units,
8128 int unit_size, ULONGEST *xfered_len_units,
8129 char packet_format, int use_length)
8130{
8131 struct remote_state *rs = get_remote_state ();
8132 char *p;
8133 char *plen = NULL;
8134 int plenlen = 0;
8135 int todo_units;
8136 int units_written;
8137 int payload_capacity_bytes;
8138 int payload_length_bytes;
8139
8140 if (packet_format != 'X' && packet_format != 'M')
8141 internal_error (__FILE__, __LINE__,
8142 _("remote_write_bytes_aux: bad packet format"));
8143
8144 if (len_units == 0)
8145 return TARGET_XFER_EOF;
8146
8147 payload_capacity_bytes = get_memory_write_packet_size ();
8148
8149 /* The packet buffer will be large enough for the payload;
8150 get_memory_packet_size ensures this. */
8151 rs->buf[0] = '\0';
8152
8153 /* Compute the size of the actual payload by subtracting out the
8154 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8155
8156 payload_capacity_bytes -= strlen ("$,:#NN");
8157 if (!use_length)
8158 /* The comma won't be used. */
8159 payload_capacity_bytes += 1;
8160 payload_capacity_bytes -= strlen (header);
8161 payload_capacity_bytes -= hexnumlen (memaddr);
8162
8163 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8164
8165 strcat (rs->buf, header);
8166 p = rs->buf + strlen (header);
8167
8168 /* Compute a best guess of the number of bytes actually transfered. */
8169 if (packet_format == 'X')
8170 {
8171 /* Best guess at number of bytes that will fit. */
8172 todo_units = std::min (len_units,
8173 (ULONGEST) payload_capacity_bytes / unit_size);
8174 if (use_length)
8175 payload_capacity_bytes -= hexnumlen (todo_units);
8176 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8177 }
8178 else
8179 {
8180 /* Number of bytes that will fit. */
8181 todo_units
8182 = std::min (len_units,
8183 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8184 if (use_length)
8185 payload_capacity_bytes -= hexnumlen (todo_units);
8186 todo_units = std::min (todo_units,
8187 (payload_capacity_bytes / unit_size) / 2);
8188 }
8189
8190 if (todo_units <= 0)
8191 internal_error (__FILE__, __LINE__,
8192 _("minimum packet size too small to write data"));
8193
8194 /* If we already need another packet, then try to align the end
8195 of this packet to a useful boundary. */
8196 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8197 todo_units = align_for_efficient_write (todo_units, memaddr);
8198
8199 /* Append "<memaddr>". */
8200 memaddr = remote_address_masked (memaddr);
8201 p += hexnumstr (p, (ULONGEST) memaddr);
8202
8203 if (use_length)
8204 {
8205 /* Append ",". */
8206 *p++ = ',';
8207
8208 /* Append the length and retain its location and size. It may need to be
8209 adjusted once the packet body has been created. */
8210 plen = p;
8211 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8212 p += plenlen;
8213 }
8214
8215 /* Append ":". */
8216 *p++ = ':';
8217 *p = '\0';
8218
8219 /* Append the packet body. */
8220 if (packet_format == 'X')
8221 {
8222 /* Binary mode. Send target system values byte by byte, in
8223 increasing byte addresses. Only escape certain critical
8224 characters. */
8225 payload_length_bytes =
8226 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8227 &units_written, payload_capacity_bytes);
8228
8229 /* If not all TODO units fit, then we'll need another packet. Make
8230 a second try to keep the end of the packet aligned. Don't do
8231 this if the packet is tiny. */
8232 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8233 {
8234 int new_todo_units;
8235
8236 new_todo_units = align_for_efficient_write (units_written, memaddr);
8237
8238 if (new_todo_units != units_written)
8239 payload_length_bytes =
8240 remote_escape_output (myaddr, new_todo_units, unit_size,
8241 (gdb_byte *) p, &units_written,
8242 payload_capacity_bytes);
8243 }
8244
8245 p += payload_length_bytes;
8246 if (use_length && units_written < todo_units)
8247 {
8248 /* Escape chars have filled up the buffer prematurely,
8249 and we have actually sent fewer units than planned.
8250 Fix-up the length field of the packet. Use the same
8251 number of characters as before. */
8252 plen += hexnumnstr (plen, (ULONGEST) units_written,
8253 plenlen);
8254 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8255 }
8256 }
8257 else
8258 {
8259 /* Normal mode: Send target system values byte by byte, in
8260 increasing byte addresses. Each byte is encoded as a two hex
8261 value. */
8262 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8263 units_written = todo_units;
8264 }
8265
8266 putpkt_binary (rs->buf, (int) (p - rs->buf));
8267 getpkt (&rs->buf, &rs->buf_size, 0);
8268
8269 if (rs->buf[0] == 'E')
8270 return TARGET_XFER_E_IO;
8271
8272 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8273 send fewer units than we'd planned. */
8274 *xfered_len_units = (ULONGEST) units_written;
8275 return TARGET_XFER_OK;
8276}
8277
8278/* Write memory data directly to the remote machine.
8279 This does not inform the data cache; the data cache uses this.
8280 MEMADDR is the address in the remote memory space.
8281 MYADDR is the address of the buffer in our space.
8282 LEN is the number of bytes.
8283
8284 Return the transferred status, error or OK (an
8285 'enum target_xfer_status' value). Save the number of bytes
8286 transferred in *XFERED_LEN. Only transfer a single packet. */
8287
8288static enum target_xfer_status
8289remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8290 int unit_size, ULONGEST *xfered_len)
8291{
8292 const char *packet_format = NULL;
8293
8294 /* Check whether the target supports binary download. */
8295 check_binary_download (memaddr);
8296
8297 switch (packet_support (PACKET_X))
8298 {
8299 case PACKET_ENABLE:
8300 packet_format = "X";
8301 break;
8302 case PACKET_DISABLE:
8303 packet_format = "M";
8304 break;
8305 case PACKET_SUPPORT_UNKNOWN:
8306 internal_error (__FILE__, __LINE__,
8307 _("remote_write_bytes: bad internal state"));
8308 default:
8309 internal_error (__FILE__, __LINE__, _("bad switch"));
8310 }
8311
8312 return remote_write_bytes_aux (packet_format,
8313 memaddr, myaddr, len, unit_size, xfered_len,
8314 packet_format[0], 1);
8315}
8316
8317/* Read memory data directly from the remote machine.
8318 This does not use the data cache; the data cache uses this.
8319 MEMADDR is the address in the remote memory space.
8320 MYADDR is the address of the buffer in our space.
8321 LEN_UNITS is the number of addressable memory units to read..
8322 UNIT_SIZE is the length in bytes of an addressable unit.
8323
8324 Return the transferred status, error or OK (an
8325 'enum target_xfer_status' value). Save the number of bytes
8326 transferred in *XFERED_LEN_UNITS.
8327
8328 See the comment of remote_write_bytes_aux for an example of
8329 memory read/write exchange between gdb and the stub. */
8330
8331static enum target_xfer_status
8332remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8333 int unit_size, ULONGEST *xfered_len_units)
8334{
8335 struct remote_state *rs = get_remote_state ();
8336 int buf_size_bytes; /* Max size of packet output buffer. */
8337 char *p;
8338 int todo_units;
8339 int decoded_bytes;
8340
8341 buf_size_bytes = get_memory_read_packet_size ();
8342 /* The packet buffer will be large enough for the payload;
8343 get_memory_packet_size ensures this. */
8344
8345 /* Number of units that will fit. */
8346 todo_units = std::min (len_units,
8347 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8348
8349 /* Construct "m"<memaddr>","<len>". */
8350 memaddr = remote_address_masked (memaddr);
8351 p = rs->buf;
8352 *p++ = 'm';
8353 p += hexnumstr (p, (ULONGEST) memaddr);
8354 *p++ = ',';
8355 p += hexnumstr (p, (ULONGEST) todo_units);
8356 *p = '\0';
8357 putpkt (rs->buf);
8358 getpkt (&rs->buf, &rs->buf_size, 0);
8359 if (rs->buf[0] == 'E'
8360 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8361 && rs->buf[3] == '\0')
8362 return TARGET_XFER_E_IO;
8363 /* Reply describes memory byte by byte, each byte encoded as two hex
8364 characters. */
8365 p = rs->buf;
8366 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8367 /* Return what we have. Let higher layers handle partial reads. */
8368 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8369 return TARGET_XFER_OK;
8370}
8371
8372/* Using the set of read-only target sections of remote, read live
8373 read-only memory.
8374
8375 For interface/parameters/return description see target.h,
8376 to_xfer_partial. */
8377
8378static enum target_xfer_status
8379remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8380 ULONGEST memaddr, ULONGEST len,
8381 int unit_size, ULONGEST *xfered_len)
8382{
8383 struct target_section *secp;
8384 struct target_section_table *table;
8385
8386 secp = target_section_by_addr (ops, memaddr);
8387 if (secp != NULL
8388 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8389 secp->the_bfd_section)
8390 & SEC_READONLY))
8391 {
8392 struct target_section *p;
8393 ULONGEST memend = memaddr + len;
8394
8395 table = target_get_section_table (ops);
8396
8397 for (p = table->sections; p < table->sections_end; p++)
8398 {
8399 if (memaddr >= p->addr)
8400 {
8401 if (memend <= p->endaddr)
8402 {
8403 /* Entire transfer is within this section. */
8404 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8405 xfered_len);
8406 }
8407 else if (memaddr >= p->endaddr)
8408 {
8409 /* This section ends before the transfer starts. */
8410 continue;
8411 }
8412 else
8413 {
8414 /* This section overlaps the transfer. Just do half. */
8415 len = p->endaddr - memaddr;
8416 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8417 xfered_len);
8418 }
8419 }
8420 }
8421 }
8422
8423 return TARGET_XFER_EOF;
8424}
8425
8426/* Similar to remote_read_bytes_1, but it reads from the remote stub
8427 first if the requested memory is unavailable in traceframe.
8428 Otherwise, fall back to remote_read_bytes_1. */
8429
8430static enum target_xfer_status
8431remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8432 gdb_byte *myaddr, ULONGEST len, int unit_size,
8433 ULONGEST *xfered_len)
8434{
8435 if (len == 0)
8436 return TARGET_XFER_EOF;
8437
8438 if (get_traceframe_number () != -1)
8439 {
8440 std::vector<mem_range> available;
8441
8442 /* If we fail to get the set of available memory, then the
8443 target does not support querying traceframe info, and so we
8444 attempt reading from the traceframe anyway (assuming the
8445 target implements the old QTro packet then). */
8446 if (traceframe_available_memory (&available, memaddr, len))
8447 {
8448 if (available.empty () || available[0].start != memaddr)
8449 {
8450 enum target_xfer_status res;
8451
8452 /* Don't read into the traceframe's available
8453 memory. */
8454 if (!available.empty ())
8455 {
8456 LONGEST oldlen = len;
8457
8458 len = available[0].start - memaddr;
8459 gdb_assert (len <= oldlen);
8460 }
8461
8462 /* This goes through the topmost target again. */
8463 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8464 len, unit_size, xfered_len);
8465 if (res == TARGET_XFER_OK)
8466 return TARGET_XFER_OK;
8467 else
8468 {
8469 /* No use trying further, we know some memory starting
8470 at MEMADDR isn't available. */
8471 *xfered_len = len;
8472 return TARGET_XFER_UNAVAILABLE;
8473 }
8474 }
8475
8476 /* Don't try to read more than how much is available, in
8477 case the target implements the deprecated QTro packet to
8478 cater for older GDBs (the target's knowledge of read-only
8479 sections may be outdated by now). */
8480 len = available[0].length;
8481 }
8482 }
8483
8484 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8485}
8486
8487\f
8488
8489/* Sends a packet with content determined by the printf format string
8490 FORMAT and the remaining arguments, then gets the reply. Returns
8491 whether the packet was a success, a failure, or unknown. */
8492
8493static enum packet_result remote_send_printf (const char *format, ...)
8494 ATTRIBUTE_PRINTF (1, 2);
8495
8496static enum packet_result
8497remote_send_printf (const char *format, ...)
8498{
8499 struct remote_state *rs = get_remote_state ();
8500 int max_size = get_remote_packet_size ();
8501 va_list ap;
8502
8503 va_start (ap, format);
8504
8505 rs->buf[0] = '\0';
8506 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8507 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8508
8509 if (putpkt (rs->buf) < 0)
8510 error (_("Communication problem with target."));
8511
8512 rs->buf[0] = '\0';
8513 getpkt (&rs->buf, &rs->buf_size, 0);
8514
8515 return packet_check_result (rs->buf);
8516}
8517
8518/* Flash writing can take quite some time. We'll set
8519 effectively infinite timeout for flash operations.
8520 In future, we'll need to decide on a better approach. */
8521static const int remote_flash_timeout = 1000;
8522
8523static void
8524remote_flash_erase (struct target_ops *ops,
8525 ULONGEST address, LONGEST length)
8526{
8527 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8528 enum packet_result ret;
8529 scoped_restore restore_timeout
8530 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8531
8532 ret = remote_send_printf ("vFlashErase:%s,%s",
8533 phex (address, addr_size),
8534 phex (length, 4));
8535 switch (ret)
8536 {
8537 case PACKET_UNKNOWN:
8538 error (_("Remote target does not support flash erase"));
8539 case PACKET_ERROR:
8540 error (_("Error erasing flash with vFlashErase packet"));
8541 default:
8542 break;
8543 }
8544}
8545
8546static enum target_xfer_status
8547remote_flash_write (struct target_ops *ops, ULONGEST address,
8548 ULONGEST length, ULONGEST *xfered_len,
8549 const gdb_byte *data)
8550{
8551 scoped_restore restore_timeout
8552 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8553 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8554 xfered_len,'X', 0);
8555}
8556
8557static void
8558remote_flash_done (struct target_ops *ops)
8559{
8560 int ret;
8561
8562 scoped_restore restore_timeout
8563 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8564
8565 ret = remote_send_printf ("vFlashDone");
8566
8567 switch (ret)
8568 {
8569 case PACKET_UNKNOWN:
8570 error (_("Remote target does not support vFlashDone"));
8571 case PACKET_ERROR:
8572 error (_("Error finishing flash operation"));
8573 default:
8574 break;
8575 }
8576}
8577
8578static void
8579remote_files_info (struct target_ops *ignore)
8580{
8581 puts_filtered ("Debugging a target over a serial line.\n");
8582}
8583\f
8584/* Stuff for dealing with the packets which are part of this protocol.
8585 See comment at top of file for details. */
8586
8587/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8588 error to higher layers. Called when a serial error is detected.
8589 The exception message is STRING, followed by a colon and a blank,
8590 the system error message for errno at function entry and final dot
8591 for output compatibility with throw_perror_with_name. */
8592
8593static void
8594unpush_and_perror (const char *string)
8595{
8596 int saved_errno = errno;
8597
8598 remote_unpush_target ();
8599 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8600 safe_strerror (saved_errno));
8601}
8602
8603/* Read a single character from the remote end. The current quit
8604 handler is overridden to avoid quitting in the middle of packet
8605 sequence, as that would break communication with the remote server.
8606 See remote_serial_quit_handler for more detail. */
8607
8608static int
8609readchar (int timeout)
8610{
8611 int ch;
8612 struct remote_state *rs = get_remote_state ();
8613
8614 {
8615 scoped_restore restore_quit
8616 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8617
8618 rs->got_ctrlc_during_io = 0;
8619
8620 ch = serial_readchar (rs->remote_desc, timeout);
8621
8622 if (rs->got_ctrlc_during_io)
8623 set_quit_flag ();
8624 }
8625
8626 if (ch >= 0)
8627 return ch;
8628
8629 switch ((enum serial_rc) ch)
8630 {
8631 case SERIAL_EOF:
8632 remote_unpush_target ();
8633 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8634 /* no return */
8635 case SERIAL_ERROR:
8636 unpush_and_perror (_("Remote communication error. "
8637 "Target disconnected."));
8638 /* no return */
8639 case SERIAL_TIMEOUT:
8640 break;
8641 }
8642 return ch;
8643}
8644
8645/* Wrapper for serial_write that closes the target and throws if
8646 writing fails. The current quit handler is overridden to avoid
8647 quitting in the middle of packet sequence, as that would break
8648 communication with the remote server. See
8649 remote_serial_quit_handler for more detail. */
8650
8651static void
8652remote_serial_write (const char *str, int len)
8653{
8654 struct remote_state *rs = get_remote_state ();
8655
8656 scoped_restore restore_quit
8657 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8658
8659 rs->got_ctrlc_during_io = 0;
8660
8661 if (serial_write (rs->remote_desc, str, len))
8662 {
8663 unpush_and_perror (_("Remote communication error. "
8664 "Target disconnected."));
8665 }
8666
8667 if (rs->got_ctrlc_during_io)
8668 set_quit_flag ();
8669}
8670
8671/* Send the command in *BUF to the remote machine, and read the reply
8672 into *BUF. Report an error if we get an error reply. Resize
8673 *BUF using xrealloc if necessary to hold the result, and update
8674 *SIZEOF_BUF. */
8675
8676static void
8677remote_send (char **buf,
8678 long *sizeof_buf)
8679{
8680 putpkt (*buf);
8681 getpkt (buf, sizeof_buf, 0);
8682
8683 if ((*buf)[0] == 'E')
8684 error (_("Remote failure reply: %s"), *buf);
8685}
8686
8687/* Return a string representing an escaped version of BUF, of len N.
8688 E.g. \n is converted to \\n, \t to \\t, etc. */
8689
8690static std::string
8691escape_buffer (const char *buf, int n)
8692{
8693 string_file stb;
8694
8695 stb.putstrn (buf, n, '\\');
8696 return std::move (stb.string ());
8697}
8698
8699/* Display a null-terminated packet on stdout, for debugging, using C
8700 string notation. */
8701
8702static void
8703print_packet (const char *buf)
8704{
8705 puts_filtered ("\"");
8706 fputstr_filtered (buf, '"', gdb_stdout);
8707 puts_filtered ("\"");
8708}
8709
8710int
8711putpkt (const char *buf)
8712{
8713 return putpkt_binary (buf, strlen (buf));
8714}
8715
8716/* Send a packet to the remote machine, with error checking. The data
8717 of the packet is in BUF. The string in BUF can be at most
8718 get_remote_packet_size () - 5 to account for the $, # and checksum,
8719 and for a possible /0 if we are debugging (remote_debug) and want
8720 to print the sent packet as a string. */
8721
8722static int
8723putpkt_binary (const char *buf, int cnt)
8724{
8725 struct remote_state *rs = get_remote_state ();
8726 int i;
8727 unsigned char csum = 0;
8728 gdb::def_vector<char> data (cnt + 6);
8729 char *buf2 = data.data ();
8730
8731 int ch;
8732 int tcount = 0;
8733 char *p;
8734
8735 /* Catch cases like trying to read memory or listing threads while
8736 we're waiting for a stop reply. The remote server wouldn't be
8737 ready to handle this request, so we'd hang and timeout. We don't
8738 have to worry about this in synchronous mode, because in that
8739 case it's not possible to issue a command while the target is
8740 running. This is not a problem in non-stop mode, because in that
8741 case, the stub is always ready to process serial input. */
8742 if (!target_is_non_stop_p ()
8743 && target_is_async_p ()
8744 && rs->waiting_for_stop_reply)
8745 {
8746 error (_("Cannot execute this command while the target is running.\n"
8747 "Use the \"interrupt\" command to stop the target\n"
8748 "and then try again."));
8749 }
8750
8751 /* We're sending out a new packet. Make sure we don't look at a
8752 stale cached response. */
8753 rs->cached_wait_status = 0;
8754
8755 /* Copy the packet into buffer BUF2, encapsulating it
8756 and giving it a checksum. */
8757
8758 p = buf2;
8759 *p++ = '$';
8760
8761 for (i = 0; i < cnt; i++)
8762 {
8763 csum += buf[i];
8764 *p++ = buf[i];
8765 }
8766 *p++ = '#';
8767 *p++ = tohex ((csum >> 4) & 0xf);
8768 *p++ = tohex (csum & 0xf);
8769
8770 /* Send it over and over until we get a positive ack. */
8771
8772 while (1)
8773 {
8774 int started_error_output = 0;
8775
8776 if (remote_debug)
8777 {
8778 *p = '\0';
8779
8780 int len = (int) (p - buf2);
8781
8782 std::string str
8783 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8784
8785 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8786
8787 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
8788 {
8789 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
8790 str.length () - REMOTE_DEBUG_MAX_CHAR);
8791 }
8792
8793 fprintf_unfiltered (gdb_stdlog, "...");
8794
8795 gdb_flush (gdb_stdlog);
8796 }
8797 remote_serial_write (buf2, p - buf2);
8798
8799 /* If this is a no acks version of the remote protocol, send the
8800 packet and move on. */
8801 if (rs->noack_mode)
8802 break;
8803
8804 /* Read until either a timeout occurs (-2) or '+' is read.
8805 Handle any notification that arrives in the mean time. */
8806 while (1)
8807 {
8808 ch = readchar (remote_timeout);
8809
8810 if (remote_debug)
8811 {
8812 switch (ch)
8813 {
8814 case '+':
8815 case '-':
8816 case SERIAL_TIMEOUT:
8817 case '$':
8818 case '%':
8819 if (started_error_output)
8820 {
8821 putchar_unfiltered ('\n');
8822 started_error_output = 0;
8823 }
8824 }
8825 }
8826
8827 switch (ch)
8828 {
8829 case '+':
8830 if (remote_debug)
8831 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8832 return 1;
8833 case '-':
8834 if (remote_debug)
8835 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8836 /* FALLTHROUGH */
8837 case SERIAL_TIMEOUT:
8838 tcount++;
8839 if (tcount > 3)
8840 return 0;
8841 break; /* Retransmit buffer. */
8842 case '$':
8843 {
8844 if (remote_debug)
8845 fprintf_unfiltered (gdb_stdlog,
8846 "Packet instead of Ack, ignoring it\n");
8847 /* It's probably an old response sent because an ACK
8848 was lost. Gobble up the packet and ack it so it
8849 doesn't get retransmitted when we resend this
8850 packet. */
8851 skip_frame ();
8852 remote_serial_write ("+", 1);
8853 continue; /* Now, go look for +. */
8854 }
8855
8856 case '%':
8857 {
8858 int val;
8859
8860 /* If we got a notification, handle it, and go back to looking
8861 for an ack. */
8862 /* We've found the start of a notification. Now
8863 collect the data. */
8864 val = read_frame (&rs->buf, &rs->buf_size);
8865 if (val >= 0)
8866 {
8867 if (remote_debug)
8868 {
8869 std::string str = escape_buffer (rs->buf, val);
8870
8871 fprintf_unfiltered (gdb_stdlog,
8872 " Notification received: %s\n",
8873 str.c_str ());
8874 }
8875 handle_notification (rs->notif_state, rs->buf);
8876 /* We're in sync now, rewait for the ack. */
8877 tcount = 0;
8878 }
8879 else
8880 {
8881 if (remote_debug)
8882 {
8883 if (!started_error_output)
8884 {
8885 started_error_output = 1;
8886 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8887 }
8888 fputc_unfiltered (ch & 0177, gdb_stdlog);
8889 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8890 }
8891 }
8892 continue;
8893 }
8894 /* fall-through */
8895 default:
8896 if (remote_debug)
8897 {
8898 if (!started_error_output)
8899 {
8900 started_error_output = 1;
8901 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8902 }
8903 fputc_unfiltered (ch & 0177, gdb_stdlog);
8904 }
8905 continue;
8906 }
8907 break; /* Here to retransmit. */
8908 }
8909
8910#if 0
8911 /* This is wrong. If doing a long backtrace, the user should be
8912 able to get out next time we call QUIT, without anything as
8913 violent as interrupt_query. If we want to provide a way out of
8914 here without getting to the next QUIT, it should be based on
8915 hitting ^C twice as in remote_wait. */
8916 if (quit_flag)
8917 {
8918 quit_flag = 0;
8919 interrupt_query ();
8920 }
8921#endif
8922 }
8923
8924 return 0;
8925}
8926
8927/* Come here after finding the start of a frame when we expected an
8928 ack. Do our best to discard the rest of this packet. */
8929
8930static void
8931skip_frame (void)
8932{
8933 int c;
8934
8935 while (1)
8936 {
8937 c = readchar (remote_timeout);
8938 switch (c)
8939 {
8940 case SERIAL_TIMEOUT:
8941 /* Nothing we can do. */
8942 return;
8943 case '#':
8944 /* Discard the two bytes of checksum and stop. */
8945 c = readchar (remote_timeout);
8946 if (c >= 0)
8947 c = readchar (remote_timeout);
8948
8949 return;
8950 case '*': /* Run length encoding. */
8951 /* Discard the repeat count. */
8952 c = readchar (remote_timeout);
8953 if (c < 0)
8954 return;
8955 break;
8956 default:
8957 /* A regular character. */
8958 break;
8959 }
8960 }
8961}
8962
8963/* Come here after finding the start of the frame. Collect the rest
8964 into *BUF, verifying the checksum, length, and handling run-length
8965 compression. NUL terminate the buffer. If there is not enough room,
8966 expand *BUF using xrealloc.
8967
8968 Returns -1 on error, number of characters in buffer (ignoring the
8969 trailing NULL) on success. (could be extended to return one of the
8970 SERIAL status indications). */
8971
8972static long
8973read_frame (char **buf_p,
8974 long *sizeof_buf)
8975{
8976 unsigned char csum;
8977 long bc;
8978 int c;
8979 char *buf = *buf_p;
8980 struct remote_state *rs = get_remote_state ();
8981
8982 csum = 0;
8983 bc = 0;
8984
8985 while (1)
8986 {
8987 c = readchar (remote_timeout);
8988 switch (c)
8989 {
8990 case SERIAL_TIMEOUT:
8991 if (remote_debug)
8992 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8993 return -1;
8994 case '$':
8995 if (remote_debug)
8996 fputs_filtered ("Saw new packet start in middle of old one\n",
8997 gdb_stdlog);
8998 return -1; /* Start a new packet, count retries. */
8999 case '#':
9000 {
9001 unsigned char pktcsum;
9002 int check_0 = 0;
9003 int check_1 = 0;
9004
9005 buf[bc] = '\0';
9006
9007 check_0 = readchar (remote_timeout);
9008 if (check_0 >= 0)
9009 check_1 = readchar (remote_timeout);
9010
9011 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9012 {
9013 if (remote_debug)
9014 fputs_filtered ("Timeout in checksum, retrying\n",
9015 gdb_stdlog);
9016 return -1;
9017 }
9018 else if (check_0 < 0 || check_1 < 0)
9019 {
9020 if (remote_debug)
9021 fputs_filtered ("Communication error in checksum\n",
9022 gdb_stdlog);
9023 return -1;
9024 }
9025
9026 /* Don't recompute the checksum; with no ack packets we
9027 don't have any way to indicate a packet retransmission
9028 is necessary. */
9029 if (rs->noack_mode)
9030 return bc;
9031
9032 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9033 if (csum == pktcsum)
9034 return bc;
9035
9036 if (remote_debug)
9037 {
9038 std::string str = escape_buffer (buf, bc);
9039
9040 fprintf_unfiltered (gdb_stdlog,
9041 "Bad checksum, sentsum=0x%x, "
9042 "csum=0x%x, buf=%s\n",
9043 pktcsum, csum, str.c_str ());
9044 }
9045 /* Number of characters in buffer ignoring trailing
9046 NULL. */
9047 return -1;
9048 }
9049 case '*': /* Run length encoding. */
9050 {
9051 int repeat;
9052
9053 csum += c;
9054 c = readchar (remote_timeout);
9055 csum += c;
9056 repeat = c - ' ' + 3; /* Compute repeat count. */
9057
9058 /* The character before ``*'' is repeated. */
9059
9060 if (repeat > 0 && repeat <= 255 && bc > 0)
9061 {
9062 if (bc + repeat - 1 >= *sizeof_buf - 1)
9063 {
9064 /* Make some more room in the buffer. */
9065 *sizeof_buf += repeat;
9066 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9067 buf = *buf_p;
9068 }
9069
9070 memset (&buf[bc], buf[bc - 1], repeat);
9071 bc += repeat;
9072 continue;
9073 }
9074
9075 buf[bc] = '\0';
9076 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9077 return -1;
9078 }
9079 default:
9080 if (bc >= *sizeof_buf - 1)
9081 {
9082 /* Make some more room in the buffer. */
9083 *sizeof_buf *= 2;
9084 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9085 buf = *buf_p;
9086 }
9087
9088 buf[bc++] = c;
9089 csum += c;
9090 continue;
9091 }
9092 }
9093}
9094
9095/* Read a packet from the remote machine, with error checking, and
9096 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9097 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9098 rather than timing out; this is used (in synchronous mode) to wait
9099 for a target that is is executing user code to stop. */
9100/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9101 don't have to change all the calls to getpkt to deal with the
9102 return value, because at the moment I don't know what the right
9103 thing to do it for those. */
9104void
9105getpkt (char **buf,
9106 long *sizeof_buf,
9107 int forever)
9108{
9109 getpkt_sane (buf, sizeof_buf, forever);
9110}
9111
9112
9113/* Read a packet from the remote machine, with error checking, and
9114 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9115 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9116 rather than timing out; this is used (in synchronous mode) to wait
9117 for a target that is is executing user code to stop. If FOREVER ==
9118 0, this function is allowed to time out gracefully and return an
9119 indication of this to the caller. Otherwise return the number of
9120 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9121 enough reason to return to the caller. *IS_NOTIF is an output
9122 boolean that indicates whether *BUF holds a notification or not
9123 (a regular packet). */
9124
9125static int
9126getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9127 int expecting_notif, int *is_notif)
9128{
9129 struct remote_state *rs = get_remote_state ();
9130 int c;
9131 int tries;
9132 int timeout;
9133 int val = -1;
9134
9135 /* We're reading a new response. Make sure we don't look at a
9136 previously cached response. */
9137 rs->cached_wait_status = 0;
9138
9139 strcpy (*buf, "timeout");
9140
9141 if (forever)
9142 timeout = watchdog > 0 ? watchdog : -1;
9143 else if (expecting_notif)
9144 timeout = 0; /* There should already be a char in the buffer. If
9145 not, bail out. */
9146 else
9147 timeout = remote_timeout;
9148
9149#define MAX_TRIES 3
9150
9151 /* Process any number of notifications, and then return when
9152 we get a packet. */
9153 for (;;)
9154 {
9155 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9156 times. */
9157 for (tries = 1; tries <= MAX_TRIES; tries++)
9158 {
9159 /* This can loop forever if the remote side sends us
9160 characters continuously, but if it pauses, we'll get
9161 SERIAL_TIMEOUT from readchar because of timeout. Then
9162 we'll count that as a retry.
9163
9164 Note that even when forever is set, we will only wait
9165 forever prior to the start of a packet. After that, we
9166 expect characters to arrive at a brisk pace. They should
9167 show up within remote_timeout intervals. */
9168 do
9169 c = readchar (timeout);
9170 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9171
9172 if (c == SERIAL_TIMEOUT)
9173 {
9174 if (expecting_notif)
9175 return -1; /* Don't complain, it's normal to not get
9176 anything in this case. */
9177
9178 if (forever) /* Watchdog went off? Kill the target. */
9179 {
9180 remote_unpush_target ();
9181 throw_error (TARGET_CLOSE_ERROR,
9182 _("Watchdog timeout has expired. "
9183 "Target detached."));
9184 }
9185 if (remote_debug)
9186 fputs_filtered ("Timed out.\n", gdb_stdlog);
9187 }
9188 else
9189 {
9190 /* We've found the start of a packet or notification.
9191 Now collect the data. */
9192 val = read_frame (buf, sizeof_buf);
9193 if (val >= 0)
9194 break;
9195 }
9196
9197 remote_serial_write ("-", 1);
9198 }
9199
9200 if (tries > MAX_TRIES)
9201 {
9202 /* We have tried hard enough, and just can't receive the
9203 packet/notification. Give up. */
9204 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9205
9206 /* Skip the ack char if we're in no-ack mode. */
9207 if (!rs->noack_mode)
9208 remote_serial_write ("+", 1);
9209 return -1;
9210 }
9211
9212 /* If we got an ordinary packet, return that to our caller. */
9213 if (c == '$')
9214 {
9215 if (remote_debug)
9216 {
9217 std::string str
9218 = escape_buffer (*buf,
9219 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9220
9221 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9222 str.c_str ());
9223
9224 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
9225 {
9226 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
9227 str.length () - REMOTE_DEBUG_MAX_CHAR);
9228 }
9229
9230 fprintf_unfiltered (gdb_stdlog, "\n");
9231 }
9232
9233 /* Skip the ack char if we're in no-ack mode. */
9234 if (!rs->noack_mode)
9235 remote_serial_write ("+", 1);
9236 if (is_notif != NULL)
9237 *is_notif = 0;
9238 return val;
9239 }
9240
9241 /* If we got a notification, handle it, and go back to looking
9242 for a packet. */
9243 else
9244 {
9245 gdb_assert (c == '%');
9246
9247 if (remote_debug)
9248 {
9249 std::string str = escape_buffer (*buf, val);
9250
9251 fprintf_unfiltered (gdb_stdlog,
9252 " Notification received: %s\n",
9253 str.c_str ());
9254 }
9255 if (is_notif != NULL)
9256 *is_notif = 1;
9257
9258 handle_notification (rs->notif_state, *buf);
9259
9260 /* Notifications require no acknowledgement. */
9261
9262 if (expecting_notif)
9263 return val;
9264 }
9265 }
9266}
9267
9268static int
9269getpkt_sane (char **buf, long *sizeof_buf, int forever)
9270{
9271 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9272}
9273
9274static int
9275getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9276 int *is_notif)
9277{
9278 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9279 is_notif);
9280}
9281
9282/* Check whether EVENT is a fork event for the process specified
9283 by the pid passed in DATA, and if it is, kill the fork child. */
9284
9285static int
9286kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9287 QUEUE_ITER (stop_reply_p) *iter,
9288 stop_reply_p event,
9289 void *data)
9290{
9291 struct queue_iter_param *param = (struct queue_iter_param *) data;
9292 int parent_pid = *(int *) param->input;
9293
9294 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9295 {
9296 struct remote_state *rs = get_remote_state ();
9297 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9298 int res;
9299
9300 res = remote_vkill (child_pid, rs);
9301 if (res != 0)
9302 error (_("Can't kill fork child process %d"), child_pid);
9303 }
9304
9305 return 1;
9306}
9307
9308/* Kill any new fork children of process PID that haven't been
9309 processed by follow_fork. */
9310
9311static void
9312kill_new_fork_children (int pid, struct remote_state *rs)
9313{
9314 struct thread_info *thread;
9315 struct notif_client *notif = &notif_client_stop;
9316 struct queue_iter_param param;
9317
9318 /* Kill the fork child threads of any threads in process PID
9319 that are stopped at a fork event. */
9320 ALL_NON_EXITED_THREADS (thread)
9321 {
9322 struct target_waitstatus *ws = &thread->pending_follow;
9323
9324 if (is_pending_fork_parent (ws, pid, thread->ptid))
9325 {
9326 struct remote_state *rs = get_remote_state ();
9327 int child_pid = ptid_get_pid (ws->value.related_pid);
9328 int res;
9329
9330 res = remote_vkill (child_pid, rs);
9331 if (res != 0)
9332 error (_("Can't kill fork child process %d"), child_pid);
9333 }
9334 }
9335
9336 /* Check for any pending fork events (not reported or processed yet)
9337 in process PID and kill those fork child threads as well. */
9338 remote_notif_get_pending_events (notif);
9339 param.input = &pid;
9340 param.output = NULL;
9341 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9342 kill_child_of_pending_fork, &param);
9343}
9344
9345\f
9346/* Target hook to kill the current inferior. */
9347
9348static void
9349remote_kill (struct target_ops *ops)
9350{
9351 int res = -1;
9352 int pid = ptid_get_pid (inferior_ptid);
9353 struct remote_state *rs = get_remote_state ();
9354
9355 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9356 {
9357 /* If we're stopped while forking and we haven't followed yet,
9358 kill the child task. We need to do this before killing the
9359 parent task because if this is a vfork then the parent will
9360 be sleeping. */
9361 kill_new_fork_children (pid, rs);
9362
9363 res = remote_vkill (pid, rs);
9364 if (res == 0)
9365 {
9366 target_mourn_inferior (inferior_ptid);
9367 return;
9368 }
9369 }
9370
9371 /* If we are in 'target remote' mode and we are killing the only
9372 inferior, then we will tell gdbserver to exit and unpush the
9373 target. */
9374 if (res == -1 && !remote_multi_process_p (rs)
9375 && number_of_live_inferiors () == 1)
9376 {
9377 remote_kill_k ();
9378
9379 /* We've killed the remote end, we get to mourn it. If we are
9380 not in extended mode, mourning the inferior also unpushes
9381 remote_ops from the target stack, which closes the remote
9382 connection. */
9383 target_mourn_inferior (inferior_ptid);
9384
9385 return;
9386 }
9387
9388 error (_("Can't kill process"));
9389}
9390
9391/* Send a kill request to the target using the 'vKill' packet. */
9392
9393static int
9394remote_vkill (int pid, struct remote_state *rs)
9395{
9396 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9397 return -1;
9398
9399 /* Tell the remote target to detach. */
9400 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9401 putpkt (rs->buf);
9402 getpkt (&rs->buf, &rs->buf_size, 0);
9403
9404 switch (packet_ok (rs->buf,
9405 &remote_protocol_packets[PACKET_vKill]))
9406 {
9407 case PACKET_OK:
9408 return 0;
9409 case PACKET_ERROR:
9410 return 1;
9411 case PACKET_UNKNOWN:
9412 return -1;
9413 default:
9414 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9415 }
9416}
9417
9418/* Send a kill request to the target using the 'k' packet. */
9419
9420static void
9421remote_kill_k (void)
9422{
9423 /* Catch errors so the user can quit from gdb even when we
9424 aren't on speaking terms with the remote system. */
9425 TRY
9426 {
9427 putpkt ("k");
9428 }
9429 CATCH (ex, RETURN_MASK_ERROR)
9430 {
9431 if (ex.error == TARGET_CLOSE_ERROR)
9432 {
9433 /* If we got an (EOF) error that caused the target
9434 to go away, then we're done, that's what we wanted.
9435 "k" is susceptible to cause a premature EOF, given
9436 that the remote server isn't actually required to
9437 reply to "k", and it can happen that it doesn't
9438 even get to reply ACK to the "k". */
9439 return;
9440 }
9441
9442 /* Otherwise, something went wrong. We didn't actually kill
9443 the target. Just propagate the exception, and let the
9444 user or higher layers decide what to do. */
9445 throw_exception (ex);
9446 }
9447 END_CATCH
9448}
9449
9450static void
9451remote_mourn (struct target_ops *target)
9452{
9453 struct remote_state *rs = get_remote_state ();
9454
9455 /* In 'target remote' mode with one inferior, we close the connection. */
9456 if (!rs->extended && number_of_live_inferiors () <= 1)
9457 {
9458 unpush_target (target);
9459
9460 /* remote_close takes care of doing most of the clean up. */
9461 generic_mourn_inferior ();
9462 return;
9463 }
9464
9465 /* In case we got here due to an error, but we're going to stay
9466 connected. */
9467 rs->waiting_for_stop_reply = 0;
9468
9469 /* If the current general thread belonged to the process we just
9470 detached from or has exited, the remote side current general
9471 thread becomes undefined. Considering a case like this:
9472
9473 - We just got here due to a detach.
9474 - The process that we're detaching from happens to immediately
9475 report a global breakpoint being hit in non-stop mode, in the
9476 same thread we had selected before.
9477 - GDB attaches to this process again.
9478 - This event happens to be the next event we handle.
9479
9480 GDB would consider that the current general thread didn't need to
9481 be set on the stub side (with Hg), since for all it knew,
9482 GENERAL_THREAD hadn't changed.
9483
9484 Notice that although in all-stop mode, the remote server always
9485 sets the current thread to the thread reporting the stop event,
9486 that doesn't happen in non-stop mode; in non-stop, the stub *must
9487 not* change the current thread when reporting a breakpoint hit,
9488 due to the decoupling of event reporting and event handling.
9489
9490 To keep things simple, we always invalidate our notion of the
9491 current thread. */
9492 record_currthread (rs, minus_one_ptid);
9493
9494 /* Call common code to mark the inferior as not running. */
9495 generic_mourn_inferior ();
9496
9497 if (!have_inferiors ())
9498 {
9499 if (!remote_multi_process_p (rs))
9500 {
9501 /* Check whether the target is running now - some remote stubs
9502 automatically restart after kill. */
9503 putpkt ("?");
9504 getpkt (&rs->buf, &rs->buf_size, 0);
9505
9506 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9507 {
9508 /* Assume that the target has been restarted. Set
9509 inferior_ptid so that bits of core GDB realizes
9510 there's something here, e.g., so that the user can
9511 say "kill" again. */
9512 inferior_ptid = magic_null_ptid;
9513 }
9514 }
9515 }
9516}
9517
9518static int
9519extended_remote_supports_disable_randomization (struct target_ops *self)
9520{
9521 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9522}
9523
9524static void
9525extended_remote_disable_randomization (int val)
9526{
9527 struct remote_state *rs = get_remote_state ();
9528 char *reply;
9529
9530 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9531 val);
9532 putpkt (rs->buf);
9533 reply = remote_get_noisy_reply ();
9534 if (*reply == '\0')
9535 error (_("Target does not support QDisableRandomization."));
9536 if (strcmp (reply, "OK") != 0)
9537 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9538}
9539
9540static int
9541extended_remote_run (const std::string &args)
9542{
9543 struct remote_state *rs = get_remote_state ();
9544 int len;
9545 const char *remote_exec_file = get_remote_exec_file ();
9546
9547 /* If the user has disabled vRun support, or we have detected that
9548 support is not available, do not try it. */
9549 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9550 return -1;
9551
9552 strcpy (rs->buf, "vRun;");
9553 len = strlen (rs->buf);
9554
9555 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9556 error (_("Remote file name too long for run packet"));
9557 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9558 strlen (remote_exec_file));
9559
9560 if (!args.empty ())
9561 {
9562 int i;
9563
9564 gdb_argv argv (args.c_str ());
9565 for (i = 0; argv[i] != NULL; i++)
9566 {
9567 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9568 error (_("Argument list too long for run packet"));
9569 rs->buf[len++] = ';';
9570 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9571 strlen (argv[i]));
9572 }
9573 }
9574
9575 rs->buf[len++] = '\0';
9576
9577 putpkt (rs->buf);
9578 getpkt (&rs->buf, &rs->buf_size, 0);
9579
9580 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9581 {
9582 case PACKET_OK:
9583 /* We have a wait response. All is well. */
9584 return 0;
9585 case PACKET_UNKNOWN:
9586 return -1;
9587 case PACKET_ERROR:
9588 if (remote_exec_file[0] == '\0')
9589 error (_("Running the default executable on the remote target failed; "
9590 "try \"set remote exec-file\"?"));
9591 else
9592 error (_("Running \"%s\" on the remote target failed"),
9593 remote_exec_file);
9594 default:
9595 gdb_assert_not_reached (_("bad switch"));
9596 }
9597}
9598
9599/* Helper function to send set/unset environment packets. ACTION is
9600 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9601 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9602 sent. */
9603
9604static void
9605send_environment_packet (struct remote_state *rs,
9606 const char *action,
9607 const char *packet,
9608 const char *value)
9609{
9610 /* Convert the environment variable to an hex string, which
9611 is the best format to be transmitted over the wire. */
9612 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9613 strlen (value));
9614
9615 xsnprintf (rs->buf, get_remote_packet_size (),
9616 "%s:%s", packet, encoded_value.c_str ());
9617
9618 putpkt (rs->buf);
9619 getpkt (&rs->buf, &rs->buf_size, 0);
9620 if (strcmp (rs->buf, "OK") != 0)
9621 warning (_("Unable to %s environment variable '%s' on remote."),
9622 action, value);
9623}
9624
9625/* Helper function to handle the QEnvironment* packets. */
9626
9627static void
9628extended_remote_environment_support (struct remote_state *rs)
9629{
9630 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9631 {
9632 putpkt ("QEnvironmentReset");
9633 getpkt (&rs->buf, &rs->buf_size, 0);
9634 if (strcmp (rs->buf, "OK") != 0)
9635 warning (_("Unable to reset environment on remote."));
9636 }
9637
9638 gdb_environ *e = &current_inferior ()->environment;
9639
9640 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9641 for (const std::string &el : e->user_set_env ())
9642 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9643 el.c_str ());
9644
9645 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9646 for (const std::string &el : e->user_unset_env ())
9647 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9648}
9649
9650/* Helper function to set the current working directory for the
9651 inferior in the remote target. */
9652
9653static void
9654extended_remote_set_inferior_cwd (struct remote_state *rs)
9655{
9656 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9657 {
9658 const char *inferior_cwd = get_inferior_cwd ();
9659
9660 if (inferior_cwd != NULL)
9661 {
9662 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9663 strlen (inferior_cwd));
9664
9665 xsnprintf (rs->buf, get_remote_packet_size (),
9666 "QSetWorkingDir:%s", hexpath.c_str ());
9667 }
9668 else
9669 {
9670 /* An empty inferior_cwd means that the user wants us to
9671 reset the remote server's inferior's cwd. */
9672 xsnprintf (rs->buf, get_remote_packet_size (),
9673 "QSetWorkingDir:");
9674 }
9675
9676 putpkt (rs->buf);
9677 getpkt (&rs->buf, &rs->buf_size, 0);
9678 if (packet_ok (rs->buf,
9679 &remote_protocol_packets[PACKET_QSetWorkingDir])
9680 != PACKET_OK)
9681 error (_("\
9682Remote replied unexpectedly while setting the inferior's working\n\
9683directory: %s"),
9684 rs->buf);
9685
9686 }
9687}
9688
9689/* In the extended protocol we want to be able to do things like
9690 "run" and have them basically work as expected. So we need
9691 a special create_inferior function. We support changing the
9692 executable file and the command line arguments, but not the
9693 environment. */
9694
9695static void
9696extended_remote_create_inferior (struct target_ops *ops,
9697 const char *exec_file,
9698 const std::string &args,
9699 char **env, int from_tty)
9700{
9701 int run_worked;
9702 char *stop_reply;
9703 struct remote_state *rs = get_remote_state ();
9704 const char *remote_exec_file = get_remote_exec_file ();
9705
9706 /* If running asynchronously, register the target file descriptor
9707 with the event loop. */
9708 if (target_can_async_p ())
9709 target_async (1);
9710
9711 /* Disable address space randomization if requested (and supported). */
9712 if (extended_remote_supports_disable_randomization (ops))
9713 extended_remote_disable_randomization (disable_randomization);
9714
9715 /* If startup-with-shell is on, we inform gdbserver to start the
9716 remote inferior using a shell. */
9717 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9718 {
9719 xsnprintf (rs->buf, get_remote_packet_size (),
9720 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9721 putpkt (rs->buf);
9722 getpkt (&rs->buf, &rs->buf_size, 0);
9723 if (strcmp (rs->buf, "OK") != 0)
9724 error (_("\
9725Remote replied unexpectedly while setting startup-with-shell: %s"),
9726 rs->buf);
9727 }
9728
9729 extended_remote_environment_support (rs);
9730
9731 extended_remote_set_inferior_cwd (rs);
9732
9733 /* Now restart the remote server. */
9734 run_worked = extended_remote_run (args) != -1;
9735 if (!run_worked)
9736 {
9737 /* vRun was not supported. Fail if we need it to do what the
9738 user requested. */
9739 if (remote_exec_file[0])
9740 error (_("Remote target does not support \"set remote exec-file\""));
9741 if (!args.empty ())
9742 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9743
9744 /* Fall back to "R". */
9745 extended_remote_restart ();
9746 }
9747
9748 if (!have_inferiors ())
9749 {
9750 /* Clean up from the last time we ran, before we mark the target
9751 running again. This will mark breakpoints uninserted, and
9752 get_offsets may insert breakpoints. */
9753 init_thread_list ();
9754 init_wait_for_inferior ();
9755 }
9756
9757 /* vRun's success return is a stop reply. */
9758 stop_reply = run_worked ? rs->buf : NULL;
9759 add_current_inferior_and_thread (stop_reply);
9760
9761 /* Get updated offsets, if the stub uses qOffsets. */
9762 get_offsets ();
9763}
9764\f
9765
9766/* Given a location's target info BP_TGT and the packet buffer BUF, output
9767 the list of conditions (in agent expression bytecode format), if any, the
9768 target needs to evaluate. The output is placed into the packet buffer
9769 started from BUF and ended at BUF_END. */
9770
9771static int
9772remote_add_target_side_condition (struct gdbarch *gdbarch,
9773 struct bp_target_info *bp_tgt, char *buf,
9774 char *buf_end)
9775{
9776 if (bp_tgt->conditions.empty ())
9777 return 0;
9778
9779 buf += strlen (buf);
9780 xsnprintf (buf, buf_end - buf, "%s", ";");
9781 buf++;
9782
9783 /* Send conditions to the target. */
9784 for (agent_expr *aexpr : bp_tgt->conditions)
9785 {
9786 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9787 buf += strlen (buf);
9788 for (int i = 0; i < aexpr->len; ++i)
9789 buf = pack_hex_byte (buf, aexpr->buf[i]);
9790 *buf = '\0';
9791 }
9792 return 0;
9793}
9794
9795static void
9796remote_add_target_side_commands (struct gdbarch *gdbarch,
9797 struct bp_target_info *bp_tgt, char *buf)
9798{
9799 if (bp_tgt->tcommands.empty ())
9800 return;
9801
9802 buf += strlen (buf);
9803
9804 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9805 buf += strlen (buf);
9806
9807 /* Concatenate all the agent expressions that are commands into the
9808 cmds parameter. */
9809 for (agent_expr *aexpr : bp_tgt->tcommands)
9810 {
9811 sprintf (buf, "X%x,", aexpr->len);
9812 buf += strlen (buf);
9813 for (int i = 0; i < aexpr->len; ++i)
9814 buf = pack_hex_byte (buf, aexpr->buf[i]);
9815 *buf = '\0';
9816 }
9817}
9818
9819/* Insert a breakpoint. On targets that have software breakpoint
9820 support, we ask the remote target to do the work; on targets
9821 which don't, we insert a traditional memory breakpoint. */
9822
9823static int
9824remote_insert_breakpoint (struct target_ops *ops,
9825 struct gdbarch *gdbarch,
9826 struct bp_target_info *bp_tgt)
9827{
9828 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9829 If it succeeds, then set the support to PACKET_ENABLE. If it
9830 fails, and the user has explicitly requested the Z support then
9831 report an error, otherwise, mark it disabled and go on. */
9832
9833 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9834 {
9835 CORE_ADDR addr = bp_tgt->reqstd_address;
9836 struct remote_state *rs;
9837 char *p, *endbuf;
9838 int bpsize;
9839
9840 /* Make sure the remote is pointing at the right process, if
9841 necessary. */
9842 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9843 set_general_process ();
9844
9845 rs = get_remote_state ();
9846 p = rs->buf;
9847 endbuf = rs->buf + get_remote_packet_size ();
9848
9849 *(p++) = 'Z';
9850 *(p++) = '0';
9851 *(p++) = ',';
9852 addr = (ULONGEST) remote_address_masked (addr);
9853 p += hexnumstr (p, addr);
9854 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9855
9856 if (remote_supports_cond_breakpoints (ops))
9857 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9858
9859 if (remote_can_run_breakpoint_commands (ops))
9860 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9861
9862 putpkt (rs->buf);
9863 getpkt (&rs->buf, &rs->buf_size, 0);
9864
9865 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9866 {
9867 case PACKET_ERROR:
9868 return -1;
9869 case PACKET_OK:
9870 return 0;
9871 case PACKET_UNKNOWN:
9872 break;
9873 }
9874 }
9875
9876 /* If this breakpoint has target-side commands but this stub doesn't
9877 support Z0 packets, throw error. */
9878 if (!bp_tgt->tcommands.empty ())
9879 throw_error (NOT_SUPPORTED_ERROR, _("\
9880Target doesn't support breakpoints that have target side commands."));
9881
9882 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9883}
9884
9885static int
9886remote_remove_breakpoint (struct target_ops *ops,
9887 struct gdbarch *gdbarch,
9888 struct bp_target_info *bp_tgt,
9889 enum remove_bp_reason reason)
9890{
9891 CORE_ADDR addr = bp_tgt->placed_address;
9892 struct remote_state *rs = get_remote_state ();
9893
9894 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9895 {
9896 char *p = rs->buf;
9897 char *endbuf = rs->buf + get_remote_packet_size ();
9898
9899 /* Make sure the remote is pointing at the right process, if
9900 necessary. */
9901 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9902 set_general_process ();
9903
9904 *(p++) = 'z';
9905 *(p++) = '0';
9906 *(p++) = ',';
9907
9908 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9909 p += hexnumstr (p, addr);
9910 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9911
9912 putpkt (rs->buf);
9913 getpkt (&rs->buf, &rs->buf_size, 0);
9914
9915 return (rs->buf[0] == 'E');
9916 }
9917
9918 return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
9919}
9920
9921static enum Z_packet_type
9922watchpoint_to_Z_packet (int type)
9923{
9924 switch (type)
9925 {
9926 case hw_write:
9927 return Z_PACKET_WRITE_WP;
9928 break;
9929 case hw_read:
9930 return Z_PACKET_READ_WP;
9931 break;
9932 case hw_access:
9933 return Z_PACKET_ACCESS_WP;
9934 break;
9935 default:
9936 internal_error (__FILE__, __LINE__,
9937 _("hw_bp_to_z: bad watchpoint type %d"), type);
9938 }
9939}
9940
9941static int
9942remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9943 enum target_hw_bp_type type, struct expression *cond)
9944{
9945 struct remote_state *rs = get_remote_state ();
9946 char *endbuf = rs->buf + get_remote_packet_size ();
9947 char *p;
9948 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9949
9950 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9951 return 1;
9952
9953 /* Make sure the remote is pointing at the right process, if
9954 necessary. */
9955 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9956 set_general_process ();
9957
9958 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9959 p = strchr (rs->buf, '\0');
9960 addr = remote_address_masked (addr);
9961 p += hexnumstr (p, (ULONGEST) addr);
9962 xsnprintf (p, endbuf - p, ",%x", len);
9963
9964 putpkt (rs->buf);
9965 getpkt (&rs->buf, &rs->buf_size, 0);
9966
9967 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9968 {
9969 case PACKET_ERROR:
9970 return -1;
9971 case PACKET_UNKNOWN:
9972 return 1;
9973 case PACKET_OK:
9974 return 0;
9975 }
9976 internal_error (__FILE__, __LINE__,
9977 _("remote_insert_watchpoint: reached end of function"));
9978}
9979
9980static int
9981remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9982 CORE_ADDR start, int length)
9983{
9984 CORE_ADDR diff = remote_address_masked (addr - start);
9985
9986 return diff < length;
9987}
9988
9989
9990static int
9991remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9992 enum target_hw_bp_type type, struct expression *cond)
9993{
9994 struct remote_state *rs = get_remote_state ();
9995 char *endbuf = rs->buf + get_remote_packet_size ();
9996 char *p;
9997 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9998
9999 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10000 return -1;
10001
10002 /* Make sure the remote is pointing at the right process, if
10003 necessary. */
10004 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10005 set_general_process ();
10006
10007 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10008 p = strchr (rs->buf, '\0');
10009 addr = remote_address_masked (addr);
10010 p += hexnumstr (p, (ULONGEST) addr);
10011 xsnprintf (p, endbuf - p, ",%x", len);
10012 putpkt (rs->buf);
10013 getpkt (&rs->buf, &rs->buf_size, 0);
10014
10015 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10016 {
10017 case PACKET_ERROR:
10018 case PACKET_UNKNOWN:
10019 return -1;
10020 case PACKET_OK:
10021 return 0;
10022 }
10023 internal_error (__FILE__, __LINE__,
10024 _("remote_remove_watchpoint: reached end of function"));
10025}
10026
10027
10028int remote_hw_watchpoint_limit = -1;
10029int remote_hw_watchpoint_length_limit = -1;
10030int remote_hw_breakpoint_limit = -1;
10031
10032static int
10033remote_region_ok_for_hw_watchpoint (struct target_ops *self,
10034 CORE_ADDR addr, int len)
10035{
10036 if (remote_hw_watchpoint_length_limit == 0)
10037 return 0;
10038 else if (remote_hw_watchpoint_length_limit < 0)
10039 return 1;
10040 else if (len <= remote_hw_watchpoint_length_limit)
10041 return 1;
10042 else
10043 return 0;
10044}
10045
10046static int
10047remote_check_watch_resources (struct target_ops *self,
10048 enum bptype type, int cnt, int ot)
10049{
10050 if (type == bp_hardware_breakpoint)
10051 {
10052 if (remote_hw_breakpoint_limit == 0)
10053 return 0;
10054 else if (remote_hw_breakpoint_limit < 0)
10055 return 1;
10056 else if (cnt <= remote_hw_breakpoint_limit)
10057 return 1;
10058 }
10059 else
10060 {
10061 if (remote_hw_watchpoint_limit == 0)
10062 return 0;
10063 else if (remote_hw_watchpoint_limit < 0)
10064 return 1;
10065 else if (ot)
10066 return -1;
10067 else if (cnt <= remote_hw_watchpoint_limit)
10068 return 1;
10069 }
10070 return -1;
10071}
10072
10073/* The to_stopped_by_sw_breakpoint method of target remote. */
10074
10075static int
10076remote_stopped_by_sw_breakpoint (struct target_ops *ops)
10077{
10078 struct thread_info *thread = inferior_thread ();
10079
10080 return (thread->priv != NULL
10081 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
10082}
10083
10084/* The to_supports_stopped_by_sw_breakpoint method of target
10085 remote. */
10086
10087static int
10088remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
10089{
10090 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10091}
10092
10093/* The to_stopped_by_hw_breakpoint method of target remote. */
10094
10095static int
10096remote_stopped_by_hw_breakpoint (struct target_ops *ops)
10097{
10098 struct thread_info *thread = inferior_thread ();
10099
10100 return (thread->priv != NULL
10101 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
10102}
10103
10104/* The to_supports_stopped_by_hw_breakpoint method of target
10105 remote. */
10106
10107static int
10108remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
10109{
10110 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10111}
10112
10113static int
10114remote_stopped_by_watchpoint (struct target_ops *ops)
10115{
10116 struct thread_info *thread = inferior_thread ();
10117
10118 return (thread->priv != NULL
10119 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
10120}
10121
10122static int
10123remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
10124{
10125 struct thread_info *thread = inferior_thread ();
10126
10127 if (thread->priv != NULL
10128 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
10129 {
10130 *addr_p = thread->priv->watch_data_address;
10131 return 1;
10132 }
10133
10134 return 0;
10135}
10136
10137
10138static int
10139remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10140 struct bp_target_info *bp_tgt)
10141{
10142 CORE_ADDR addr = bp_tgt->reqstd_address;
10143 struct remote_state *rs;
10144 char *p, *endbuf;
10145 char *message;
10146
10147 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10148 return -1;
10149
10150 /* Make sure the remote is pointing at the right process, if
10151 necessary. */
10152 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10153 set_general_process ();
10154
10155 rs = get_remote_state ();
10156 p = rs->buf;
10157 endbuf = rs->buf + get_remote_packet_size ();
10158
10159 *(p++) = 'Z';
10160 *(p++) = '1';
10161 *(p++) = ',';
10162
10163 addr = remote_address_masked (addr);
10164 p += hexnumstr (p, (ULONGEST) addr);
10165 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10166
10167 if (remote_supports_cond_breakpoints (self))
10168 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10169
10170 if (remote_can_run_breakpoint_commands (self))
10171 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10172
10173 putpkt (rs->buf);
10174 getpkt (&rs->buf, &rs->buf_size, 0);
10175
10176 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10177 {
10178 case PACKET_ERROR:
10179 if (rs->buf[1] == '.')
10180 {
10181 message = strchr (rs->buf + 2, '.');
10182 if (message)
10183 error (_("Remote failure reply: %s"), message + 1);
10184 }
10185 return -1;
10186 case PACKET_UNKNOWN:
10187 return -1;
10188 case PACKET_OK:
10189 return 0;
10190 }
10191 internal_error (__FILE__, __LINE__,
10192 _("remote_insert_hw_breakpoint: reached end of function"));
10193}
10194
10195
10196static int
10197remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10198 struct bp_target_info *bp_tgt)
10199{
10200 CORE_ADDR addr;
10201 struct remote_state *rs = get_remote_state ();
10202 char *p = rs->buf;
10203 char *endbuf = rs->buf + get_remote_packet_size ();
10204
10205 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10206 return -1;
10207
10208 /* Make sure the remote is pointing at the right process, if
10209 necessary. */
10210 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10211 set_general_process ();
10212
10213 *(p++) = 'z';
10214 *(p++) = '1';
10215 *(p++) = ',';
10216
10217 addr = remote_address_masked (bp_tgt->placed_address);
10218 p += hexnumstr (p, (ULONGEST) addr);
10219 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10220
10221 putpkt (rs->buf);
10222 getpkt (&rs->buf, &rs->buf_size, 0);
10223
10224 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10225 {
10226 case PACKET_ERROR:
10227 case PACKET_UNKNOWN:
10228 return -1;
10229 case PACKET_OK:
10230 return 0;
10231 }
10232 internal_error (__FILE__, __LINE__,
10233 _("remote_remove_hw_breakpoint: reached end of function"));
10234}
10235
10236/* Verify memory using the "qCRC:" request. */
10237
10238static int
10239remote_verify_memory (struct target_ops *ops,
10240 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10241{
10242 struct remote_state *rs = get_remote_state ();
10243 unsigned long host_crc, target_crc;
10244 char *tmp;
10245
10246 /* It doesn't make sense to use qCRC if the remote target is
10247 connected but not running. */
10248 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10249 {
10250 enum packet_result result;
10251
10252 /* Make sure the remote is pointing at the right process. */
10253 set_general_process ();
10254
10255 /* FIXME: assumes lma can fit into long. */
10256 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10257 (long) lma, (long) size);
10258 putpkt (rs->buf);
10259
10260 /* Be clever; compute the host_crc before waiting for target
10261 reply. */
10262 host_crc = xcrc32 (data, size, 0xffffffff);
10263
10264 getpkt (&rs->buf, &rs->buf_size, 0);
10265
10266 result = packet_ok (rs->buf,
10267 &remote_protocol_packets[PACKET_qCRC]);
10268 if (result == PACKET_ERROR)
10269 return -1;
10270 else if (result == PACKET_OK)
10271 {
10272 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10273 target_crc = target_crc * 16 + fromhex (*tmp);
10274
10275 return (host_crc == target_crc);
10276 }
10277 }
10278
10279 return simple_verify_memory (ops, data, lma, size);
10280}
10281
10282/* compare-sections command
10283
10284 With no arguments, compares each loadable section in the exec bfd
10285 with the same memory range on the target, and reports mismatches.
10286 Useful for verifying the image on the target against the exec file. */
10287
10288static void
10289compare_sections_command (const char *args, int from_tty)
10290{
10291 asection *s;
10292 gdb_byte *sectdata;
10293 const char *sectname;
10294 bfd_size_type size;
10295 bfd_vma lma;
10296 int matched = 0;
10297 int mismatched = 0;
10298 int res;
10299 int read_only = 0;
10300
10301 if (!exec_bfd)
10302 error (_("command cannot be used without an exec file"));
10303
10304 /* Make sure the remote is pointing at the right process. */
10305 set_general_process ();
10306
10307 if (args != NULL && strcmp (args, "-r") == 0)
10308 {
10309 read_only = 1;
10310 args = NULL;
10311 }
10312
10313 for (s = exec_bfd->sections; s; s = s->next)
10314 {
10315 if (!(s->flags & SEC_LOAD))
10316 continue; /* Skip non-loadable section. */
10317
10318 if (read_only && (s->flags & SEC_READONLY) == 0)
10319 continue; /* Skip writeable sections */
10320
10321 size = bfd_get_section_size (s);
10322 if (size == 0)
10323 continue; /* Skip zero-length section. */
10324
10325 sectname = bfd_get_section_name (exec_bfd, s);
10326 if (args && strcmp (args, sectname) != 0)
10327 continue; /* Not the section selected by user. */
10328
10329 matched = 1; /* Do this section. */
10330 lma = s->lma;
10331
10332 gdb::byte_vector sectdata (size);
10333 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10334
10335 res = target_verify_memory (sectdata.data (), lma, size);
10336
10337 if (res == -1)
10338 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10339 paddress (target_gdbarch (), lma),
10340 paddress (target_gdbarch (), lma + size));
10341
10342 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10343 paddress (target_gdbarch (), lma),
10344 paddress (target_gdbarch (), lma + size));
10345 if (res)
10346 printf_filtered ("matched.\n");
10347 else
10348 {
10349 printf_filtered ("MIS-MATCHED!\n");
10350 mismatched++;
10351 }
10352 }
10353 if (mismatched > 0)
10354 warning (_("One or more sections of the target image does not match\n\
10355the loaded file\n"));
10356 if (args && !matched)
10357 printf_filtered (_("No loaded section named '%s'.\n"), args);
10358}
10359
10360/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10361 into remote target. The number of bytes written to the remote
10362 target is returned, or -1 for error. */
10363
10364static enum target_xfer_status
10365remote_write_qxfer (struct target_ops *ops, const char *object_name,
10366 const char *annex, const gdb_byte *writebuf,
10367 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10368 struct packet_config *packet)
10369{
10370 int i, buf_len;
10371 ULONGEST n;
10372 struct remote_state *rs = get_remote_state ();
10373 int max_size = get_memory_write_packet_size ();
10374
10375 if (packet->support == PACKET_DISABLE)
10376 return TARGET_XFER_E_IO;
10377
10378 /* Insert header. */
10379 i = snprintf (rs->buf, max_size,
10380 "qXfer:%s:write:%s:%s:",
10381 object_name, annex ? annex : "",
10382 phex_nz (offset, sizeof offset));
10383 max_size -= (i + 1);
10384
10385 /* Escape as much data as fits into rs->buf. */
10386 buf_len = remote_escape_output
10387 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10388
10389 if (putpkt_binary (rs->buf, i + buf_len) < 0
10390 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10391 || packet_ok (rs->buf, packet) != PACKET_OK)
10392 return TARGET_XFER_E_IO;
10393
10394 unpack_varlen_hex (rs->buf, &n);
10395
10396 *xfered_len = n;
10397 return TARGET_XFER_OK;
10398}
10399
10400/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10401 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10402 number of bytes read is returned, or 0 for EOF, or -1 for error.
10403 The number of bytes read may be less than LEN without indicating an
10404 EOF. PACKET is checked and updated to indicate whether the remote
10405 target supports this object. */
10406
10407static enum target_xfer_status
10408remote_read_qxfer (struct target_ops *ops, const char *object_name,
10409 const char *annex,
10410 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10411 ULONGEST *xfered_len,
10412 struct packet_config *packet)
10413{
10414 struct remote_state *rs = get_remote_state ();
10415 LONGEST i, n, packet_len;
10416
10417 if (packet->support == PACKET_DISABLE)
10418 return TARGET_XFER_E_IO;
10419
10420 /* Check whether we've cached an end-of-object packet that matches
10421 this request. */
10422 if (rs->finished_object)
10423 {
10424 if (strcmp (object_name, rs->finished_object) == 0
10425 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10426 && offset == rs->finished_offset)
10427 return TARGET_XFER_EOF;
10428
10429
10430 /* Otherwise, we're now reading something different. Discard
10431 the cache. */
10432 xfree (rs->finished_object);
10433 xfree (rs->finished_annex);
10434 rs->finished_object = NULL;
10435 rs->finished_annex = NULL;
10436 }
10437
10438 /* Request only enough to fit in a single packet. The actual data
10439 may not, since we don't know how much of it will need to be escaped;
10440 the target is free to respond with slightly less data. We subtract
10441 five to account for the response type and the protocol frame. */
10442 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10443 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10444 object_name, annex ? annex : "",
10445 phex_nz (offset, sizeof offset),
10446 phex_nz (n, sizeof n));
10447 i = putpkt (rs->buf);
10448 if (i < 0)
10449 return TARGET_XFER_E_IO;
10450
10451 rs->buf[0] = '\0';
10452 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10453 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10454 return TARGET_XFER_E_IO;
10455
10456 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10457 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10458
10459 /* 'm' means there is (or at least might be) more data after this
10460 batch. That does not make sense unless there's at least one byte
10461 of data in this reply. */
10462 if (rs->buf[0] == 'm' && packet_len == 1)
10463 error (_("Remote qXfer reply contained no data."));
10464
10465 /* Got some data. */
10466 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10467 packet_len - 1, readbuf, n);
10468
10469 /* 'l' is an EOF marker, possibly including a final block of data,
10470 or possibly empty. If we have the final block of a non-empty
10471 object, record this fact to bypass a subsequent partial read. */
10472 if (rs->buf[0] == 'l' && offset + i > 0)
10473 {
10474 rs->finished_object = xstrdup (object_name);
10475 rs->finished_annex = xstrdup (annex ? annex : "");
10476 rs->finished_offset = offset + i;
10477 }
10478
10479 if (i == 0)
10480 return TARGET_XFER_EOF;
10481 else
10482 {
10483 *xfered_len = i;
10484 return TARGET_XFER_OK;
10485 }
10486}
10487
10488static enum target_xfer_status
10489remote_xfer_partial (struct target_ops *ops, enum target_object object,
10490 const char *annex, gdb_byte *readbuf,
10491 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10492 ULONGEST *xfered_len)
10493{
10494 struct remote_state *rs;
10495 int i;
10496 char *p2;
10497 char query_type;
10498 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10499
10500 set_remote_traceframe ();
10501 set_general_thread (inferior_ptid);
10502
10503 rs = get_remote_state ();
10504
10505 /* Handle memory using the standard memory routines. */
10506 if (object == TARGET_OBJECT_MEMORY)
10507 {
10508 /* If the remote target is connected but not running, we should
10509 pass this request down to a lower stratum (e.g. the executable
10510 file). */
10511 if (!target_has_execution)
10512 return TARGET_XFER_EOF;
10513
10514 if (writebuf != NULL)
10515 return remote_write_bytes (offset, writebuf, len, unit_size,
10516 xfered_len);
10517 else
10518 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10519 xfered_len);
10520 }
10521
10522 /* Handle SPU memory using qxfer packets. */
10523 if (object == TARGET_OBJECT_SPU)
10524 {
10525 if (readbuf)
10526 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
10527 xfered_len, &remote_protocol_packets
10528 [PACKET_qXfer_spu_read]);
10529 else
10530 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
10531 xfered_len, &remote_protocol_packets
10532 [PACKET_qXfer_spu_write]);
10533 }
10534
10535 /* Handle extra signal info using qxfer packets. */
10536 if (object == TARGET_OBJECT_SIGNAL_INFO)
10537 {
10538 if (readbuf)
10539 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10540 xfered_len, &remote_protocol_packets
10541 [PACKET_qXfer_siginfo_read]);
10542 else
10543 return remote_write_qxfer (ops, "siginfo", annex,
10544 writebuf, offset, len, xfered_len,
10545 &remote_protocol_packets
10546 [PACKET_qXfer_siginfo_write]);
10547 }
10548
10549 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10550 {
10551 if (readbuf)
10552 return remote_read_qxfer (ops, "statictrace", annex,
10553 readbuf, offset, len, xfered_len,
10554 &remote_protocol_packets
10555 [PACKET_qXfer_statictrace_read]);
10556 else
10557 return TARGET_XFER_E_IO;
10558 }
10559
10560 /* Only handle flash writes. */
10561 if (writebuf != NULL)
10562 {
10563 switch (object)
10564 {
10565 case TARGET_OBJECT_FLASH:
10566 return remote_flash_write (ops, offset, len, xfered_len,
10567 writebuf);
10568
10569 default:
10570 return TARGET_XFER_E_IO;
10571 }
10572 }
10573
10574 /* Map pre-existing objects onto letters. DO NOT do this for new
10575 objects!!! Instead specify new query packets. */
10576 switch (object)
10577 {
10578 case TARGET_OBJECT_AVR:
10579 query_type = 'R';
10580 break;
10581
10582 case TARGET_OBJECT_AUXV:
10583 gdb_assert (annex == NULL);
10584 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10585 xfered_len,
10586 &remote_protocol_packets[PACKET_qXfer_auxv]);
10587
10588 case TARGET_OBJECT_AVAILABLE_FEATURES:
10589 return remote_read_qxfer
10590 (ops, "features", annex, readbuf, offset, len, xfered_len,
10591 &remote_protocol_packets[PACKET_qXfer_features]);
10592
10593 case TARGET_OBJECT_LIBRARIES:
10594 return remote_read_qxfer
10595 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10596 &remote_protocol_packets[PACKET_qXfer_libraries]);
10597
10598 case TARGET_OBJECT_LIBRARIES_SVR4:
10599 return remote_read_qxfer
10600 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10601 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10602
10603 case TARGET_OBJECT_MEMORY_MAP:
10604 gdb_assert (annex == NULL);
10605 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10606 xfered_len,
10607 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10608
10609 case TARGET_OBJECT_OSDATA:
10610 /* Should only get here if we're connected. */
10611 gdb_assert (rs->remote_desc);
10612 return remote_read_qxfer
10613 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10614 &remote_protocol_packets[PACKET_qXfer_osdata]);
10615
10616 case TARGET_OBJECT_THREADS:
10617 gdb_assert (annex == NULL);
10618 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10619 xfered_len,
10620 &remote_protocol_packets[PACKET_qXfer_threads]);
10621
10622 case TARGET_OBJECT_TRACEFRAME_INFO:
10623 gdb_assert (annex == NULL);
10624 return remote_read_qxfer
10625 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10626 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10627
10628 case TARGET_OBJECT_FDPIC:
10629 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10630 xfered_len,
10631 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10632
10633 case TARGET_OBJECT_OPENVMS_UIB:
10634 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10635 xfered_len,
10636 &remote_protocol_packets[PACKET_qXfer_uib]);
10637
10638 case TARGET_OBJECT_BTRACE:
10639 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10640 xfered_len,
10641 &remote_protocol_packets[PACKET_qXfer_btrace]);
10642
10643 case TARGET_OBJECT_BTRACE_CONF:
10644 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10645 len, xfered_len,
10646 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10647
10648 case TARGET_OBJECT_EXEC_FILE:
10649 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10650 len, xfered_len,
10651 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10652
10653 default:
10654 return TARGET_XFER_E_IO;
10655 }
10656
10657 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10658 large enough let the caller deal with it. */
10659 if (len < get_remote_packet_size ())
10660 return TARGET_XFER_E_IO;
10661 len = get_remote_packet_size ();
10662
10663 /* Except for querying the minimum buffer size, target must be open. */
10664 if (!rs->remote_desc)
10665 error (_("remote query is only available after target open"));
10666
10667 gdb_assert (annex != NULL);
10668 gdb_assert (readbuf != NULL);
10669
10670 p2 = rs->buf;
10671 *p2++ = 'q';
10672 *p2++ = query_type;
10673
10674 /* We used one buffer char for the remote protocol q command and
10675 another for the query type. As the remote protocol encapsulation
10676 uses 4 chars plus one extra in case we are debugging
10677 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10678 string. */
10679 i = 0;
10680 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10681 {
10682 /* Bad caller may have sent forbidden characters. */
10683 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10684 *p2++ = annex[i];
10685 i++;
10686 }
10687 *p2 = '\0';
10688 gdb_assert (annex[i] == '\0');
10689
10690 i = putpkt (rs->buf);
10691 if (i < 0)
10692 return TARGET_XFER_E_IO;
10693
10694 getpkt (&rs->buf, &rs->buf_size, 0);
10695 strcpy ((char *) readbuf, rs->buf);
10696
10697 *xfered_len = strlen ((char *) readbuf);
10698 return TARGET_XFER_OK;
10699}
10700
10701/* Implementation of to_get_memory_xfer_limit. */
10702
10703static ULONGEST
10704remote_get_memory_xfer_limit (struct target_ops *ops)
10705{
10706 return get_memory_write_packet_size ();
10707}
10708
10709static int
10710remote_search_memory (struct target_ops* ops,
10711 CORE_ADDR start_addr, ULONGEST search_space_len,
10712 const gdb_byte *pattern, ULONGEST pattern_len,
10713 CORE_ADDR *found_addrp)
10714{
10715 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10716 struct remote_state *rs = get_remote_state ();
10717 int max_size = get_memory_write_packet_size ();
10718 struct packet_config *packet =
10719 &remote_protocol_packets[PACKET_qSearch_memory];
10720 /* Number of packet bytes used to encode the pattern;
10721 this could be more than PATTERN_LEN due to escape characters. */
10722 int escaped_pattern_len;
10723 /* Amount of pattern that was encodable in the packet. */
10724 int used_pattern_len;
10725 int i;
10726 int found;
10727 ULONGEST found_addr;
10728
10729 /* Don't go to the target if we don't have to.
10730 This is done before checking packet->support to avoid the possibility that
10731 a success for this edge case means the facility works in general. */
10732 if (pattern_len > search_space_len)
10733 return 0;
10734 if (pattern_len == 0)
10735 {
10736 *found_addrp = start_addr;
10737 return 1;
10738 }
10739
10740 /* If we already know the packet isn't supported, fall back to the simple
10741 way of searching memory. */
10742
10743 if (packet_config_support (packet) == PACKET_DISABLE)
10744 {
10745 /* Target doesn't provided special support, fall back and use the
10746 standard support (copy memory and do the search here). */
10747 return simple_search_memory (ops, start_addr, search_space_len,
10748 pattern, pattern_len, found_addrp);
10749 }
10750
10751 /* Make sure the remote is pointing at the right process. */
10752 set_general_process ();
10753
10754 /* Insert header. */
10755 i = snprintf (rs->buf, max_size,
10756 "qSearch:memory:%s;%s;",
10757 phex_nz (start_addr, addr_size),
10758 phex_nz (search_space_len, sizeof (search_space_len)));
10759 max_size -= (i + 1);
10760
10761 /* Escape as much data as fits into rs->buf. */
10762 escaped_pattern_len =
10763 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10764 &used_pattern_len, max_size);
10765
10766 /* Bail if the pattern is too large. */
10767 if (used_pattern_len != pattern_len)
10768 error (_("Pattern is too large to transmit to remote target."));
10769
10770 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10771 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10772 || packet_ok (rs->buf, packet) != PACKET_OK)
10773 {
10774 /* The request may not have worked because the command is not
10775 supported. If so, fall back to the simple way. */
10776 if (packet->support == PACKET_DISABLE)
10777 {
10778 return simple_search_memory (ops, start_addr, search_space_len,
10779 pattern, pattern_len, found_addrp);
10780 }
10781 return -1;
10782 }
10783
10784 if (rs->buf[0] == '0')
10785 found = 0;
10786 else if (rs->buf[0] == '1')
10787 {
10788 found = 1;
10789 if (rs->buf[1] != ',')
10790 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10791 unpack_varlen_hex (rs->buf + 2, &found_addr);
10792 *found_addrp = found_addr;
10793 }
10794 else
10795 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10796
10797 return found;
10798}
10799
10800static void
10801remote_rcmd (struct target_ops *self, const char *command,
10802 struct ui_file *outbuf)
10803{
10804 struct remote_state *rs = get_remote_state ();
10805 char *p = rs->buf;
10806
10807 if (!rs->remote_desc)
10808 error (_("remote rcmd is only available after target open"));
10809
10810 /* Send a NULL command across as an empty command. */
10811 if (command == NULL)
10812 command = "";
10813
10814 /* The query prefix. */
10815 strcpy (rs->buf, "qRcmd,");
10816 p = strchr (rs->buf, '\0');
10817
10818 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10819 > get_remote_packet_size ())
10820 error (_("\"monitor\" command ``%s'' is too long."), command);
10821
10822 /* Encode the actual command. */
10823 bin2hex ((const gdb_byte *) command, p, strlen (command));
10824
10825 if (putpkt (rs->buf) < 0)
10826 error (_("Communication problem with target."));
10827
10828 /* get/display the response */
10829 while (1)
10830 {
10831 char *buf;
10832
10833 /* XXX - see also remote_get_noisy_reply(). */
10834 QUIT; /* Allow user to bail out with ^C. */
10835 rs->buf[0] = '\0';
10836 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10837 {
10838 /* Timeout. Continue to (try to) read responses.
10839 This is better than stopping with an error, assuming the stub
10840 is still executing the (long) monitor command.
10841 If needed, the user can interrupt gdb using C-c, obtaining
10842 an effect similar to stop on timeout. */
10843 continue;
10844 }
10845 buf = rs->buf;
10846 if (buf[0] == '\0')
10847 error (_("Target does not support this command."));
10848 if (buf[0] == 'O' && buf[1] != 'K')
10849 {
10850 remote_console_output (buf + 1); /* 'O' message from stub. */
10851 continue;
10852 }
10853 if (strcmp (buf, "OK") == 0)
10854 break;
10855 if (strlen (buf) == 3 && buf[0] == 'E'
10856 && isdigit (buf[1]) && isdigit (buf[2]))
10857 {
10858 error (_("Protocol error with Rcmd"));
10859 }
10860 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10861 {
10862 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10863
10864 fputc_unfiltered (c, outbuf);
10865 }
10866 break;
10867 }
10868}
10869
10870static std::vector<mem_region>
10871remote_memory_map (struct target_ops *ops)
10872{
10873 std::vector<mem_region> result;
10874 gdb::unique_xmalloc_ptr<char> text
10875 = target_read_stralloc (&current_target, TARGET_OBJECT_MEMORY_MAP, NULL);
10876
10877 if (text)
10878 result = parse_memory_map (text.get ());
10879
10880 return result;
10881}
10882
10883static void
10884packet_command (const char *args, int from_tty)
10885{
10886 struct remote_state *rs = get_remote_state ();
10887
10888 if (!rs->remote_desc)
10889 error (_("command can only be used with remote target"));
10890
10891 if (!args)
10892 error (_("remote-packet command requires packet text as argument"));
10893
10894 puts_filtered ("sending: ");
10895 print_packet (args);
10896 puts_filtered ("\n");
10897 putpkt (args);
10898
10899 getpkt (&rs->buf, &rs->buf_size, 0);
10900 puts_filtered ("received: ");
10901 print_packet (rs->buf);
10902 puts_filtered ("\n");
10903}
10904
10905#if 0
10906/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10907
10908static void display_thread_info (struct gdb_ext_thread_info *info);
10909
10910static void threadset_test_cmd (char *cmd, int tty);
10911
10912static void threadalive_test (char *cmd, int tty);
10913
10914static void threadlist_test_cmd (char *cmd, int tty);
10915
10916int get_and_display_threadinfo (threadref *ref);
10917
10918static void threadinfo_test_cmd (char *cmd, int tty);
10919
10920static int thread_display_step (threadref *ref, void *context);
10921
10922static void threadlist_update_test_cmd (char *cmd, int tty);
10923
10924static void init_remote_threadtests (void);
10925
10926#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10927
10928static void
10929threadset_test_cmd (char *cmd, int tty)
10930{
10931 int sample_thread = SAMPLE_THREAD;
10932
10933 printf_filtered (_("Remote threadset test\n"));
10934 set_general_thread (sample_thread);
10935}
10936
10937
10938static void
10939threadalive_test (char *cmd, int tty)
10940{
10941 int sample_thread = SAMPLE_THREAD;
10942 int pid = ptid_get_pid (inferior_ptid);
10943 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10944
10945 if (remote_thread_alive (ptid))
10946 printf_filtered ("PASS: Thread alive test\n");
10947 else
10948 printf_filtered ("FAIL: Thread alive test\n");
10949}
10950
10951void output_threadid (char *title, threadref *ref);
10952
10953void
10954output_threadid (char *title, threadref *ref)
10955{
10956 char hexid[20];
10957
10958 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10959 hexid[16] = 0;
10960 printf_filtered ("%s %s\n", title, (&hexid[0]));
10961}
10962
10963static void
10964threadlist_test_cmd (char *cmd, int tty)
10965{
10966 int startflag = 1;
10967 threadref nextthread;
10968 int done, result_count;
10969 threadref threadlist[3];
10970
10971 printf_filtered ("Remote Threadlist test\n");
10972 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10973 &result_count, &threadlist[0]))
10974 printf_filtered ("FAIL: threadlist test\n");
10975 else
10976 {
10977 threadref *scan = threadlist;
10978 threadref *limit = scan + result_count;
10979
10980 while (scan < limit)
10981 output_threadid (" thread ", scan++);
10982 }
10983}
10984
10985void
10986display_thread_info (struct gdb_ext_thread_info *info)
10987{
10988 output_threadid ("Threadid: ", &info->threadid);
10989 printf_filtered ("Name: %s\n ", info->shortname);
10990 printf_filtered ("State: %s\n", info->display);
10991 printf_filtered ("other: %s\n\n", info->more_display);
10992}
10993
10994int
10995get_and_display_threadinfo (threadref *ref)
10996{
10997 int result;
10998 int set;
10999 struct gdb_ext_thread_info threadinfo;
11000
11001 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11002 | TAG_MOREDISPLAY | TAG_DISPLAY;
11003 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11004 display_thread_info (&threadinfo);
11005 return result;
11006}
11007
11008static void
11009threadinfo_test_cmd (char *cmd, int tty)
11010{
11011 int athread = SAMPLE_THREAD;
11012 threadref thread;
11013 int set;
11014
11015 int_to_threadref (&thread, athread);
11016 printf_filtered ("Remote Threadinfo test\n");
11017 if (!get_and_display_threadinfo (&thread))
11018 printf_filtered ("FAIL cannot get thread info\n");
11019}
11020
11021static int
11022thread_display_step (threadref *ref, void *context)
11023{
11024 /* output_threadid(" threadstep ",ref); *//* simple test */
11025 return get_and_display_threadinfo (ref);
11026}
11027
11028static void
11029threadlist_update_test_cmd (char *cmd, int tty)
11030{
11031 printf_filtered ("Remote Threadlist update test\n");
11032 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11033}
11034
11035static void
11036init_remote_threadtests (void)
11037{
11038 add_com ("tlist", class_obscure, threadlist_test_cmd,
11039 _("Fetch and print the remote list of "
11040 "thread identifiers, one pkt only"));
11041 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11042 _("Fetch and display info about one thread"));
11043 add_com ("tset", class_obscure, threadset_test_cmd,
11044 _("Test setting to a different thread"));
11045 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11046 _("Iterate through updating all remote thread info"));
11047 add_com ("talive", class_obscure, threadalive_test,
11048 _(" Remote thread alive test "));
11049}
11050
11051#endif /* 0 */
11052
11053/* Convert a thread ID to a string. Returns the string in a static
11054 buffer. */
11055
11056static const char *
11057remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
11058{
11059 static char buf[64];
11060 struct remote_state *rs = get_remote_state ();
11061
11062 if (ptid_equal (ptid, null_ptid))
11063 return normal_pid_to_str (ptid);
11064 else if (ptid_is_pid (ptid))
11065 {
11066 /* Printing an inferior target id. */
11067
11068 /* When multi-process extensions are off, there's no way in the
11069 remote protocol to know the remote process id, if there's any
11070 at all. There's one exception --- when we're connected with
11071 target extended-remote, and we manually attached to a process
11072 with "attach PID". We don't record anywhere a flag that
11073 allows us to distinguish that case from the case of
11074 connecting with extended-remote and the stub already being
11075 attached to a process, and reporting yes to qAttached, hence
11076 no smart special casing here. */
11077 if (!remote_multi_process_p (rs))
11078 {
11079 xsnprintf (buf, sizeof buf, "Remote target");
11080 return buf;
11081 }
11082
11083 return normal_pid_to_str (ptid);
11084 }
11085 else
11086 {
11087 if (ptid_equal (magic_null_ptid, ptid))
11088 xsnprintf (buf, sizeof buf, "Thread <main>");
11089 else if (remote_multi_process_p (rs))
11090 if (ptid_get_lwp (ptid) == 0)
11091 return normal_pid_to_str (ptid);
11092 else
11093 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11094 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11095 else
11096 xsnprintf (buf, sizeof buf, "Thread %ld",
11097 ptid_get_lwp (ptid));
11098 return buf;
11099 }
11100}
11101
11102/* Get the address of the thread local variable in OBJFILE which is
11103 stored at OFFSET within the thread local storage for thread PTID. */
11104
11105static CORE_ADDR
11106remote_get_thread_local_address (struct target_ops *ops,
11107 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
11108{
11109 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11110 {
11111 struct remote_state *rs = get_remote_state ();
11112 char *p = rs->buf;
11113 char *endp = rs->buf + get_remote_packet_size ();
11114 enum packet_result result;
11115
11116 strcpy (p, "qGetTLSAddr:");
11117 p += strlen (p);
11118 p = write_ptid (p, endp, ptid);
11119 *p++ = ',';
11120 p += hexnumstr (p, offset);
11121 *p++ = ',';
11122 p += hexnumstr (p, lm);
11123 *p++ = '\0';
11124
11125 putpkt (rs->buf);
11126 getpkt (&rs->buf, &rs->buf_size, 0);
11127 result = packet_ok (rs->buf,
11128 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11129 if (result == PACKET_OK)
11130 {
11131 ULONGEST result;
11132
11133 unpack_varlen_hex (rs->buf, &result);
11134 return result;
11135 }
11136 else if (result == PACKET_UNKNOWN)
11137 throw_error (TLS_GENERIC_ERROR,
11138 _("Remote target doesn't support qGetTLSAddr packet"));
11139 else
11140 throw_error (TLS_GENERIC_ERROR,
11141 _("Remote target failed to process qGetTLSAddr request"));
11142 }
11143 else
11144 throw_error (TLS_GENERIC_ERROR,
11145 _("TLS not supported or disabled on this target"));
11146 /* Not reached. */
11147 return 0;
11148}
11149
11150/* Provide thread local base, i.e. Thread Information Block address.
11151 Returns 1 if ptid is found and thread_local_base is non zero. */
11152
11153static int
11154remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
11155{
11156 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11157 {
11158 struct remote_state *rs = get_remote_state ();
11159 char *p = rs->buf;
11160 char *endp = rs->buf + get_remote_packet_size ();
11161 enum packet_result result;
11162
11163 strcpy (p, "qGetTIBAddr:");
11164 p += strlen (p);
11165 p = write_ptid (p, endp, ptid);
11166 *p++ = '\0';
11167
11168 putpkt (rs->buf);
11169 getpkt (&rs->buf, &rs->buf_size, 0);
11170 result = packet_ok (rs->buf,
11171 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11172 if (result == PACKET_OK)
11173 {
11174 ULONGEST result;
11175
11176 unpack_varlen_hex (rs->buf, &result);
11177 if (addr)
11178 *addr = (CORE_ADDR) result;
11179 return 1;
11180 }
11181 else if (result == PACKET_UNKNOWN)
11182 error (_("Remote target doesn't support qGetTIBAddr packet"));
11183 else
11184 error (_("Remote target failed to process qGetTIBAddr request"));
11185 }
11186 else
11187 error (_("qGetTIBAddr not supported or disabled on this target"));
11188 /* Not reached. */
11189 return 0;
11190}
11191
11192/* Support for inferring a target description based on the current
11193 architecture and the size of a 'g' packet. While the 'g' packet
11194 can have any size (since optional registers can be left off the
11195 end), some sizes are easily recognizable given knowledge of the
11196 approximate architecture. */
11197
11198struct remote_g_packet_guess
11199{
11200 int bytes;
11201 const struct target_desc *tdesc;
11202};
11203typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11204DEF_VEC_O(remote_g_packet_guess_s);
11205
11206struct remote_g_packet_data
11207{
11208 VEC(remote_g_packet_guess_s) *guesses;
11209};
11210
11211static struct gdbarch_data *remote_g_packet_data_handle;
11212
11213static void *
11214remote_g_packet_data_init (struct obstack *obstack)
11215{
11216 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11217}
11218
11219void
11220register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11221 const struct target_desc *tdesc)
11222{
11223 struct remote_g_packet_data *data
11224 = ((struct remote_g_packet_data *)
11225 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11226 struct remote_g_packet_guess new_guess, *guess;
11227 int ix;
11228
11229 gdb_assert (tdesc != NULL);
11230
11231 for (ix = 0;
11232 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11233 ix++)
11234 if (guess->bytes == bytes)
11235 internal_error (__FILE__, __LINE__,
11236 _("Duplicate g packet description added for size %d"),
11237 bytes);
11238
11239 new_guess.bytes = bytes;
11240 new_guess.tdesc = tdesc;
11241 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11242}
11243
11244/* Return 1 if remote_read_description would do anything on this target
11245 and architecture, 0 otherwise. */
11246
11247static int
11248remote_read_description_p (struct target_ops *target)
11249{
11250 struct remote_g_packet_data *data
11251 = ((struct remote_g_packet_data *)
11252 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11253
11254 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11255 return 1;
11256
11257 return 0;
11258}
11259
11260static const struct target_desc *
11261remote_read_description (struct target_ops *target)
11262{
11263 struct remote_g_packet_data *data
11264 = ((struct remote_g_packet_data *)
11265 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11266
11267 /* Do not try this during initial connection, when we do not know
11268 whether there is a running but stopped thread. */
11269 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11270 return target->beneath->to_read_description (target->beneath);
11271
11272 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11273 {
11274 struct remote_g_packet_guess *guess;
11275 int ix;
11276 int bytes = send_g_packet ();
11277
11278 for (ix = 0;
11279 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11280 ix++)
11281 if (guess->bytes == bytes)
11282 return guess->tdesc;
11283
11284 /* We discard the g packet. A minor optimization would be to
11285 hold on to it, and fill the register cache once we have selected
11286 an architecture, but it's too tricky to do safely. */
11287 }
11288
11289 return target->beneath->to_read_description (target->beneath);
11290}
11291
11292/* Remote file transfer support. This is host-initiated I/O, not
11293 target-initiated; for target-initiated, see remote-fileio.c. */
11294
11295/* If *LEFT is at least the length of STRING, copy STRING to
11296 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11297 decrease *LEFT. Otherwise raise an error. */
11298
11299static void
11300remote_buffer_add_string (char **buffer, int *left, const char *string)
11301{
11302 int len = strlen (string);
11303
11304 if (len > *left)
11305 error (_("Packet too long for target."));
11306
11307 memcpy (*buffer, string, len);
11308 *buffer += len;
11309 *left -= len;
11310
11311 /* NUL-terminate the buffer as a convenience, if there is
11312 room. */
11313 if (*left)
11314 **buffer = '\0';
11315}
11316
11317/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11318 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11319 decrease *LEFT. Otherwise raise an error. */
11320
11321static void
11322remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11323 int len)
11324{
11325 if (2 * len > *left)
11326 error (_("Packet too long for target."));
11327
11328 bin2hex (bytes, *buffer, len);
11329 *buffer += 2 * len;
11330 *left -= 2 * len;
11331
11332 /* NUL-terminate the buffer as a convenience, if there is
11333 room. */
11334 if (*left)
11335 **buffer = '\0';
11336}
11337
11338/* If *LEFT is large enough, convert VALUE to hex and add it to
11339 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11340 decrease *LEFT. Otherwise raise an error. */
11341
11342static void
11343remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11344{
11345 int len = hexnumlen (value);
11346
11347 if (len > *left)
11348 error (_("Packet too long for target."));
11349
11350 hexnumstr (*buffer, value);
11351 *buffer += len;
11352 *left -= len;
11353
11354 /* NUL-terminate the buffer as a convenience, if there is
11355 room. */
11356 if (*left)
11357 **buffer = '\0';
11358}
11359
11360/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11361 value, *REMOTE_ERRNO to the remote error number or zero if none
11362 was included, and *ATTACHMENT to point to the start of the annex
11363 if any. The length of the packet isn't needed here; there may
11364 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11365
11366 Return 0 if the packet could be parsed, -1 if it could not. If
11367 -1 is returned, the other variables may not be initialized. */
11368
11369static int
11370remote_hostio_parse_result (char *buffer, int *retcode,
11371 int *remote_errno, char **attachment)
11372{
11373 char *p, *p2;
11374
11375 *remote_errno = 0;
11376 *attachment = NULL;
11377
11378 if (buffer[0] != 'F')
11379 return -1;
11380
11381 errno = 0;
11382 *retcode = strtol (&buffer[1], &p, 16);
11383 if (errno != 0 || p == &buffer[1])
11384 return -1;
11385
11386 /* Check for ",errno". */
11387 if (*p == ',')
11388 {
11389 errno = 0;
11390 *remote_errno = strtol (p + 1, &p2, 16);
11391 if (errno != 0 || p + 1 == p2)
11392 return -1;
11393 p = p2;
11394 }
11395
11396 /* Check for ";attachment". If there is no attachment, the
11397 packet should end here. */
11398 if (*p == ';')
11399 {
11400 *attachment = p + 1;
11401 return 0;
11402 }
11403 else if (*p == '\0')
11404 return 0;
11405 else
11406 return -1;
11407}
11408
11409/* Send a prepared I/O packet to the target and read its response.
11410 The prepared packet is in the global RS->BUF before this function
11411 is called, and the answer is there when we return.
11412
11413 COMMAND_BYTES is the length of the request to send, which may include
11414 binary data. WHICH_PACKET is the packet configuration to check
11415 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11416 is set to the error number and -1 is returned. Otherwise the value
11417 returned by the function is returned.
11418
11419 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11420 attachment is expected; an error will be reported if there's a
11421 mismatch. If one is found, *ATTACHMENT will be set to point into
11422 the packet buffer and *ATTACHMENT_LEN will be set to the
11423 attachment's length. */
11424
11425static int
11426remote_hostio_send_command (int command_bytes, int which_packet,
11427 int *remote_errno, char **attachment,
11428 int *attachment_len)
11429{
11430 struct remote_state *rs = get_remote_state ();
11431 int ret, bytes_read;
11432 char *attachment_tmp;
11433
11434 if (!rs->remote_desc
11435 || packet_support (which_packet) == PACKET_DISABLE)
11436 {
11437 *remote_errno = FILEIO_ENOSYS;
11438 return -1;
11439 }
11440
11441 putpkt_binary (rs->buf, command_bytes);
11442 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11443
11444 /* If it timed out, something is wrong. Don't try to parse the
11445 buffer. */
11446 if (bytes_read < 0)
11447 {
11448 *remote_errno = FILEIO_EINVAL;
11449 return -1;
11450 }
11451
11452 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11453 {
11454 case PACKET_ERROR:
11455 *remote_errno = FILEIO_EINVAL;
11456 return -1;
11457 case PACKET_UNKNOWN:
11458 *remote_errno = FILEIO_ENOSYS;
11459 return -1;
11460 case PACKET_OK:
11461 break;
11462 }
11463
11464 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11465 &attachment_tmp))
11466 {
11467 *remote_errno = FILEIO_EINVAL;
11468 return -1;
11469 }
11470
11471 /* Make sure we saw an attachment if and only if we expected one. */
11472 if ((attachment_tmp == NULL && attachment != NULL)
11473 || (attachment_tmp != NULL && attachment == NULL))
11474 {
11475 *remote_errno = FILEIO_EINVAL;
11476 return -1;
11477 }
11478
11479 /* If an attachment was found, it must point into the packet buffer;
11480 work out how many bytes there were. */
11481 if (attachment_tmp != NULL)
11482 {
11483 *attachment = attachment_tmp;
11484 *attachment_len = bytes_read - (*attachment - rs->buf);
11485 }
11486
11487 return ret;
11488}
11489
11490/* Invalidate the readahead cache. */
11491
11492static void
11493readahead_cache_invalidate (void)
11494{
11495 struct remote_state *rs = get_remote_state ();
11496
11497 rs->readahead_cache.fd = -1;
11498}
11499
11500/* Invalidate the readahead cache if it is holding data for FD. */
11501
11502static void
11503readahead_cache_invalidate_fd (int fd)
11504{
11505 struct remote_state *rs = get_remote_state ();
11506
11507 if (rs->readahead_cache.fd == fd)
11508 rs->readahead_cache.fd = -1;
11509}
11510
11511/* Set the filesystem remote_hostio functions that take FILENAME
11512 arguments will use. Return 0 on success, or -1 if an error
11513 occurs (and set *REMOTE_ERRNO). */
11514
11515static int
11516remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11517{
11518 struct remote_state *rs = get_remote_state ();
11519 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11520 char *p = rs->buf;
11521 int left = get_remote_packet_size () - 1;
11522 char arg[9];
11523 int ret;
11524
11525 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11526 return 0;
11527
11528 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11529 return 0;
11530
11531 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11532
11533 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11534 remote_buffer_add_string (&p, &left, arg);
11535
11536 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11537 remote_errno, NULL, NULL);
11538
11539 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11540 return 0;
11541
11542 if (ret == 0)
11543 rs->fs_pid = required_pid;
11544
11545 return ret;
11546}
11547
11548/* Implementation of to_fileio_open. */
11549
11550static int
11551remote_hostio_open (struct target_ops *self,
11552 struct inferior *inf, const char *filename,
11553 int flags, int mode, int warn_if_slow,
11554 int *remote_errno)
11555{
11556 struct remote_state *rs = get_remote_state ();
11557 char *p = rs->buf;
11558 int left = get_remote_packet_size () - 1;
11559
11560 if (warn_if_slow)
11561 {
11562 static int warning_issued = 0;
11563
11564 printf_unfiltered (_("Reading %s from remote target...\n"),
11565 filename);
11566
11567 if (!warning_issued)
11568 {
11569 warning (_("File transfers from remote targets can be slow."
11570 " Use \"set sysroot\" to access files locally"
11571 " instead."));
11572 warning_issued = 1;
11573 }
11574 }
11575
11576 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11577 return -1;
11578
11579 remote_buffer_add_string (&p, &left, "vFile:open:");
11580
11581 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11582 strlen (filename));
11583 remote_buffer_add_string (&p, &left, ",");
11584
11585 remote_buffer_add_int (&p, &left, flags);
11586 remote_buffer_add_string (&p, &left, ",");
11587
11588 remote_buffer_add_int (&p, &left, mode);
11589
11590 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11591 remote_errno, NULL, NULL);
11592}
11593
11594/* Implementation of to_fileio_pwrite. */
11595
11596static int
11597remote_hostio_pwrite (struct target_ops *self,
11598 int fd, const gdb_byte *write_buf, int len,
11599 ULONGEST offset, int *remote_errno)
11600{
11601 struct remote_state *rs = get_remote_state ();
11602 char *p = rs->buf;
11603 int left = get_remote_packet_size ();
11604 int out_len;
11605
11606 readahead_cache_invalidate_fd (fd);
11607
11608 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11609
11610 remote_buffer_add_int (&p, &left, fd);
11611 remote_buffer_add_string (&p, &left, ",");
11612
11613 remote_buffer_add_int (&p, &left, offset);
11614 remote_buffer_add_string (&p, &left, ",");
11615
11616 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11617 get_remote_packet_size () - (p - rs->buf));
11618
11619 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11620 remote_errno, NULL, NULL);
11621}
11622
11623/* Helper for the implementation of to_fileio_pread. Read the file
11624 from the remote side with vFile:pread. */
11625
11626static int
11627remote_hostio_pread_vFile (struct target_ops *self,
11628 int fd, gdb_byte *read_buf, int len,
11629 ULONGEST offset, int *remote_errno)
11630{
11631 struct remote_state *rs = get_remote_state ();
11632 char *p = rs->buf;
11633 char *attachment;
11634 int left = get_remote_packet_size ();
11635 int ret, attachment_len;
11636 int read_len;
11637
11638 remote_buffer_add_string (&p, &left, "vFile:pread:");
11639
11640 remote_buffer_add_int (&p, &left, fd);
11641 remote_buffer_add_string (&p, &left, ",");
11642
11643 remote_buffer_add_int (&p, &left, len);
11644 remote_buffer_add_string (&p, &left, ",");
11645
11646 remote_buffer_add_int (&p, &left, offset);
11647
11648 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11649 remote_errno, &attachment,
11650 &attachment_len);
11651
11652 if (ret < 0)
11653 return ret;
11654
11655 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11656 read_buf, len);
11657 if (read_len != ret)
11658 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11659
11660 return ret;
11661}
11662
11663/* Serve pread from the readahead cache. Returns number of bytes
11664 read, or 0 if the request can't be served from the cache. */
11665
11666static int
11667remote_hostio_pread_from_cache (struct remote_state *rs,
11668 int fd, gdb_byte *read_buf, size_t len,
11669 ULONGEST offset)
11670{
11671 struct readahead_cache *cache = &rs->readahead_cache;
11672
11673 if (cache->fd == fd
11674 && cache->offset <= offset
11675 && offset < cache->offset + cache->bufsize)
11676 {
11677 ULONGEST max = cache->offset + cache->bufsize;
11678
11679 if (offset + len > max)
11680 len = max - offset;
11681
11682 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11683 return len;
11684 }
11685
11686 return 0;
11687}
11688
11689/* Implementation of to_fileio_pread. */
11690
11691static int
11692remote_hostio_pread (struct target_ops *self,
11693 int fd, gdb_byte *read_buf, int len,
11694 ULONGEST offset, int *remote_errno)
11695{
11696 int ret;
11697 struct remote_state *rs = get_remote_state ();
11698 struct readahead_cache *cache = &rs->readahead_cache;
11699
11700 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11701 if (ret > 0)
11702 {
11703 cache->hit_count++;
11704
11705 if (remote_debug)
11706 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11707 pulongest (cache->hit_count));
11708 return ret;
11709 }
11710
11711 cache->miss_count++;
11712 if (remote_debug)
11713 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11714 pulongest (cache->miss_count));
11715
11716 cache->fd = fd;
11717 cache->offset = offset;
11718 cache->bufsize = get_remote_packet_size ();
11719 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11720
11721 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11722 cache->offset, remote_errno);
11723 if (ret <= 0)
11724 {
11725 readahead_cache_invalidate_fd (fd);
11726 return ret;
11727 }
11728
11729 cache->bufsize = ret;
11730 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11731}
11732
11733/* Implementation of to_fileio_close. */
11734
11735static int
11736remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11737{
11738 struct remote_state *rs = get_remote_state ();
11739 char *p = rs->buf;
11740 int left = get_remote_packet_size () - 1;
11741
11742 readahead_cache_invalidate_fd (fd);
11743
11744 remote_buffer_add_string (&p, &left, "vFile:close:");
11745
11746 remote_buffer_add_int (&p, &left, fd);
11747
11748 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11749 remote_errno, NULL, NULL);
11750}
11751
11752/* Implementation of to_fileio_unlink. */
11753
11754static int
11755remote_hostio_unlink (struct target_ops *self,
11756 struct inferior *inf, const char *filename,
11757 int *remote_errno)
11758{
11759 struct remote_state *rs = get_remote_state ();
11760 char *p = rs->buf;
11761 int left = get_remote_packet_size () - 1;
11762
11763 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11764 return -1;
11765
11766 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11767
11768 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11769 strlen (filename));
11770
11771 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11772 remote_errno, NULL, NULL);
11773}
11774
11775/* Implementation of to_fileio_readlink. */
11776
11777static char *
11778remote_hostio_readlink (struct target_ops *self,
11779 struct inferior *inf, const char *filename,
11780 int *remote_errno)
11781{
11782 struct remote_state *rs = get_remote_state ();
11783 char *p = rs->buf;
11784 char *attachment;
11785 int left = get_remote_packet_size ();
11786 int len, attachment_len;
11787 int read_len;
11788 char *ret;
11789
11790 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11791 return NULL;
11792
11793 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11794
11795 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11796 strlen (filename));
11797
11798 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11799 remote_errno, &attachment,
11800 &attachment_len);
11801
11802 if (len < 0)
11803 return NULL;
11804
11805 ret = (char *) xmalloc (len + 1);
11806
11807 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11808 (gdb_byte *) ret, len);
11809 if (read_len != len)
11810 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11811
11812 ret[len] = '\0';
11813 return ret;
11814}
11815
11816/* Implementation of to_fileio_fstat. */
11817
11818static int
11819remote_hostio_fstat (struct target_ops *self,
11820 int fd, struct stat *st,
11821 int *remote_errno)
11822{
11823 struct remote_state *rs = get_remote_state ();
11824 char *p = rs->buf;
11825 int left = get_remote_packet_size ();
11826 int attachment_len, ret;
11827 char *attachment;
11828 struct fio_stat fst;
11829 int read_len;
11830
11831 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11832
11833 remote_buffer_add_int (&p, &left, fd);
11834
11835 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11836 remote_errno, &attachment,
11837 &attachment_len);
11838 if (ret < 0)
11839 {
11840 if (*remote_errno != FILEIO_ENOSYS)
11841 return ret;
11842
11843 /* Strictly we should return -1, ENOSYS here, but when
11844 "set sysroot remote:" was implemented in August 2008
11845 BFD's need for a stat function was sidestepped with
11846 this hack. This was not remedied until March 2015
11847 so we retain the previous behavior to avoid breaking
11848 compatibility.
11849
11850 Note that the memset is a March 2015 addition; older
11851 GDBs set st_size *and nothing else* so the structure
11852 would have garbage in all other fields. This might
11853 break something but retaining the previous behavior
11854 here would be just too wrong. */
11855
11856 memset (st, 0, sizeof (struct stat));
11857 st->st_size = INT_MAX;
11858 return 0;
11859 }
11860
11861 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11862 (gdb_byte *) &fst, sizeof (fst));
11863
11864 if (read_len != ret)
11865 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11866
11867 if (read_len != sizeof (fst))
11868 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11869 read_len, (int) sizeof (fst));
11870
11871 remote_fileio_to_host_stat (&fst, st);
11872
11873 return 0;
11874}
11875
11876/* Implementation of to_filesystem_is_local. */
11877
11878static int
11879remote_filesystem_is_local (struct target_ops *self)
11880{
11881 /* Valgrind GDB presents itself as a remote target but works
11882 on the local filesystem: it does not implement remote get
11883 and users are not expected to set a sysroot. To handle
11884 this case we treat the remote filesystem as local if the
11885 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11886 does not support vFile:open. */
11887 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11888 {
11889 enum packet_support ps = packet_support (PACKET_vFile_open);
11890
11891 if (ps == PACKET_SUPPORT_UNKNOWN)
11892 {
11893 int fd, remote_errno;
11894
11895 /* Try opening a file to probe support. The supplied
11896 filename is irrelevant, we only care about whether
11897 the stub recognizes the packet or not. */
11898 fd = remote_hostio_open (self, NULL, "just probing",
11899 FILEIO_O_RDONLY, 0700, 0,
11900 &remote_errno);
11901
11902 if (fd >= 0)
11903 remote_hostio_close (self, fd, &remote_errno);
11904
11905 ps = packet_support (PACKET_vFile_open);
11906 }
11907
11908 if (ps == PACKET_DISABLE)
11909 {
11910 static int warning_issued = 0;
11911
11912 if (!warning_issued)
11913 {
11914 warning (_("remote target does not support file"
11915 " transfer, attempting to access files"
11916 " from local filesystem."));
11917 warning_issued = 1;
11918 }
11919
11920 return 1;
11921 }
11922 }
11923
11924 return 0;
11925}
11926
11927static int
11928remote_fileio_errno_to_host (int errnum)
11929{
11930 switch (errnum)
11931 {
11932 case FILEIO_EPERM:
11933 return EPERM;
11934 case FILEIO_ENOENT:
11935 return ENOENT;
11936 case FILEIO_EINTR:
11937 return EINTR;
11938 case FILEIO_EIO:
11939 return EIO;
11940 case FILEIO_EBADF:
11941 return EBADF;
11942 case FILEIO_EACCES:
11943 return EACCES;
11944 case FILEIO_EFAULT:
11945 return EFAULT;
11946 case FILEIO_EBUSY:
11947 return EBUSY;
11948 case FILEIO_EEXIST:
11949 return EEXIST;
11950 case FILEIO_ENODEV:
11951 return ENODEV;
11952 case FILEIO_ENOTDIR:
11953 return ENOTDIR;
11954 case FILEIO_EISDIR:
11955 return EISDIR;
11956 case FILEIO_EINVAL:
11957 return EINVAL;
11958 case FILEIO_ENFILE:
11959 return ENFILE;
11960 case FILEIO_EMFILE:
11961 return EMFILE;
11962 case FILEIO_EFBIG:
11963 return EFBIG;
11964 case FILEIO_ENOSPC:
11965 return ENOSPC;
11966 case FILEIO_ESPIPE:
11967 return ESPIPE;
11968 case FILEIO_EROFS:
11969 return EROFS;
11970 case FILEIO_ENOSYS:
11971 return ENOSYS;
11972 case FILEIO_ENAMETOOLONG:
11973 return ENAMETOOLONG;
11974 }
11975 return -1;
11976}
11977
11978static char *
11979remote_hostio_error (int errnum)
11980{
11981 int host_error = remote_fileio_errno_to_host (errnum);
11982
11983 if (host_error == -1)
11984 error (_("Unknown remote I/O error %d"), errnum);
11985 else
11986 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11987}
11988
11989static void
11990remote_hostio_close_cleanup (void *opaque)
11991{
11992 int fd = *(int *) opaque;
11993 int remote_errno;
11994
11995 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11996}
11997
11998void
11999remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12000{
12001 struct cleanup *back_to, *close_cleanup;
12002 int retcode, fd, remote_errno, bytes, io_size;
12003 gdb_byte *buffer;
12004 int bytes_in_buffer;
12005 int saw_eof;
12006 ULONGEST offset;
12007 struct remote_state *rs = get_remote_state ();
12008
12009 if (!rs->remote_desc)
12010 error (_("command can only be used with remote target"));
12011
12012 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12013 if (file == NULL)
12014 perror_with_name (local_file);
12015
12016 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12017 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12018 | FILEIO_O_TRUNC),
12019 0700, 0, &remote_errno);
12020 if (fd == -1)
12021 remote_hostio_error (remote_errno);
12022
12023 /* Send up to this many bytes at once. They won't all fit in the
12024 remote packet limit, so we'll transfer slightly fewer. */
12025 io_size = get_remote_packet_size ();
12026 buffer = (gdb_byte *) xmalloc (io_size);
12027 back_to = make_cleanup (xfree, buffer);
12028
12029 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12030
12031 bytes_in_buffer = 0;
12032 saw_eof = 0;
12033 offset = 0;
12034 while (bytes_in_buffer || !saw_eof)
12035 {
12036 if (!saw_eof)
12037 {
12038 bytes = fread (buffer + bytes_in_buffer, 1,
12039 io_size - bytes_in_buffer,
12040 file.get ());
12041 if (bytes == 0)
12042 {
12043 if (ferror (file.get ()))
12044 error (_("Error reading %s."), local_file);
12045 else
12046 {
12047 /* EOF. Unless there is something still in the
12048 buffer from the last iteration, we are done. */
12049 saw_eof = 1;
12050 if (bytes_in_buffer == 0)
12051 break;
12052 }
12053 }
12054 }
12055 else
12056 bytes = 0;
12057
12058 bytes += bytes_in_buffer;
12059 bytes_in_buffer = 0;
12060
12061 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12062 fd, buffer, bytes,
12063 offset, &remote_errno);
12064
12065 if (retcode < 0)
12066 remote_hostio_error (remote_errno);
12067 else if (retcode == 0)
12068 error (_("Remote write of %d bytes returned 0!"), bytes);
12069 else if (retcode < bytes)
12070 {
12071 /* Short write. Save the rest of the read data for the next
12072 write. */
12073 bytes_in_buffer = bytes - retcode;
12074 memmove (buffer, buffer + retcode, bytes_in_buffer);
12075 }
12076
12077 offset += retcode;
12078 }
12079
12080 discard_cleanups (close_cleanup);
12081 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12082 remote_hostio_error (remote_errno);
12083
12084 if (from_tty)
12085 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12086 do_cleanups (back_to);
12087}
12088
12089void
12090remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12091{
12092 struct cleanup *back_to, *close_cleanup;
12093 int fd, remote_errno, bytes, io_size;
12094 gdb_byte *buffer;
12095 ULONGEST offset;
12096 struct remote_state *rs = get_remote_state ();
12097
12098 if (!rs->remote_desc)
12099 error (_("command can only be used with remote target"));
12100
12101 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12102 remote_file, FILEIO_O_RDONLY, 0, 0,
12103 &remote_errno);
12104 if (fd == -1)
12105 remote_hostio_error (remote_errno);
12106
12107 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12108 if (file == NULL)
12109 perror_with_name (local_file);
12110
12111 /* Send up to this many bytes at once. They won't all fit in the
12112 remote packet limit, so we'll transfer slightly fewer. */
12113 io_size = get_remote_packet_size ();
12114 buffer = (gdb_byte *) xmalloc (io_size);
12115 back_to = make_cleanup (xfree, buffer);
12116
12117 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12118
12119 offset = 0;
12120 while (1)
12121 {
12122 bytes = remote_hostio_pread (find_target_at (process_stratum),
12123 fd, buffer, io_size, offset, &remote_errno);
12124 if (bytes == 0)
12125 /* Success, but no bytes, means end-of-file. */
12126 break;
12127 if (bytes == -1)
12128 remote_hostio_error (remote_errno);
12129
12130 offset += bytes;
12131
12132 bytes = fwrite (buffer, 1, bytes, file.get ());
12133 if (bytes == 0)
12134 perror_with_name (local_file);
12135 }
12136
12137 discard_cleanups (close_cleanup);
12138 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12139 remote_hostio_error (remote_errno);
12140
12141 if (from_tty)
12142 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12143 do_cleanups (back_to);
12144}
12145
12146void
12147remote_file_delete (const char *remote_file, int from_tty)
12148{
12149 int retcode, remote_errno;
12150 struct remote_state *rs = get_remote_state ();
12151
12152 if (!rs->remote_desc)
12153 error (_("command can only be used with remote target"));
12154
12155 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12156 NULL, remote_file, &remote_errno);
12157 if (retcode == -1)
12158 remote_hostio_error (remote_errno);
12159
12160 if (from_tty)
12161 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12162}
12163
12164static void
12165remote_put_command (const char *args, int from_tty)
12166{
12167 if (args == NULL)
12168 error_no_arg (_("file to put"));
12169
12170 gdb_argv argv (args);
12171 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12172 error (_("Invalid parameters to remote put"));
12173
12174 remote_file_put (argv[0], argv[1], from_tty);
12175}
12176
12177static void
12178remote_get_command (const char *args, int from_tty)
12179{
12180 if (args == NULL)
12181 error_no_arg (_("file to get"));
12182
12183 gdb_argv argv (args);
12184 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12185 error (_("Invalid parameters to remote get"));
12186
12187 remote_file_get (argv[0], argv[1], from_tty);
12188}
12189
12190static void
12191remote_delete_command (const char *args, int from_tty)
12192{
12193 if (args == NULL)
12194 error_no_arg (_("file to delete"));
12195
12196 gdb_argv argv (args);
12197 if (argv[0] == NULL || argv[1] != NULL)
12198 error (_("Invalid parameters to remote delete"));
12199
12200 remote_file_delete (argv[0], from_tty);
12201}
12202
12203static void
12204remote_command (const char *args, int from_tty)
12205{
12206 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12207}
12208
12209static int
12210remote_can_execute_reverse (struct target_ops *self)
12211{
12212 if (packet_support (PACKET_bs) == PACKET_ENABLE
12213 || packet_support (PACKET_bc) == PACKET_ENABLE)
12214 return 1;
12215 else
12216 return 0;
12217}
12218
12219static int
12220remote_supports_non_stop (struct target_ops *self)
12221{
12222 return 1;
12223}
12224
12225static int
12226remote_supports_disable_randomization (struct target_ops *self)
12227{
12228 /* Only supported in extended mode. */
12229 return 0;
12230}
12231
12232static int
12233remote_supports_multi_process (struct target_ops *self)
12234{
12235 struct remote_state *rs = get_remote_state ();
12236
12237 return remote_multi_process_p (rs);
12238}
12239
12240static int
12241remote_supports_cond_tracepoints (void)
12242{
12243 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12244}
12245
12246static int
12247remote_supports_cond_breakpoints (struct target_ops *self)
12248{
12249 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12250}
12251
12252static int
12253remote_supports_fast_tracepoints (void)
12254{
12255 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12256}
12257
12258static int
12259remote_supports_static_tracepoints (void)
12260{
12261 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12262}
12263
12264static int
12265remote_supports_install_in_trace (void)
12266{
12267 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12268}
12269
12270static int
12271remote_supports_enable_disable_tracepoint (struct target_ops *self)
12272{
12273 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12274 == PACKET_ENABLE);
12275}
12276
12277static int
12278remote_supports_string_tracing (struct target_ops *self)
12279{
12280 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12281}
12282
12283static int
12284remote_can_run_breakpoint_commands (struct target_ops *self)
12285{
12286 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12287}
12288
12289static void
12290remote_trace_init (struct target_ops *self)
12291{
12292 struct remote_state *rs = get_remote_state ();
12293
12294 putpkt ("QTinit");
12295 remote_get_noisy_reply ();
12296 if (strcmp (rs->buf, "OK") != 0)
12297 error (_("Target does not support this command."));
12298}
12299
12300static void free_actions_list (char **actions_list);
12301static void free_actions_list_cleanup_wrapper (void *);
12302static void
12303free_actions_list_cleanup_wrapper (void *al)
12304{
12305 free_actions_list ((char **) al);
12306}
12307
12308static void
12309free_actions_list (char **actions_list)
12310{
12311 int ndx;
12312
12313 if (actions_list == 0)
12314 return;
12315
12316 for (ndx = 0; actions_list[ndx]; ndx++)
12317 xfree (actions_list[ndx]);
12318
12319 xfree (actions_list);
12320}
12321
12322/* Recursive routine to walk through command list including loops, and
12323 download packets for each command. */
12324
12325static void
12326remote_download_command_source (int num, ULONGEST addr,
12327 struct command_line *cmds)
12328{
12329 struct remote_state *rs = get_remote_state ();
12330 struct command_line *cmd;
12331
12332 for (cmd = cmds; cmd; cmd = cmd->next)
12333 {
12334 QUIT; /* Allow user to bail out with ^C. */
12335 strcpy (rs->buf, "QTDPsrc:");
12336 encode_source_string (num, addr, "cmd", cmd->line,
12337 rs->buf + strlen (rs->buf),
12338 rs->buf_size - strlen (rs->buf));
12339 putpkt (rs->buf);
12340 remote_get_noisy_reply ();
12341 if (strcmp (rs->buf, "OK"))
12342 warning (_("Target does not support source download."));
12343
12344 if (cmd->control_type == while_control
12345 || cmd->control_type == while_stepping_control)
12346 {
12347 remote_download_command_source (num, addr, *cmd->body_list);
12348
12349 QUIT; /* Allow user to bail out with ^C. */
12350 strcpy (rs->buf, "QTDPsrc:");
12351 encode_source_string (num, addr, "cmd", "end",
12352 rs->buf + strlen (rs->buf),
12353 rs->buf_size - strlen (rs->buf));
12354 putpkt (rs->buf);
12355 remote_get_noisy_reply ();
12356 if (strcmp (rs->buf, "OK"))
12357 warning (_("Target does not support source download."));
12358 }
12359 }
12360}
12361
12362static void
12363remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
12364{
12365#define BUF_SIZE 2048
12366
12367 CORE_ADDR tpaddr;
12368 char addrbuf[40];
12369 char buf[BUF_SIZE];
12370 char **tdp_actions;
12371 char **stepping_actions;
12372 int ndx;
12373 struct cleanup *old_chain = NULL;
12374 char *pkt;
12375 struct breakpoint *b = loc->owner;
12376 struct tracepoint *t = (struct tracepoint *) b;
12377 struct remote_state *rs = get_remote_state ();
12378
12379 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12380 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
12381 tdp_actions);
12382 (void) make_cleanup (free_actions_list_cleanup_wrapper,
12383 stepping_actions);
12384
12385 tpaddr = loc->address;
12386 sprintf_vma (addrbuf, tpaddr);
12387 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12388 addrbuf, /* address */
12389 (b->enable_state == bp_enabled ? 'E' : 'D'),
12390 t->step_count, t->pass_count);
12391 /* Fast tracepoints are mostly handled by the target, but we can
12392 tell the target how big of an instruction block should be moved
12393 around. */
12394 if (b->type == bp_fast_tracepoint)
12395 {
12396 /* Only test for support at download time; we may not know
12397 target capabilities at definition time. */
12398 if (remote_supports_fast_tracepoints ())
12399 {
12400 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12401 NULL))
12402 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12403 gdb_insn_length (loc->gdbarch, tpaddr));
12404 else
12405 /* If it passed validation at definition but fails now,
12406 something is very wrong. */
12407 internal_error (__FILE__, __LINE__,
12408 _("Fast tracepoint not "
12409 "valid during download"));
12410 }
12411 else
12412 /* Fast tracepoints are functionally identical to regular
12413 tracepoints, so don't take lack of support as a reason to
12414 give up on the trace run. */
12415 warning (_("Target does not support fast tracepoints, "
12416 "downloading %d as regular tracepoint"), b->number);
12417 }
12418 else if (b->type == bp_static_tracepoint)
12419 {
12420 /* Only test for support at download time; we may not know
12421 target capabilities at definition time. */
12422 if (remote_supports_static_tracepoints ())
12423 {
12424 struct static_tracepoint_marker marker;
12425
12426 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12427 strcat (buf, ":S");
12428 else
12429 error (_("Static tracepoint not valid during download"));
12430 }
12431 else
12432 /* Fast tracepoints are functionally identical to regular
12433 tracepoints, so don't take lack of support as a reason
12434 to give up on the trace run. */
12435 error (_("Target does not support static tracepoints"));
12436 }
12437 /* If the tracepoint has a conditional, make it into an agent
12438 expression and append to the definition. */
12439 if (loc->cond)
12440 {
12441 /* Only test support at download time, we may not know target
12442 capabilities at definition time. */
12443 if (remote_supports_cond_tracepoints ())
12444 {
12445 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12446 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12447 aexpr->len);
12448 pkt = buf + strlen (buf);
12449 for (ndx = 0; ndx < aexpr->len; ++ndx)
12450 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12451 *pkt = '\0';
12452 }
12453 else
12454 warning (_("Target does not support conditional tracepoints, "
12455 "ignoring tp %d cond"), b->number);
12456 }
12457
12458 if (b->commands || *default_collect)
12459 strcat (buf, "-");
12460 putpkt (buf);
12461 remote_get_noisy_reply ();
12462 if (strcmp (rs->buf, "OK"))
12463 error (_("Target does not support tracepoints."));
12464
12465 /* do_single_steps (t); */
12466 if (tdp_actions)
12467 {
12468 for (ndx = 0; tdp_actions[ndx]; ndx++)
12469 {
12470 QUIT; /* Allow user to bail out with ^C. */
12471 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12472 b->number, addrbuf, /* address */
12473 tdp_actions[ndx],
12474 ((tdp_actions[ndx + 1] || stepping_actions)
12475 ? '-' : 0));
12476 putpkt (buf);
12477 remote_get_noisy_reply ();
12478 if (strcmp (rs->buf, "OK"))
12479 error (_("Error on target while setting tracepoints."));
12480 }
12481 }
12482 if (stepping_actions)
12483 {
12484 for (ndx = 0; stepping_actions[ndx]; ndx++)
12485 {
12486 QUIT; /* Allow user to bail out with ^C. */
12487 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12488 b->number, addrbuf, /* address */
12489 ((ndx == 0) ? "S" : ""),
12490 stepping_actions[ndx],
12491 (stepping_actions[ndx + 1] ? "-" : ""));
12492 putpkt (buf);
12493 remote_get_noisy_reply ();
12494 if (strcmp (rs->buf, "OK"))
12495 error (_("Error on target while setting tracepoints."));
12496 }
12497 }
12498
12499 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12500 {
12501 if (b->location != NULL)
12502 {
12503 strcpy (buf, "QTDPsrc:");
12504 encode_source_string (b->number, loc->address, "at",
12505 event_location_to_string (b->location.get ()),
12506 buf + strlen (buf), 2048 - strlen (buf));
12507 putpkt (buf);
12508 remote_get_noisy_reply ();
12509 if (strcmp (rs->buf, "OK"))
12510 warning (_("Target does not support source download."));
12511 }
12512 if (b->cond_string)
12513 {
12514 strcpy (buf, "QTDPsrc:");
12515 encode_source_string (b->number, loc->address,
12516 "cond", b->cond_string, buf + strlen (buf),
12517 2048 - strlen (buf));
12518 putpkt (buf);
12519 remote_get_noisy_reply ();
12520 if (strcmp (rs->buf, "OK"))
12521 warning (_("Target does not support source download."));
12522 }
12523 remote_download_command_source (b->number, loc->address,
12524 breakpoint_commands (b));
12525 }
12526
12527 do_cleanups (old_chain);
12528}
12529
12530static int
12531remote_can_download_tracepoint (struct target_ops *self)
12532{
12533 struct remote_state *rs = get_remote_state ();
12534 struct trace_status *ts;
12535 int status;
12536
12537 /* Don't try to install tracepoints until we've relocated our
12538 symbols, and fetched and merged the target's tracepoint list with
12539 ours. */
12540 if (rs->starting_up)
12541 return 0;
12542
12543 ts = current_trace_status ();
12544 status = remote_get_trace_status (self, ts);
12545
12546 if (status == -1 || !ts->running_known || !ts->running)
12547 return 0;
12548
12549 /* If we are in a tracing experiment, but remote stub doesn't support
12550 installing tracepoint in trace, we have to return. */
12551 if (!remote_supports_install_in_trace ())
12552 return 0;
12553
12554 return 1;
12555}
12556
12557
12558static void
12559remote_download_trace_state_variable (struct target_ops *self,
12560 struct trace_state_variable *tsv)
12561{
12562 struct remote_state *rs = get_remote_state ();
12563 char *p;
12564
12565 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12566 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12567 tsv->builtin);
12568 p = rs->buf + strlen (rs->buf);
12569 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12570 error (_("Trace state variable name too long for tsv definition packet"));
12571 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12572 *p++ = '\0';
12573 putpkt (rs->buf);
12574 remote_get_noisy_reply ();
12575 if (*rs->buf == '\0')
12576 error (_("Target does not support this command."));
12577 if (strcmp (rs->buf, "OK") != 0)
12578 error (_("Error on target while downloading trace state variable."));
12579}
12580
12581static void
12582remote_enable_tracepoint (struct target_ops *self,
12583 struct bp_location *location)
12584{
12585 struct remote_state *rs = get_remote_state ();
12586 char addr_buf[40];
12587
12588 sprintf_vma (addr_buf, location->address);
12589 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12590 location->owner->number, addr_buf);
12591 putpkt (rs->buf);
12592 remote_get_noisy_reply ();
12593 if (*rs->buf == '\0')
12594 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12595 if (strcmp (rs->buf, "OK") != 0)
12596 error (_("Error on target while enabling tracepoint."));
12597}
12598
12599static void
12600remote_disable_tracepoint (struct target_ops *self,
12601 struct bp_location *location)
12602{
12603 struct remote_state *rs = get_remote_state ();
12604 char addr_buf[40];
12605
12606 sprintf_vma (addr_buf, location->address);
12607 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12608 location->owner->number, addr_buf);
12609 putpkt (rs->buf);
12610 remote_get_noisy_reply ();
12611 if (*rs->buf == '\0')
12612 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12613 if (strcmp (rs->buf, "OK") != 0)
12614 error (_("Error on target while disabling tracepoint."));
12615}
12616
12617static void
12618remote_trace_set_readonly_regions (struct target_ops *self)
12619{
12620 asection *s;
12621 bfd *abfd = NULL;
12622 bfd_size_type size;
12623 bfd_vma vma;
12624 int anysecs = 0;
12625 int offset = 0;
12626
12627 if (!exec_bfd)
12628 return; /* No information to give. */
12629
12630 struct remote_state *rs = get_remote_state ();
12631
12632 strcpy (rs->buf, "QTro");
12633 offset = strlen (rs->buf);
12634 for (s = exec_bfd->sections; s; s = s->next)
12635 {
12636 char tmp1[40], tmp2[40];
12637 int sec_length;
12638
12639 if ((s->flags & SEC_LOAD) == 0 ||
12640 /* (s->flags & SEC_CODE) == 0 || */
12641 (s->flags & SEC_READONLY) == 0)
12642 continue;
12643
12644 anysecs = 1;
12645 vma = bfd_get_section_vma (abfd, s);
12646 size = bfd_get_section_size (s);
12647 sprintf_vma (tmp1, vma);
12648 sprintf_vma (tmp2, vma + size);
12649 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12650 if (offset + sec_length + 1 > rs->buf_size)
12651 {
12652 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12653 warning (_("\
12654Too many sections for read-only sections definition packet."));
12655 break;
12656 }
12657 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12658 tmp1, tmp2);
12659 offset += sec_length;
12660 }
12661 if (anysecs)
12662 {
12663 putpkt (rs->buf);
12664 getpkt (&rs->buf, &rs->buf_size, 0);
12665 }
12666}
12667
12668static void
12669remote_trace_start (struct target_ops *self)
12670{
12671 struct remote_state *rs = get_remote_state ();
12672
12673 putpkt ("QTStart");
12674 remote_get_noisy_reply ();
12675 if (*rs->buf == '\0')
12676 error (_("Target does not support this command."));
12677 if (strcmp (rs->buf, "OK") != 0)
12678 error (_("Bogus reply from target: %s"), rs->buf);
12679}
12680
12681static int
12682remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12683{
12684 /* Initialize it just to avoid a GCC false warning. */
12685 char *p = NULL;
12686 /* FIXME we need to get register block size some other way. */
12687 extern int trace_regblock_size;
12688 enum packet_result result;
12689 struct remote_state *rs = get_remote_state ();
12690
12691 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12692 return -1;
12693
12694 trace_regblock_size
12695 = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12696
12697 putpkt ("qTStatus");
12698
12699 TRY
12700 {
12701 p = remote_get_noisy_reply ();
12702 }
12703 CATCH (ex, RETURN_MASK_ERROR)
12704 {
12705 if (ex.error != TARGET_CLOSE_ERROR)
12706 {
12707 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12708 return -1;
12709 }
12710 throw_exception (ex);
12711 }
12712 END_CATCH
12713
12714 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12715
12716 /* If the remote target doesn't do tracing, flag it. */
12717 if (result == PACKET_UNKNOWN)
12718 return -1;
12719
12720 /* We're working with a live target. */
12721 ts->filename = NULL;
12722
12723 if (*p++ != 'T')
12724 error (_("Bogus trace status reply from target: %s"), rs->buf);
12725
12726 /* Function 'parse_trace_status' sets default value of each field of
12727 'ts' at first, so we don't have to do it here. */
12728 parse_trace_status (p, ts);
12729
12730 return ts->running;
12731}
12732
12733static void
12734remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12735 struct uploaded_tp *utp)
12736{
12737 struct remote_state *rs = get_remote_state ();
12738 char *reply;
12739 struct bp_location *loc;
12740 struct tracepoint *tp = (struct tracepoint *) bp;
12741 size_t size = get_remote_packet_size ();
12742
12743 if (tp)
12744 {
12745 tp->hit_count = 0;
12746 tp->traceframe_usage = 0;
12747 for (loc = tp->loc; loc; loc = loc->next)
12748 {
12749 /* If the tracepoint was never downloaded, don't go asking for
12750 any status. */
12751 if (tp->number_on_target == 0)
12752 continue;
12753 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12754 phex_nz (loc->address, 0));
12755 putpkt (rs->buf);
12756 reply = remote_get_noisy_reply ();
12757 if (reply && *reply)
12758 {
12759 if (*reply == 'V')
12760 parse_tracepoint_status (reply + 1, bp, utp);
12761 }
12762 }
12763 }
12764 else if (utp)
12765 {
12766 utp->hit_count = 0;
12767 utp->traceframe_usage = 0;
12768 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12769 phex_nz (utp->addr, 0));
12770 putpkt (rs->buf);
12771 reply = remote_get_noisy_reply ();
12772 if (reply && *reply)
12773 {
12774 if (*reply == 'V')
12775 parse_tracepoint_status (reply + 1, bp, utp);
12776 }
12777 }
12778}
12779
12780static void
12781remote_trace_stop (struct target_ops *self)
12782{
12783 struct remote_state *rs = get_remote_state ();
12784
12785 putpkt ("QTStop");
12786 remote_get_noisy_reply ();
12787 if (*rs->buf == '\0')
12788 error (_("Target does not support this command."));
12789 if (strcmp (rs->buf, "OK") != 0)
12790 error (_("Bogus reply from target: %s"), rs->buf);
12791}
12792
12793static int
12794remote_trace_find (struct target_ops *self,
12795 enum trace_find_type type, int num,
12796 CORE_ADDR addr1, CORE_ADDR addr2,
12797 int *tpp)
12798{
12799 struct remote_state *rs = get_remote_state ();
12800 char *endbuf = rs->buf + get_remote_packet_size ();
12801 char *p, *reply;
12802 int target_frameno = -1, target_tracept = -1;
12803
12804 /* Lookups other than by absolute frame number depend on the current
12805 trace selected, so make sure it is correct on the remote end
12806 first. */
12807 if (type != tfind_number)
12808 set_remote_traceframe ();
12809
12810 p = rs->buf;
12811 strcpy (p, "QTFrame:");
12812 p = strchr (p, '\0');
12813 switch (type)
12814 {
12815 case tfind_number:
12816 xsnprintf (p, endbuf - p, "%x", num);
12817 break;
12818 case tfind_pc:
12819 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12820 break;
12821 case tfind_tp:
12822 xsnprintf (p, endbuf - p, "tdp:%x", num);
12823 break;
12824 case tfind_range:
12825 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12826 phex_nz (addr2, 0));
12827 break;
12828 case tfind_outside:
12829 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12830 phex_nz (addr2, 0));
12831 break;
12832 default:
12833 error (_("Unknown trace find type %d"), type);
12834 }
12835
12836 putpkt (rs->buf);
12837 reply = remote_get_noisy_reply ();
12838 if (*reply == '\0')
12839 error (_("Target does not support this command."));
12840
12841 while (reply && *reply)
12842 switch (*reply)
12843 {
12844 case 'F':
12845 p = ++reply;
12846 target_frameno = (int) strtol (p, &reply, 16);
12847 if (reply == p)
12848 error (_("Unable to parse trace frame number"));
12849 /* Don't update our remote traceframe number cache on failure
12850 to select a remote traceframe. */
12851 if (target_frameno == -1)
12852 return -1;
12853 break;
12854 case 'T':
12855 p = ++reply;
12856 target_tracept = (int) strtol (p, &reply, 16);
12857 if (reply == p)
12858 error (_("Unable to parse tracepoint number"));
12859 break;
12860 case 'O': /* "OK"? */
12861 if (reply[1] == 'K' && reply[2] == '\0')
12862 reply += 2;
12863 else
12864 error (_("Bogus reply from target: %s"), reply);
12865 break;
12866 default:
12867 error (_("Bogus reply from target: %s"), reply);
12868 }
12869 if (tpp)
12870 *tpp = target_tracept;
12871
12872 rs->remote_traceframe_number = target_frameno;
12873 return target_frameno;
12874}
12875
12876static int
12877remote_get_trace_state_variable_value (struct target_ops *self,
12878 int tsvnum, LONGEST *val)
12879{
12880 struct remote_state *rs = get_remote_state ();
12881 char *reply;
12882 ULONGEST uval;
12883
12884 set_remote_traceframe ();
12885
12886 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12887 putpkt (rs->buf);
12888 reply = remote_get_noisy_reply ();
12889 if (reply && *reply)
12890 {
12891 if (*reply == 'V')
12892 {
12893 unpack_varlen_hex (reply + 1, &uval);
12894 *val = (LONGEST) uval;
12895 return 1;
12896 }
12897 }
12898 return 0;
12899}
12900
12901static int
12902remote_save_trace_data (struct target_ops *self, const char *filename)
12903{
12904 struct remote_state *rs = get_remote_state ();
12905 char *p, *reply;
12906
12907 p = rs->buf;
12908 strcpy (p, "QTSave:");
12909 p += strlen (p);
12910 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12911 error (_("Remote file name too long for trace save packet"));
12912 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12913 *p++ = '\0';
12914 putpkt (rs->buf);
12915 reply = remote_get_noisy_reply ();
12916 if (*reply == '\0')
12917 error (_("Target does not support this command."));
12918 if (strcmp (reply, "OK") != 0)
12919 error (_("Bogus reply from target: %s"), reply);
12920 return 0;
12921}
12922
12923/* This is basically a memory transfer, but needs to be its own packet
12924 because we don't know how the target actually organizes its trace
12925 memory, plus we want to be able to ask for as much as possible, but
12926 not be unhappy if we don't get as much as we ask for. */
12927
12928static LONGEST
12929remote_get_raw_trace_data (struct target_ops *self,
12930 gdb_byte *buf, ULONGEST offset, LONGEST len)
12931{
12932 struct remote_state *rs = get_remote_state ();
12933 char *reply;
12934 char *p;
12935 int rslt;
12936
12937 p = rs->buf;
12938 strcpy (p, "qTBuffer:");
12939 p += strlen (p);
12940 p += hexnumstr (p, offset);
12941 *p++ = ',';
12942 p += hexnumstr (p, len);
12943 *p++ = '\0';
12944
12945 putpkt (rs->buf);
12946 reply = remote_get_noisy_reply ();
12947 if (reply && *reply)
12948 {
12949 /* 'l' by itself means we're at the end of the buffer and
12950 there is nothing more to get. */
12951 if (*reply == 'l')
12952 return 0;
12953
12954 /* Convert the reply into binary. Limit the number of bytes to
12955 convert according to our passed-in buffer size, rather than
12956 what was returned in the packet; if the target is
12957 unexpectedly generous and gives us a bigger reply than we
12958 asked for, we don't want to crash. */
12959 rslt = hex2bin (reply, buf, len);
12960 return rslt;
12961 }
12962
12963 /* Something went wrong, flag as an error. */
12964 return -1;
12965}
12966
12967static void
12968remote_set_disconnected_tracing (struct target_ops *self, int val)
12969{
12970 struct remote_state *rs = get_remote_state ();
12971
12972 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12973 {
12974 char *reply;
12975
12976 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12977 putpkt (rs->buf);
12978 reply = remote_get_noisy_reply ();
12979 if (*reply == '\0')
12980 error (_("Target does not support this command."));
12981 if (strcmp (reply, "OK") != 0)
12982 error (_("Bogus reply from target: %s"), reply);
12983 }
12984 else if (val)
12985 warning (_("Target does not support disconnected tracing."));
12986}
12987
12988static int
12989remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12990{
12991 struct thread_info *info = find_thread_ptid (ptid);
12992
12993 if (info && info->priv)
12994 return info->priv->core;
12995 return -1;
12996}
12997
12998static void
12999remote_set_circular_trace_buffer (struct target_ops *self, int val)
13000{
13001 struct remote_state *rs = get_remote_state ();
13002 char *reply;
13003
13004 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13005 putpkt (rs->buf);
13006 reply = remote_get_noisy_reply ();
13007 if (*reply == '\0')
13008 error (_("Target does not support this command."));
13009 if (strcmp (reply, "OK") != 0)
13010 error (_("Bogus reply from target: %s"), reply);
13011}
13012
13013static traceframe_info_up
13014remote_traceframe_info (struct target_ops *self)
13015{
13016 gdb::unique_xmalloc_ptr<char> text
13017 = target_read_stralloc (&current_target, TARGET_OBJECT_TRACEFRAME_INFO,
13018 NULL);
13019 if (text != NULL)
13020 return parse_traceframe_info (text.get ());
13021
13022 return NULL;
13023}
13024
13025/* Handle the qTMinFTPILen packet. Returns the minimum length of
13026 instruction on which a fast tracepoint may be placed. Returns -1
13027 if the packet is not supported, and 0 if the minimum instruction
13028 length is unknown. */
13029
13030static int
13031remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
13032{
13033 struct remote_state *rs = get_remote_state ();
13034 char *reply;
13035
13036 /* If we're not debugging a process yet, the IPA can't be
13037 loaded. */
13038 if (!target_has_execution)
13039 return 0;
13040
13041 /* Make sure the remote is pointing at the right process. */
13042 set_general_process ();
13043
13044 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13045 putpkt (rs->buf);
13046 reply = remote_get_noisy_reply ();
13047 if (*reply == '\0')
13048 return -1;
13049 else
13050 {
13051 ULONGEST min_insn_len;
13052
13053 unpack_varlen_hex (reply, &min_insn_len);
13054
13055 return (int) min_insn_len;
13056 }
13057}
13058
13059static void
13060remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
13061{
13062 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13063 {
13064 struct remote_state *rs = get_remote_state ();
13065 char *buf = rs->buf;
13066 char *endbuf = rs->buf + get_remote_packet_size ();
13067 enum packet_result result;
13068
13069 gdb_assert (val >= 0 || val == -1);
13070 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13071 /* Send -1 as literal "-1" to avoid host size dependency. */
13072 if (val < 0)
13073 {
13074 *buf++ = '-';
13075 buf += hexnumstr (buf, (ULONGEST) -val);
13076 }
13077 else
13078 buf += hexnumstr (buf, (ULONGEST) val);
13079
13080 putpkt (rs->buf);
13081 remote_get_noisy_reply ();
13082 result = packet_ok (rs->buf,
13083 &remote_protocol_packets[PACKET_QTBuffer_size]);
13084
13085 if (result != PACKET_OK)
13086 warning (_("Bogus reply from target: %s"), rs->buf);
13087 }
13088}
13089
13090static int
13091remote_set_trace_notes (struct target_ops *self,
13092 const char *user, const char *notes,
13093 const char *stop_notes)
13094{
13095 struct remote_state *rs = get_remote_state ();
13096 char *reply;
13097 char *buf = rs->buf;
13098 char *endbuf = rs->buf + get_remote_packet_size ();
13099 int nbytes;
13100
13101 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13102 if (user)
13103 {
13104 buf += xsnprintf (buf, endbuf - buf, "user:");
13105 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13106 buf += 2 * nbytes;
13107 *buf++ = ';';
13108 }
13109 if (notes)
13110 {
13111 buf += xsnprintf (buf, endbuf - buf, "notes:");
13112 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13113 buf += 2 * nbytes;
13114 *buf++ = ';';
13115 }
13116 if (stop_notes)
13117 {
13118 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13119 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13120 buf += 2 * nbytes;
13121 *buf++ = ';';
13122 }
13123 /* Ensure the buffer is terminated. */
13124 *buf = '\0';
13125
13126 putpkt (rs->buf);
13127 reply = remote_get_noisy_reply ();
13128 if (*reply == '\0')
13129 return 0;
13130
13131 if (strcmp (reply, "OK") != 0)
13132 error (_("Bogus reply from target: %s"), reply);
13133
13134 return 1;
13135}
13136
13137static int
13138remote_use_agent (struct target_ops *self, int use)
13139{
13140 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13141 {
13142 struct remote_state *rs = get_remote_state ();
13143
13144 /* If the stub supports QAgent. */
13145 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13146 putpkt (rs->buf);
13147 getpkt (&rs->buf, &rs->buf_size, 0);
13148
13149 if (strcmp (rs->buf, "OK") == 0)
13150 {
13151 use_agent = use;
13152 return 1;
13153 }
13154 }
13155
13156 return 0;
13157}
13158
13159static int
13160remote_can_use_agent (struct target_ops *self)
13161{
13162 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13163}
13164
13165struct btrace_target_info
13166{
13167 /* The ptid of the traced thread. */
13168 ptid_t ptid;
13169
13170 /* The obtained branch trace configuration. */
13171 struct btrace_config conf;
13172};
13173
13174/* Reset our idea of our target's btrace configuration. */
13175
13176static void
13177remote_btrace_reset (void)
13178{
13179 struct remote_state *rs = get_remote_state ();
13180
13181 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13182}
13183
13184/* Check whether the target supports branch tracing. */
13185
13186static int
13187remote_supports_btrace (struct target_ops *self, enum btrace_format format)
13188{
13189 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
13190 return 0;
13191 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
13192 return 0;
13193
13194 switch (format)
13195 {
13196 case BTRACE_FORMAT_NONE:
13197 return 0;
13198
13199 case BTRACE_FORMAT_BTS:
13200 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
13201
13202 case BTRACE_FORMAT_PT:
13203 /* The trace is decoded on the host. Even if our target supports it,
13204 we still need to have libipt to decode the trace. */
13205#if defined (HAVE_LIBIPT)
13206 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
13207#else /* !defined (HAVE_LIBIPT) */
13208 return 0;
13209#endif /* !defined (HAVE_LIBIPT) */
13210 }
13211
13212 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
13213}
13214
13215/* Synchronize the configuration with the target. */
13216
13217static void
13218btrace_sync_conf (const struct btrace_config *conf)
13219{
13220 struct packet_config *packet;
13221 struct remote_state *rs;
13222 char *buf, *pos, *endbuf;
13223
13224 rs = get_remote_state ();
13225 buf = rs->buf;
13226 endbuf = buf + get_remote_packet_size ();
13227
13228 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13229 if (packet_config_support (packet) == PACKET_ENABLE
13230 && conf->bts.size != rs->btrace_config.bts.size)
13231 {
13232 pos = buf;
13233 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13234 conf->bts.size);
13235
13236 putpkt (buf);
13237 getpkt (&buf, &rs->buf_size, 0);
13238
13239 if (packet_ok (buf, packet) == PACKET_ERROR)
13240 {
13241 if (buf[0] == 'E' && buf[1] == '.')
13242 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13243 else
13244 error (_("Failed to configure the BTS buffer size."));
13245 }
13246
13247 rs->btrace_config.bts.size = conf->bts.size;
13248 }
13249
13250 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13251 if (packet_config_support (packet) == PACKET_ENABLE
13252 && conf->pt.size != rs->btrace_config.pt.size)
13253 {
13254 pos = buf;
13255 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13256 conf->pt.size);
13257
13258 putpkt (buf);
13259 getpkt (&buf, &rs->buf_size, 0);
13260
13261 if (packet_ok (buf, packet) == PACKET_ERROR)
13262 {
13263 if (buf[0] == 'E' && buf[1] == '.')
13264 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13265 else
13266 error (_("Failed to configure the trace buffer size."));
13267 }
13268
13269 rs->btrace_config.pt.size = conf->pt.size;
13270 }
13271}
13272
13273/* Read the current thread's btrace configuration from the target and
13274 store it into CONF. */
13275
13276static void
13277btrace_read_config (struct btrace_config *conf)
13278{
13279 gdb::unique_xmalloc_ptr<char> xml
13280 = target_read_stralloc (&current_target, TARGET_OBJECT_BTRACE_CONF, "");
13281 if (xml != NULL)
13282 parse_xml_btrace_conf (conf, xml.get ());
13283}
13284
13285/* Maybe reopen target btrace. */
13286
13287static void
13288remote_btrace_maybe_reopen (void)
13289{
13290 struct remote_state *rs = get_remote_state ();
13291 struct thread_info *tp;
13292 int btrace_target_pushed = 0;
13293 int warned = 0;
13294
13295 scoped_restore_current_thread restore_thread;
13296
13297 ALL_NON_EXITED_THREADS (tp)
13298 {
13299 set_general_thread (tp->ptid);
13300
13301 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13302 btrace_read_config (&rs->btrace_config);
13303
13304 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13305 continue;
13306
13307#if !defined (HAVE_LIBIPT)
13308 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13309 {
13310 if (!warned)
13311 {
13312 warned = 1;
13313 warning (_("GDB does not support Intel Processor Trace. "
13314 "\"record\" will not work in this session."));
13315 }
13316
13317 continue;
13318 }
13319#endif /* !defined (HAVE_LIBIPT) */
13320
13321 /* Push target, once, but before anything else happens. This way our
13322 changes to the threads will be cleaned up by unpushing the target
13323 in case btrace_read_config () throws. */
13324 if (!btrace_target_pushed)
13325 {
13326 btrace_target_pushed = 1;
13327 record_btrace_push_target ();
13328 printf_filtered (_("Target is recording using %s.\n"),
13329 btrace_format_string (rs->btrace_config.format));
13330 }
13331
13332 tp->btrace.target = XCNEW (struct btrace_target_info);
13333 tp->btrace.target->ptid = tp->ptid;
13334 tp->btrace.target->conf = rs->btrace_config;
13335 }
13336}
13337
13338/* Enable branch tracing. */
13339
13340static struct btrace_target_info *
13341remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13342 const struct btrace_config *conf)
13343{
13344 struct btrace_target_info *tinfo = NULL;
13345 struct packet_config *packet = NULL;
13346 struct remote_state *rs = get_remote_state ();
13347 char *buf = rs->buf;
13348 char *endbuf = rs->buf + get_remote_packet_size ();
13349
13350 switch (conf->format)
13351 {
13352 case BTRACE_FORMAT_BTS:
13353 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13354 break;
13355
13356 case BTRACE_FORMAT_PT:
13357 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13358 break;
13359 }
13360
13361 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13362 error (_("Target does not support branch tracing."));
13363
13364 btrace_sync_conf (conf);
13365
13366 set_general_thread (ptid);
13367
13368 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13369 putpkt (rs->buf);
13370 getpkt (&rs->buf, &rs->buf_size, 0);
13371
13372 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13373 {
13374 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13375 error (_("Could not enable branch tracing for %s: %s"),
13376 target_pid_to_str (ptid), rs->buf + 2);
13377 else
13378 error (_("Could not enable branch tracing for %s."),
13379 target_pid_to_str (ptid));
13380 }
13381
13382 tinfo = XCNEW (struct btrace_target_info);
13383 tinfo->ptid = ptid;
13384
13385 /* If we fail to read the configuration, we lose some information, but the
13386 tracing itself is not impacted. */
13387 TRY
13388 {
13389 btrace_read_config (&tinfo->conf);
13390 }
13391 CATCH (err, RETURN_MASK_ERROR)
13392 {
13393 if (err.message != NULL)
13394 warning ("%s", err.message);
13395 }
13396 END_CATCH
13397
13398 return tinfo;
13399}
13400
13401/* Disable branch tracing. */
13402
13403static void
13404remote_disable_btrace (struct target_ops *self,
13405 struct btrace_target_info *tinfo)
13406{
13407 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13408 struct remote_state *rs = get_remote_state ();
13409 char *buf = rs->buf;
13410 char *endbuf = rs->buf + get_remote_packet_size ();
13411
13412 if (packet_config_support (packet) != PACKET_ENABLE)
13413 error (_("Target does not support branch tracing."));
13414
13415 set_general_thread (tinfo->ptid);
13416
13417 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13418 putpkt (rs->buf);
13419 getpkt (&rs->buf, &rs->buf_size, 0);
13420
13421 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13422 {
13423 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13424 error (_("Could not disable branch tracing for %s: %s"),
13425 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13426 else
13427 error (_("Could not disable branch tracing for %s."),
13428 target_pid_to_str (tinfo->ptid));
13429 }
13430
13431 xfree (tinfo);
13432}
13433
13434/* Teardown branch tracing. */
13435
13436static void
13437remote_teardown_btrace (struct target_ops *self,
13438 struct btrace_target_info *tinfo)
13439{
13440 /* We must not talk to the target during teardown. */
13441 xfree (tinfo);
13442}
13443
13444/* Read the branch trace. */
13445
13446static enum btrace_error
13447remote_read_btrace (struct target_ops *self,
13448 struct btrace_data *btrace,
13449 struct btrace_target_info *tinfo,
13450 enum btrace_read_type type)
13451{
13452 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13453 const char *annex;
13454
13455 if (packet_config_support (packet) != PACKET_ENABLE)
13456 error (_("Target does not support branch tracing."));
13457
13458#if !defined(HAVE_LIBEXPAT)
13459 error (_("Cannot process branch tracing result. XML parsing not supported."));
13460#endif
13461
13462 switch (type)
13463 {
13464 case BTRACE_READ_ALL:
13465 annex = "all";
13466 break;
13467 case BTRACE_READ_NEW:
13468 annex = "new";
13469 break;
13470 case BTRACE_READ_DELTA:
13471 annex = "delta";
13472 break;
13473 default:
13474 internal_error (__FILE__, __LINE__,
13475 _("Bad branch tracing read type: %u."),
13476 (unsigned int) type);
13477 }
13478
13479 gdb::unique_xmalloc_ptr<char> xml
13480 = target_read_stralloc (&current_target, TARGET_OBJECT_BTRACE, annex);
13481 if (xml == NULL)
13482 return BTRACE_ERR_UNKNOWN;
13483
13484 parse_xml_btrace (btrace, xml.get ());
13485
13486 return BTRACE_ERR_NONE;
13487}
13488
13489static const struct btrace_config *
13490remote_btrace_conf (struct target_ops *self,
13491 const struct btrace_target_info *tinfo)
13492{
13493 return &tinfo->conf;
13494}
13495
13496static int
13497remote_augmented_libraries_svr4_read (struct target_ops *self)
13498{
13499 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13500 == PACKET_ENABLE);
13501}
13502
13503/* Implementation of to_load. */
13504
13505static void
13506remote_load (struct target_ops *self, const char *name, int from_tty)
13507{
13508 generic_load (name, from_tty);
13509}
13510
13511/* Accepts an integer PID; returns a string representing a file that
13512 can be opened on the remote side to get the symbols for the child
13513 process. Returns NULL if the operation is not supported. */
13514
13515static char *
13516remote_pid_to_exec_file (struct target_ops *self, int pid)
13517{
13518 static gdb::unique_xmalloc_ptr<char> filename;
13519 struct inferior *inf;
13520 char *annex = NULL;
13521
13522 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13523 return NULL;
13524
13525 inf = find_inferior_pid (pid);
13526 if (inf == NULL)
13527 internal_error (__FILE__, __LINE__,
13528 _("not currently attached to process %d"), pid);
13529
13530 if (!inf->fake_pid_p)
13531 {
13532 const int annex_size = 9;
13533
13534 annex = (char *) alloca (annex_size);
13535 xsnprintf (annex, annex_size, "%x", pid);
13536 }
13537
13538 filename = target_read_stralloc (&current_target,
13539 TARGET_OBJECT_EXEC_FILE, annex);
13540
13541 return filename.get ();
13542}
13543
13544/* Implement the to_can_do_single_step target_ops method. */
13545
13546static int
13547remote_can_do_single_step (struct target_ops *ops)
13548{
13549 /* We can only tell whether target supports single step or not by
13550 supported s and S vCont actions if the stub supports vContSupported
13551 feature. If the stub doesn't support vContSupported feature,
13552 we have conservatively to think target doesn't supports single
13553 step. */
13554 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13555 {
13556 struct remote_state *rs = get_remote_state ();
13557
13558 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13559 remote_vcont_probe (rs);
13560
13561 return rs->supports_vCont.s && rs->supports_vCont.S;
13562 }
13563 else
13564 return 0;
13565}
13566
13567/* Implementation of the to_execution_direction method for the remote
13568 target. */
13569
13570static enum exec_direction_kind
13571remote_execution_direction (struct target_ops *self)
13572{
13573 struct remote_state *rs = get_remote_state ();
13574
13575 return rs->last_resume_exec_dir;
13576}
13577
13578/* Return pointer to the thread_info struct which corresponds to
13579 THREAD_HANDLE (having length HANDLE_LEN). */
13580
13581static struct thread_info *
13582remote_thread_handle_to_thread_info (struct target_ops *ops,
13583 const gdb_byte *thread_handle,
13584 int handle_len,
13585 struct inferior *inf)
13586{
13587 struct thread_info *tp;
13588
13589 ALL_NON_EXITED_THREADS (tp)
13590 {
13591 struct private_thread_info *priv = get_private_info_thread (tp);
13592
13593 if (tp->inf == inf && priv != NULL)
13594 {
13595 if (handle_len != priv->thread_handle->size ())
13596 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13597 handle_len, priv->thread_handle->size ());
13598 if (memcmp (thread_handle, priv->thread_handle->data (),
13599 handle_len) == 0)
13600 return tp;
13601 }
13602 }
13603
13604 return NULL;
13605}
13606
13607static void
13608init_remote_ops (void)
13609{
13610 remote_ops.to_shortname = "remote";
13611 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13612 remote_ops.to_doc =
13613 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13614Specify the serial device it is connected to\n\
13615(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13616 remote_ops.to_open = remote_open;
13617 remote_ops.to_close = remote_close;
13618 remote_ops.to_detach = remote_detach;
13619 remote_ops.to_disconnect = remote_disconnect;
13620 remote_ops.to_resume = remote_resume;
13621 remote_ops.to_commit_resume = remote_commit_resume;
13622 remote_ops.to_wait = remote_wait;
13623 remote_ops.to_fetch_registers = remote_fetch_registers;
13624 remote_ops.to_store_registers = remote_store_registers;
13625 remote_ops.to_prepare_to_store = remote_prepare_to_store;
13626 remote_ops.to_files_info = remote_files_info;
13627 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13628 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13629 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13630 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13631 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13632 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13633 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13634 remote_ops.to_stopped_data_address = remote_stopped_data_address;
13635 remote_ops.to_watchpoint_addr_within_range =
13636 remote_watchpoint_addr_within_range;
13637 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13638 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13639 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13640 remote_ops.to_region_ok_for_hw_watchpoint
13641 = remote_region_ok_for_hw_watchpoint;
13642 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13643 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13644 remote_ops.to_kill = remote_kill;
13645 remote_ops.to_load = remote_load;
13646 remote_ops.to_mourn_inferior = remote_mourn;
13647 remote_ops.to_pass_signals = remote_pass_signals;
13648 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13649 remote_ops.to_program_signals = remote_program_signals;
13650 remote_ops.to_thread_alive = remote_thread_alive;
13651 remote_ops.to_thread_name = remote_thread_name;
13652 remote_ops.to_update_thread_list = remote_update_thread_list;
13653 remote_ops.to_pid_to_str = remote_pid_to_str;
13654 remote_ops.to_extra_thread_info = remote_threads_extra_info;
13655 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13656 remote_ops.to_stop = remote_stop;
13657 remote_ops.to_interrupt = remote_interrupt;
13658 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13659 remote_ops.to_xfer_partial = remote_xfer_partial;
13660 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
13661 remote_ops.to_rcmd = remote_rcmd;
13662 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13663 remote_ops.to_log_command = serial_log_command;
13664 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13665 remote_ops.to_stratum = process_stratum;
13666 remote_ops.to_has_all_memory = default_child_has_all_memory;
13667 remote_ops.to_has_memory = default_child_has_memory;
13668 remote_ops.to_has_stack = default_child_has_stack;
13669 remote_ops.to_has_registers = default_child_has_registers;
13670 remote_ops.to_has_execution = default_child_has_execution;
13671 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
13672 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13673 remote_ops.to_magic = OPS_MAGIC;
13674 remote_ops.to_memory_map = remote_memory_map;
13675 remote_ops.to_flash_erase = remote_flash_erase;
13676 remote_ops.to_flash_done = remote_flash_done;
13677 remote_ops.to_read_description = remote_read_description;
13678 remote_ops.to_search_memory = remote_search_memory;
13679 remote_ops.to_can_async_p = remote_can_async_p;
13680 remote_ops.to_is_async_p = remote_is_async_p;
13681 remote_ops.to_async = remote_async;
13682 remote_ops.to_thread_events = remote_thread_events;
13683 remote_ops.to_can_do_single_step = remote_can_do_single_step;
13684 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13685 remote_ops.to_terminal_ours = remote_terminal_ours;
13686 remote_ops.to_supports_non_stop = remote_supports_non_stop;
13687 remote_ops.to_supports_multi_process = remote_supports_multi_process;
13688 remote_ops.to_supports_disable_randomization
13689 = remote_supports_disable_randomization;
13690 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13691 remote_ops.to_fileio_open = remote_hostio_open;
13692 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13693 remote_ops.to_fileio_pread = remote_hostio_pread;
13694 remote_ops.to_fileio_fstat = remote_hostio_fstat;
13695 remote_ops.to_fileio_close = remote_hostio_close;
13696 remote_ops.to_fileio_unlink = remote_hostio_unlink;
13697 remote_ops.to_fileio_readlink = remote_hostio_readlink;
13698 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13699 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13700 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13701 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13702 remote_ops.to_trace_init = remote_trace_init;
13703 remote_ops.to_download_tracepoint = remote_download_tracepoint;
13704 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13705 remote_ops.to_download_trace_state_variable
13706 = remote_download_trace_state_variable;
13707 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13708 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13709 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13710 remote_ops.to_trace_start = remote_trace_start;
13711 remote_ops.to_get_trace_status = remote_get_trace_status;
13712 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13713 remote_ops.to_trace_stop = remote_trace_stop;
13714 remote_ops.to_trace_find = remote_trace_find;
13715 remote_ops.to_get_trace_state_variable_value
13716 = remote_get_trace_state_variable_value;
13717 remote_ops.to_save_trace_data = remote_save_trace_data;
13718 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13719 remote_ops.to_upload_trace_state_variables
13720 = remote_upload_trace_state_variables;
13721 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13722 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13723 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13724 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13725 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13726 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13727 remote_ops.to_core_of_thread = remote_core_of_thread;
13728 remote_ops.to_verify_memory = remote_verify_memory;
13729 remote_ops.to_get_tib_address = remote_get_tib_address;
13730 remote_ops.to_set_permissions = remote_set_permissions;
13731 remote_ops.to_static_tracepoint_marker_at
13732 = remote_static_tracepoint_marker_at;
13733 remote_ops.to_static_tracepoint_markers_by_strid
13734 = remote_static_tracepoint_markers_by_strid;
13735 remote_ops.to_traceframe_info = remote_traceframe_info;
13736 remote_ops.to_use_agent = remote_use_agent;
13737 remote_ops.to_can_use_agent = remote_can_use_agent;
13738 remote_ops.to_supports_btrace = remote_supports_btrace;
13739 remote_ops.to_enable_btrace = remote_enable_btrace;
13740 remote_ops.to_disable_btrace = remote_disable_btrace;
13741 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13742 remote_ops.to_read_btrace = remote_read_btrace;
13743 remote_ops.to_btrace_conf = remote_btrace_conf;
13744 remote_ops.to_augmented_libraries_svr4_read =
13745 remote_augmented_libraries_svr4_read;
13746 remote_ops.to_follow_fork = remote_follow_fork;
13747 remote_ops.to_follow_exec = remote_follow_exec;
13748 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13749 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13750 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13751 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13752 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13753 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13754 remote_ops.to_execution_direction = remote_execution_direction;
13755 remote_ops.to_thread_handle_to_thread_info =
13756 remote_thread_handle_to_thread_info;
13757}
13758
13759/* Set up the extended remote vector by making a copy of the standard
13760 remote vector and adding to it. */
13761
13762static void
13763init_extended_remote_ops (void)
13764{
13765 extended_remote_ops = remote_ops;
13766
13767 extended_remote_ops.to_shortname = "extended-remote";
13768 extended_remote_ops.to_longname =
13769 "Extended remote serial target in gdb-specific protocol";
13770 extended_remote_ops.to_doc =
13771 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13772Specify the serial device it is connected to (e.g. /dev/ttya).";
13773 extended_remote_ops.to_open = extended_remote_open;
13774 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13775 extended_remote_ops.to_detach = extended_remote_detach;
13776 extended_remote_ops.to_attach = extended_remote_attach;
13777 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13778 extended_remote_ops.to_supports_disable_randomization
13779 = extended_remote_supports_disable_randomization;
13780}
13781
13782static int
13783remote_can_async_p (struct target_ops *ops)
13784{
13785 struct remote_state *rs = get_remote_state ();
13786
13787 /* We don't go async if the user has explicitly prevented it with the
13788 "maint set target-async" command. */
13789 if (!target_async_permitted)
13790 return 0;
13791
13792 /* We're async whenever the serial device is. */
13793 return serial_can_async_p (rs->remote_desc);
13794}
13795
13796static int
13797remote_is_async_p (struct target_ops *ops)
13798{
13799 struct remote_state *rs = get_remote_state ();
13800
13801 if (!target_async_permitted)
13802 /* We only enable async when the user specifically asks for it. */
13803 return 0;
13804
13805 /* We're async whenever the serial device is. */
13806 return serial_is_async_p (rs->remote_desc);
13807}
13808
13809/* Pass the SERIAL event on and up to the client. One day this code
13810 will be able to delay notifying the client of an event until the
13811 point where an entire packet has been received. */
13812
13813static serial_event_ftype remote_async_serial_handler;
13814
13815static void
13816remote_async_serial_handler (struct serial *scb, void *context)
13817{
13818 /* Don't propogate error information up to the client. Instead let
13819 the client find out about the error by querying the target. */
13820 inferior_event_handler (INF_REG_EVENT, NULL);
13821}
13822
13823static void
13824remote_async_inferior_event_handler (gdb_client_data data)
13825{
13826 inferior_event_handler (INF_REG_EVENT, NULL);
13827}
13828
13829static void
13830remote_async (struct target_ops *ops, int enable)
13831{
13832 struct remote_state *rs = get_remote_state ();
13833
13834 if (enable)
13835 {
13836 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13837
13838 /* If there are pending events in the stop reply queue tell the
13839 event loop to process them. */
13840 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13841 mark_async_event_handler (remote_async_inferior_event_token);
13842 /* For simplicity, below we clear the pending events token
13843 without remembering whether it is marked, so here we always
13844 mark it. If there's actually no pending notification to
13845 process, this ends up being a no-op (other than a spurious
13846 event-loop wakeup). */
13847 if (target_is_non_stop_p ())
13848 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13849 }
13850 else
13851 {
13852 serial_async (rs->remote_desc, NULL, NULL);
13853 /* If the core is disabling async, it doesn't want to be
13854 disturbed with target events. Clear all async event sources
13855 too. */
13856 clear_async_event_handler (remote_async_inferior_event_token);
13857 if (target_is_non_stop_p ())
13858 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13859 }
13860}
13861
13862/* Implementation of the to_thread_events method. */
13863
13864static void
13865remote_thread_events (struct target_ops *ops, int enable)
13866{
13867 struct remote_state *rs = get_remote_state ();
13868 size_t size = get_remote_packet_size ();
13869
13870 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13871 return;
13872
13873 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13874 putpkt (rs->buf);
13875 getpkt (&rs->buf, &rs->buf_size, 0);
13876
13877 switch (packet_ok (rs->buf,
13878 &remote_protocol_packets[PACKET_QThreadEvents]))
13879 {
13880 case PACKET_OK:
13881 if (strcmp (rs->buf, "OK") != 0)
13882 error (_("Remote refused setting thread events: %s"), rs->buf);
13883 break;
13884 case PACKET_ERROR:
13885 warning (_("Remote failure reply: %s"), rs->buf);
13886 break;
13887 case PACKET_UNKNOWN:
13888 break;
13889 }
13890}
13891
13892static void
13893set_remote_cmd (const char *args, int from_tty)
13894{
13895 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13896}
13897
13898static void
13899show_remote_cmd (const char *args, int from_tty)
13900{
13901 /* We can't just use cmd_show_list here, because we want to skip
13902 the redundant "show remote Z-packet" and the legacy aliases. */
13903 struct cmd_list_element *list = remote_show_cmdlist;
13904 struct ui_out *uiout = current_uiout;
13905
13906 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13907 for (; list != NULL; list = list->next)
13908 if (strcmp (list->name, "Z-packet") == 0)
13909 continue;
13910 else if (list->type == not_set_cmd)
13911 /* Alias commands are exactly like the original, except they
13912 don't have the normal type. */
13913 continue;
13914 else
13915 {
13916 ui_out_emit_tuple option_emitter (uiout, "option");
13917
13918 uiout->field_string ("name", list->name);
13919 uiout->text (": ");
13920 if (list->type == show_cmd)
13921 do_show_command (NULL, from_tty, list);
13922 else
13923 cmd_func (list, NULL, from_tty);
13924 }
13925}
13926
13927
13928/* Function to be called whenever a new objfile (shlib) is detected. */
13929static void
13930remote_new_objfile (struct objfile *objfile)
13931{
13932 struct remote_state *rs = get_remote_state ();
13933
13934 if (rs->remote_desc != 0) /* Have a remote connection. */
13935 remote_check_symbols ();
13936}
13937
13938/* Pull all the tracepoints defined on the target and create local
13939 data structures representing them. We don't want to create real
13940 tracepoints yet, we don't want to mess up the user's existing
13941 collection. */
13942
13943static int
13944remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13945{
13946 struct remote_state *rs = get_remote_state ();
13947 char *p;
13948
13949 /* Ask for a first packet of tracepoint definition. */
13950 putpkt ("qTfP");
13951 getpkt (&rs->buf, &rs->buf_size, 0);
13952 p = rs->buf;
13953 while (*p && *p != 'l')
13954 {
13955 parse_tracepoint_definition (p, utpp);
13956 /* Ask for another packet of tracepoint definition. */
13957 putpkt ("qTsP");
13958 getpkt (&rs->buf, &rs->buf_size, 0);
13959 p = rs->buf;
13960 }
13961 return 0;
13962}
13963
13964static int
13965remote_upload_trace_state_variables (struct target_ops *self,
13966 struct uploaded_tsv **utsvp)
13967{
13968 struct remote_state *rs = get_remote_state ();
13969 char *p;
13970
13971 /* Ask for a first packet of variable definition. */
13972 putpkt ("qTfV");
13973 getpkt (&rs->buf, &rs->buf_size, 0);
13974 p = rs->buf;
13975 while (*p && *p != 'l')
13976 {
13977 parse_tsv_definition (p, utsvp);
13978 /* Ask for another packet of variable definition. */
13979 putpkt ("qTsV");
13980 getpkt (&rs->buf, &rs->buf_size, 0);
13981 p = rs->buf;
13982 }
13983 return 0;
13984}
13985
13986/* The "set/show range-stepping" show hook. */
13987
13988static void
13989show_range_stepping (struct ui_file *file, int from_tty,
13990 struct cmd_list_element *c,
13991 const char *value)
13992{
13993 fprintf_filtered (file,
13994 _("Debugger's willingness to use range stepping "
13995 "is %s.\n"), value);
13996}
13997
13998/* The "set/show range-stepping" set hook. */
13999
14000static void
14001set_range_stepping (char *ignore_args, int from_tty,
14002 struct cmd_list_element *c)
14003{
14004 struct remote_state *rs = get_remote_state ();
14005
14006 /* Whene enabling, check whether range stepping is actually
14007 supported by the target, and warn if not. */
14008 if (use_range_stepping)
14009 {
14010 if (rs->remote_desc != NULL)
14011 {
14012 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14013 remote_vcont_probe (rs);
14014
14015 if (packet_support (PACKET_vCont) == PACKET_ENABLE
14016 && rs->supports_vCont.r)
14017 return;
14018 }
14019
14020 warning (_("Range stepping is not supported by the current target"));
14021 }
14022}
14023
14024void
14025_initialize_remote (void)
14026{
14027 struct cmd_list_element *cmd;
14028 const char *cmd_name;
14029
14030 /* architecture specific data */
14031 remote_gdbarch_data_handle =
14032 gdbarch_data_register_post_init (init_remote_state);
14033 remote_g_packet_data_handle =
14034 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14035
14036 remote_pspace_data
14037 = register_program_space_data_with_cleanup (NULL,
14038 remote_pspace_data_cleanup);
14039
14040 /* Initialize the per-target state. At the moment there is only one
14041 of these, not one per target. Only one target is active at a
14042 time. */
14043 remote_state = new_remote_state ();
14044
14045 init_remote_ops ();
14046 add_target (&remote_ops);
14047
14048 init_extended_remote_ops ();
14049 add_target (&extended_remote_ops);
14050
14051 /* Hook into new objfile notification. */
14052 observer_attach_new_objfile (remote_new_objfile);
14053 /* We're no longer interested in notification events of an inferior
14054 when it exits. */
14055 observer_attach_inferior_exit (discard_pending_stop_replies);
14056
14057#if 0
14058 init_remote_threadtests ();
14059#endif
14060
14061 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14062 /* set/show remote ... */
14063
14064 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14065Remote protocol specific variables\n\
14066Configure various remote-protocol specific variables such as\n\
14067the packets being used"),
14068 &remote_set_cmdlist, "set remote ",
14069 0 /* allow-unknown */, &setlist);
14070 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14071Remote protocol specific variables\n\
14072Configure various remote-protocol specific variables such as\n\
14073the packets being used"),
14074 &remote_show_cmdlist, "show remote ",
14075 0 /* allow-unknown */, &showlist);
14076
14077 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14078Compare section data on target to the exec file.\n\
14079Argument is a single section name (default: all loaded sections).\n\
14080To compare only read-only loaded sections, specify the -r option."),
14081 &cmdlist);
14082
14083 add_cmd ("packet", class_maintenance, packet_command, _("\
14084Send an arbitrary packet to a remote target.\n\
14085 maintenance packet TEXT\n\
14086If GDB is talking to an inferior via the GDB serial protocol, then\n\
14087this command sends the string TEXT to the inferior, and displays the\n\
14088response packet. GDB supplies the initial `$' character, and the\n\
14089terminating `#' character and checksum."),
14090 &maintenancelist);
14091
14092 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14093Set whether to send break if interrupted."), _("\
14094Show whether to send break if interrupted."), _("\
14095If set, a break, instead of a cntrl-c, is sent to the remote target."),
14096 set_remotebreak, show_remotebreak,
14097 &setlist, &showlist);
14098 cmd_name = "remotebreak";
14099 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14100 deprecate_cmd (cmd, "set remote interrupt-sequence");
14101 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14102 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14103 deprecate_cmd (cmd, "show remote interrupt-sequence");
14104
14105 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14106 interrupt_sequence_modes, &interrupt_sequence_mode,
14107 _("\
14108Set interrupt sequence to remote target."), _("\
14109Show interrupt sequence to remote target."), _("\
14110Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14111 NULL, show_interrupt_sequence,
14112 &remote_set_cmdlist,
14113 &remote_show_cmdlist);
14114
14115 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14116 &interrupt_on_connect, _("\
14117Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14118Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14119If set, interrupt sequence is sent to remote target."),
14120 NULL, NULL,
14121 &remote_set_cmdlist, &remote_show_cmdlist);
14122
14123 /* Install commands for configuring memory read/write packets. */
14124
14125 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14126Set the maximum number of bytes per memory write packet (deprecated)."),
14127 &setlist);
14128 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14129Show the maximum number of bytes per memory write packet (deprecated)."),
14130 &showlist);
14131 add_cmd ("memory-write-packet-size", no_class,
14132 set_memory_write_packet_size, _("\
14133Set the maximum number of bytes per memory-write packet.\n\
14134Specify the number of bytes in a packet or 0 (zero) for the\n\
14135default packet size. The actual limit is further reduced\n\
14136dependent on the target. Specify ``fixed'' to disable the\n\
14137further restriction and ``limit'' to enable that restriction."),
14138 &remote_set_cmdlist);
14139 add_cmd ("memory-read-packet-size", no_class,
14140 set_memory_read_packet_size, _("\
14141Set the maximum number of bytes per memory-read packet.\n\
14142Specify the number of bytes in a packet or 0 (zero) for the\n\
14143default packet size. The actual limit is further reduced\n\
14144dependent on the target. Specify ``fixed'' to disable the\n\
14145further restriction and ``limit'' to enable that restriction."),
14146 &remote_set_cmdlist);
14147 add_cmd ("memory-write-packet-size", no_class,
14148 show_memory_write_packet_size,
14149 _("Show the maximum number of bytes per memory-write packet."),
14150 &remote_show_cmdlist);
14151 add_cmd ("memory-read-packet-size", no_class,
14152 show_memory_read_packet_size,
14153 _("Show the maximum number of bytes per memory-read packet."),
14154 &remote_show_cmdlist);
14155
14156 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14157 &remote_hw_watchpoint_limit, _("\
14158Set the maximum number of target hardware watchpoints."), _("\
14159Show the maximum number of target hardware watchpoints."), _("\
14160Specify a negative limit for unlimited."),
14161 NULL, NULL, /* FIXME: i18n: The maximum
14162 number of target hardware
14163 watchpoints is %s. */
14164 &remote_set_cmdlist, &remote_show_cmdlist);
14165 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14166 &remote_hw_watchpoint_length_limit, _("\
14167Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14168Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14169Specify a negative limit for unlimited."),
14170 NULL, NULL, /* FIXME: i18n: The maximum
14171 length (in bytes) of a target
14172 hardware watchpoint is %s. */
14173 &remote_set_cmdlist, &remote_show_cmdlist);
14174 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14175 &remote_hw_breakpoint_limit, _("\
14176Set the maximum number of target hardware breakpoints."), _("\
14177Show the maximum number of target hardware breakpoints."), _("\
14178Specify a negative limit for unlimited."),
14179 NULL, NULL, /* FIXME: i18n: The maximum
14180 number of target hardware
14181 breakpoints is %s. */
14182 &remote_set_cmdlist, &remote_show_cmdlist);
14183
14184 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14185 &remote_address_size, _("\
14186Set the maximum size of the address (in bits) in a memory packet."), _("\
14187Show the maximum size of the address (in bits) in a memory packet."), NULL,
14188 NULL,
14189 NULL, /* FIXME: i18n: */
14190 &setlist, &showlist);
14191
14192 init_all_packet_configs ();
14193
14194 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14195 "X", "binary-download", 1);
14196
14197 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14198 "vCont", "verbose-resume", 0);
14199
14200 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14201 "QPassSignals", "pass-signals", 0);
14202
14203 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14204 "QCatchSyscalls", "catch-syscalls", 0);
14205
14206 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14207 "QProgramSignals", "program-signals", 0);
14208
14209 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14210 "QSetWorkingDir", "set-working-dir", 0);
14211
14212 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14213 "QStartupWithShell", "startup-with-shell", 0);
14214
14215 add_packet_config_cmd (&remote_protocol_packets
14216 [PACKET_QEnvironmentHexEncoded],
14217 "QEnvironmentHexEncoded", "environment-hex-encoded",
14218 0);
14219
14220 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14221 "QEnvironmentReset", "environment-reset",
14222 0);
14223
14224 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14225 "QEnvironmentUnset", "environment-unset",
14226 0);
14227
14228 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14229 "qSymbol", "symbol-lookup", 0);
14230
14231 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14232 "P", "set-register", 1);
14233
14234 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14235 "p", "fetch-register", 1);
14236
14237 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14238 "Z0", "software-breakpoint", 0);
14239
14240 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14241 "Z1", "hardware-breakpoint", 0);
14242
14243 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14244 "Z2", "write-watchpoint", 0);
14245
14246 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14247 "Z3", "read-watchpoint", 0);
14248
14249 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14250 "Z4", "access-watchpoint", 0);
14251
14252 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14253 "qXfer:auxv:read", "read-aux-vector", 0);
14254
14255 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14256 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14257
14258 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14259 "qXfer:features:read", "target-features", 0);
14260
14261 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14262 "qXfer:libraries:read", "library-info", 0);
14263
14264 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14265 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14266
14267 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14268 "qXfer:memory-map:read", "memory-map", 0);
14269
14270 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14271 "qXfer:spu:read", "read-spu-object", 0);
14272
14273 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14274 "qXfer:spu:write", "write-spu-object", 0);
14275
14276 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14277 "qXfer:osdata:read", "osdata", 0);
14278
14279 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14280 "qXfer:threads:read", "threads", 0);
14281
14282 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14283 "qXfer:siginfo:read", "read-siginfo-object", 0);
14284
14285 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14286 "qXfer:siginfo:write", "write-siginfo-object", 0);
14287
14288 add_packet_config_cmd
14289 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14290 "qXfer:traceframe-info:read", "traceframe-info", 0);
14291
14292 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14293 "qXfer:uib:read", "unwind-info-block", 0);
14294
14295 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14296 "qGetTLSAddr", "get-thread-local-storage-address",
14297 0);
14298
14299 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14300 "qGetTIBAddr", "get-thread-information-block-address",
14301 0);
14302
14303 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14304 "bc", "reverse-continue", 0);
14305
14306 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14307 "bs", "reverse-step", 0);
14308
14309 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14310 "qSupported", "supported-packets", 0);
14311
14312 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14313 "qSearch:memory", "search-memory", 0);
14314
14315 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14316 "qTStatus", "trace-status", 0);
14317
14318 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14319 "vFile:setfs", "hostio-setfs", 0);
14320
14321 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14322 "vFile:open", "hostio-open", 0);
14323
14324 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14325 "vFile:pread", "hostio-pread", 0);
14326
14327 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14328 "vFile:pwrite", "hostio-pwrite", 0);
14329
14330 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14331 "vFile:close", "hostio-close", 0);
14332
14333 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14334 "vFile:unlink", "hostio-unlink", 0);
14335
14336 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14337 "vFile:readlink", "hostio-readlink", 0);
14338
14339 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14340 "vFile:fstat", "hostio-fstat", 0);
14341
14342 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14343 "vAttach", "attach", 0);
14344
14345 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14346 "vRun", "run", 0);
14347
14348 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14349 "QStartNoAckMode", "noack", 0);
14350
14351 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14352 "vKill", "kill", 0);
14353
14354 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14355 "qAttached", "query-attached", 0);
14356
14357 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14358 "ConditionalTracepoints",
14359 "conditional-tracepoints", 0);
14360
14361 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14362 "ConditionalBreakpoints",
14363 "conditional-breakpoints", 0);
14364
14365 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14366 "BreakpointCommands",
14367 "breakpoint-commands", 0);
14368
14369 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14370 "FastTracepoints", "fast-tracepoints", 0);
14371
14372 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14373 "TracepointSource", "TracepointSource", 0);
14374
14375 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14376 "QAllow", "allow", 0);
14377
14378 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14379 "StaticTracepoints", "static-tracepoints", 0);
14380
14381 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14382 "InstallInTrace", "install-in-trace", 0);
14383
14384 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14385 "qXfer:statictrace:read", "read-sdata-object", 0);
14386
14387 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14388 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14389
14390 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14391 "QDisableRandomization", "disable-randomization", 0);
14392
14393 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14394 "QAgent", "agent", 0);
14395
14396 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14397 "QTBuffer:size", "trace-buffer-size", 0);
14398
14399 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14400 "Qbtrace:off", "disable-btrace", 0);
14401
14402 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14403 "Qbtrace:bts", "enable-btrace-bts", 0);
14404
14405 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14406 "Qbtrace:pt", "enable-btrace-pt", 0);
14407
14408 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14409 "qXfer:btrace", "read-btrace", 0);
14410
14411 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14412 "qXfer:btrace-conf", "read-btrace-conf", 0);
14413
14414 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14415 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14416
14417 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14418 "multiprocess-feature", "multiprocess-feature", 0);
14419
14420 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14421 "swbreak-feature", "swbreak-feature", 0);
14422
14423 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14424 "hwbreak-feature", "hwbreak-feature", 0);
14425
14426 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14427 "fork-event-feature", "fork-event-feature", 0);
14428
14429 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14430 "vfork-event-feature", "vfork-event-feature", 0);
14431
14432 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14433 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14434
14435 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14436 "vContSupported", "verbose-resume-supported", 0);
14437
14438 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14439 "exec-event-feature", "exec-event-feature", 0);
14440
14441 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14442 "vCtrlC", "ctrl-c", 0);
14443
14444 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14445 "QThreadEvents", "thread-events", 0);
14446
14447 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14448 "N stop reply", "no-resumed-stop-reply", 0);
14449
14450 /* Assert that we've registered "set remote foo-packet" commands
14451 for all packet configs. */
14452 {
14453 int i;
14454
14455 for (i = 0; i < PACKET_MAX; i++)
14456 {
14457 /* Ideally all configs would have a command associated. Some
14458 still don't though. */
14459 int excepted;
14460
14461 switch (i)
14462 {
14463 case PACKET_QNonStop:
14464 case PACKET_EnableDisableTracepoints_feature:
14465 case PACKET_tracenz_feature:
14466 case PACKET_DisconnectedTracing_feature:
14467 case PACKET_augmented_libraries_svr4_read_feature:
14468 case PACKET_qCRC:
14469 /* Additions to this list need to be well justified:
14470 pre-existing packets are OK; new packets are not. */
14471 excepted = 1;
14472 break;
14473 default:
14474 excepted = 0;
14475 break;
14476 }
14477
14478 /* This catches both forgetting to add a config command, and
14479 forgetting to remove a packet from the exception list. */
14480 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14481 }
14482 }
14483
14484 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14485 Z sub-packet has its own set and show commands, but users may
14486 have sets to this variable in their .gdbinit files (or in their
14487 documentation). */
14488 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14489 &remote_Z_packet_detect, _("\
14490Set use of remote protocol `Z' packets"), _("\
14491Show use of remote protocol `Z' packets "), _("\
14492When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14493packets."),
14494 set_remote_protocol_Z_packet_cmd,
14495 show_remote_protocol_Z_packet_cmd,
14496 /* FIXME: i18n: Use of remote protocol
14497 `Z' packets is %s. */
14498 &remote_set_cmdlist, &remote_show_cmdlist);
14499
14500 add_prefix_cmd ("remote", class_files, remote_command, _("\
14501Manipulate files on the remote system\n\
14502Transfer files to and from the remote target system."),
14503 &remote_cmdlist, "remote ",
14504 0 /* allow-unknown */, &cmdlist);
14505
14506 add_cmd ("put", class_files, remote_put_command,
14507 _("Copy a local file to the remote system."),
14508 &remote_cmdlist);
14509
14510 add_cmd ("get", class_files, remote_get_command,
14511 _("Copy a remote file to the local system."),
14512 &remote_cmdlist);
14513
14514 add_cmd ("delete", class_files, remote_delete_command,
14515 _("Delete a remote file."),
14516 &remote_cmdlist);
14517
14518 add_setshow_string_noescape_cmd ("exec-file", class_files,
14519 &remote_exec_file_var, _("\
14520Set the remote pathname for \"run\""), _("\
14521Show the remote pathname for \"run\""), NULL,
14522 set_remote_exec_file,
14523 show_remote_exec_file,
14524 &remote_set_cmdlist,
14525 &remote_show_cmdlist);
14526
14527 add_setshow_boolean_cmd ("range-stepping", class_run,
14528 &use_range_stepping, _("\
14529Enable or disable range stepping."), _("\
14530Show whether target-assisted range stepping is enabled."), _("\
14531If on, and the target supports it, when stepping a source line, GDB\n\
14532tells the target to step the corresponding range of addresses itself instead\n\
14533of issuing multiple single-steps. This speeds up source level\n\
14534stepping. If off, GDB always issues single-steps, even if range\n\
14535stepping is supported by the target. The default is on."),
14536 set_range_stepping,
14537 show_range_stepping,
14538 &setlist,
14539 &showlist);
14540
14541 /* Eventually initialize fileio. See fileio.c */
14542 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14543
14544 /* Take advantage of the fact that the TID field is not used, to tag
14545 special ptids with it set to != 0. */
14546 magic_null_ptid = ptid_build (42000, -1, 1);
14547 not_sent_ptid = ptid_build (42000, -2, 1);
14548 any_thread_ptid = ptid_build (42000, 0, 1);
14549}