]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/remote.c
Constify some commands in remote.c
[thirdparty/binutils-gdb.git] / gdb / remote.c
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 /* Temp hacks for tracepoint encoding migration. */
80 static char *target_buf;
81 static long target_buf_size;
82
83 /* Per-program-space data key. */
84 static const struct program_space_data *remote_pspace_data;
85
86 /* The variable registered as the control variable used by the
87 remote exec-file commands. While the remote exec-file setting is
88 per-program-space, the set/show machinery uses this as the
89 location of the remote exec-file value. */
90 static char *remote_exec_file_var;
91
92 /* The size to align memory write packets, when practical. The protocol
93 does not guarantee any alignment, and gdb will generate short
94 writes and unaligned writes, but even as a best-effort attempt this
95 can improve bulk transfers. For instance, if a write is misaligned
96 relative to the target's data bus, the stub may need to make an extra
97 round trip fetching data from the target. This doesn't make a
98 huge difference, but it's easy to do, so we try to be helpful.
99
100 The alignment chosen is arbitrary; usually data bus width is
101 important here, not the possibly larger cache line size. */
102 enum { REMOTE_ALIGN_WRITES = 16 };
103
104 /* Prototypes for local functions. */
105 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
106 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
107 int forever, int *is_notif);
108
109 static void remote_files_info (struct target_ops *ignore);
110
111 static void remote_prepare_to_store (struct target_ops *self,
112 struct regcache *regcache);
113
114 static void remote_open_1 (const char *, int, struct target_ops *,
115 int extended_p);
116
117 static void remote_close (struct target_ops *self);
118
119 struct remote_state;
120
121 static int remote_vkill (int pid, struct remote_state *rs);
122
123 static void remote_kill_k (void);
124
125 static void remote_mourn (struct target_ops *ops);
126
127 static void extended_remote_restart (void);
128
129 static void remote_send (char **buf, long *sizeof_buf_p);
130
131 static int readchar (int timeout);
132
133 static void remote_serial_write (const char *str, int len);
134
135 static void remote_kill (struct target_ops *ops);
136
137 static int remote_can_async_p (struct target_ops *);
138
139 static int remote_is_async_p (struct target_ops *);
140
141 static void remote_async (struct target_ops *ops, int enable);
142
143 static void remote_thread_events (struct target_ops *ops, int enable);
144
145 static void interrupt_query (void);
146
147 static void set_general_thread (ptid_t ptid);
148 static void set_continue_thread (ptid_t ptid);
149
150 static void get_offsets (void);
151
152 static void skip_frame (void);
153
154 static long read_frame (char **buf_p, long *sizeof_buf);
155
156 static int hexnumlen (ULONGEST num);
157
158 static void init_remote_ops (void);
159
160 static void init_extended_remote_ops (void);
161
162 static void remote_stop (struct target_ops *self, ptid_t);
163
164 static int stubhex (int ch);
165
166 static int hexnumstr (char *, ULONGEST);
167
168 static int hexnumnstr (char *, ULONGEST, int);
169
170 static CORE_ADDR remote_address_masked (CORE_ADDR);
171
172 static void print_packet (const char *);
173
174 static int stub_unpack_int (char *buff, int fieldlength);
175
176 static ptid_t remote_current_thread (ptid_t oldptid);
177
178 static int putpkt_binary (const char *buf, int cnt);
179
180 static void check_binary_download (CORE_ADDR addr);
181
182 struct packet_config;
183
184 static void show_packet_config_cmd (struct packet_config *config);
185
186 static void show_remote_protocol_packet_cmd (struct ui_file *file,
187 int from_tty,
188 struct cmd_list_element *c,
189 const char *value);
190
191 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
192 static ptid_t read_ptid (char *buf, char **obuf);
193
194 static void remote_set_permissions (struct target_ops *self);
195
196 static int remote_get_trace_status (struct target_ops *self,
197 struct trace_status *ts);
198
199 static int remote_upload_tracepoints (struct target_ops *self,
200 struct uploaded_tp **utpp);
201
202 static int remote_upload_trace_state_variables (struct target_ops *self,
203 struct uploaded_tsv **utsvp);
204
205 static void remote_query_supported (void);
206
207 static void remote_check_symbols (void);
208
209 struct stop_reply;
210 static void stop_reply_xfree (struct stop_reply *);
211 static void remote_parse_stop_reply (char *, struct stop_reply *);
212 static void push_stop_reply (struct stop_reply *);
213 static void discard_pending_stop_replies_in_queue (struct remote_state *);
214 static int peek_stop_reply (ptid_t ptid);
215
216 struct threads_listing_context;
217 static void remove_new_fork_children (struct threads_listing_context *);
218
219 static void remote_async_inferior_event_handler (gdb_client_data);
220
221 static void remote_terminal_ours (struct target_ops *self);
222
223 static int remote_read_description_p (struct target_ops *target);
224
225 static void remote_console_output (char *msg);
226
227 static int remote_supports_cond_breakpoints (struct target_ops *self);
228
229 static int remote_can_run_breakpoint_commands (struct target_ops *self);
230
231 static void remote_btrace_reset (void);
232
233 static void remote_btrace_maybe_reopen (void);
234
235 static int stop_reply_queue_length (void);
236
237 static void readahead_cache_invalidate (void);
238
239 static void remote_unpush_and_throw (void);
240
241 /* For "remote". */
242
243 static struct cmd_list_element *remote_cmdlist;
244
245 /* For "set remote" and "show remote". */
246
247 static struct cmd_list_element *remote_set_cmdlist;
248 static struct cmd_list_element *remote_show_cmdlist;
249
250 /* Stub vCont actions support.
251
252 Each field is a boolean flag indicating whether the stub reports
253 support for the corresponding action. */
254
255 struct vCont_action_support
256 {
257 /* vCont;t */
258 int t;
259
260 /* vCont;r */
261 int r;
262
263 /* vCont;s */
264 int s;
265
266 /* vCont;S */
267 int S;
268 };
269
270 /* Controls whether GDB is willing to use range stepping. */
271
272 static int use_range_stepping = 1;
273
274 #define OPAQUETHREADBYTES 8
275
276 /* a 64 bit opaque identifier */
277 typedef unsigned char threadref[OPAQUETHREADBYTES];
278
279 /* About this many threadisds fit in a packet. */
280
281 #define MAXTHREADLISTRESULTS 32
282
283 /* The max number of chars in debug output. The rest of chars are
284 omitted. */
285
286 #define REMOTE_DEBUG_MAX_CHAR 512
287
288 /* Data for the vFile:pread readahead cache. */
289
290 struct readahead_cache
291 {
292 /* The file descriptor for the file that is being cached. -1 if the
293 cache is invalid. */
294 int fd;
295
296 /* The offset into the file that the cache buffer corresponds
297 to. */
298 ULONGEST offset;
299
300 /* The buffer holding the cache contents. */
301 gdb_byte *buf;
302 /* The buffer's size. We try to read as much as fits into a packet
303 at a time. */
304 size_t bufsize;
305
306 /* Cache hit and miss counters. */
307 ULONGEST hit_count;
308 ULONGEST miss_count;
309 };
310
311 /* Description of the remote protocol state for the currently
312 connected target. This is per-target state, and independent of the
313 selected architecture. */
314
315 struct remote_state
316 {
317 /* A buffer to use for incoming packets, and its current size. The
318 buffer is grown dynamically for larger incoming packets.
319 Outgoing packets may also be constructed in this buffer.
320 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
321 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
322 packets. */
323 char *buf;
324 long buf_size;
325
326 /* True if we're going through initial connection setup (finding out
327 about the remote side's threads, relocating symbols, etc.). */
328 int starting_up;
329
330 /* If we negotiated packet size explicitly (and thus can bypass
331 heuristics for the largest packet size that will not overflow
332 a buffer in the stub), this will be set to that packet size.
333 Otherwise zero, meaning to use the guessed size. */
334 long explicit_packet_size;
335
336 /* remote_wait is normally called when the target is running and
337 waits for a stop reply packet. But sometimes we need to call it
338 when the target is already stopped. We can send a "?" packet
339 and have remote_wait read the response. Or, if we already have
340 the response, we can stash it in BUF and tell remote_wait to
341 skip calling getpkt. This flag is set when BUF contains a
342 stop reply packet and the target is not waiting. */
343 int cached_wait_status;
344
345 /* True, if in no ack mode. That is, neither GDB nor the stub will
346 expect acks from each other. The connection is assumed to be
347 reliable. */
348 int noack_mode;
349
350 /* True if we're connected in extended remote mode. */
351 int extended;
352
353 /* True if we resumed the target and we're waiting for the target to
354 stop. In the mean time, we can't start another command/query.
355 The remote server wouldn't be ready to process it, so we'd
356 timeout waiting for a reply that would never come and eventually
357 we'd close the connection. This can happen in asynchronous mode
358 because we allow GDB commands while the target is running. */
359 int waiting_for_stop_reply;
360
361 /* The status of the stub support for the various vCont actions. */
362 struct vCont_action_support supports_vCont;
363
364 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
365 responded to that. */
366 int ctrlc_pending_p;
367
368 /* True if we saw a Ctrl-C while reading or writing from/to the
369 remote descriptor. At that point it is not safe to send a remote
370 interrupt packet, so we instead remember we saw the Ctrl-C and
371 process it once we're done with sending/receiving the current
372 packet, which should be shortly. If however that takes too long,
373 and the user presses Ctrl-C again, we offer to disconnect. */
374 int got_ctrlc_during_io;
375
376 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
377 remote_open knows that we don't have a file open when the program
378 starts. */
379 struct serial *remote_desc;
380
381 /* These are the threads which we last sent to the remote system. The
382 TID member will be -1 for all or -2 for not sent yet. */
383 ptid_t general_thread;
384 ptid_t continue_thread;
385
386 /* This is the traceframe which we last selected on the remote system.
387 It will be -1 if no traceframe is selected. */
388 int remote_traceframe_number;
389
390 char *last_pass_packet;
391
392 /* The last QProgramSignals packet sent to the target. We bypass
393 sending a new program signals list down to the target if the new
394 packet is exactly the same as the last we sent. IOW, we only let
395 the target know about program signals list changes. */
396 char *last_program_signals_packet;
397
398 enum gdb_signal last_sent_signal;
399
400 int last_sent_step;
401
402 /* The execution direction of the last resume we got. */
403 enum exec_direction_kind last_resume_exec_dir;
404
405 char *finished_object;
406 char *finished_annex;
407 ULONGEST finished_offset;
408
409 /* Should we try the 'ThreadInfo' query packet?
410
411 This variable (NOT available to the user: auto-detect only!)
412 determines whether GDB will use the new, simpler "ThreadInfo"
413 query or the older, more complex syntax for thread queries.
414 This is an auto-detect variable (set to true at each connect,
415 and set to false when the target fails to recognize it). */
416 int use_threadinfo_query;
417 int use_threadextra_query;
418
419 threadref echo_nextthread;
420 threadref nextthread;
421 threadref resultthreadlist[MAXTHREADLISTRESULTS];
422
423 /* The state of remote notification. */
424 struct remote_notif_state *notif_state;
425
426 /* The branch trace configuration. */
427 struct btrace_config btrace_config;
428
429 /* The argument to the last "vFile:setfs:" packet we sent, used
430 to avoid sending repeated unnecessary "vFile:setfs:" packets.
431 Initialized to -1 to indicate that no "vFile:setfs:" packet
432 has yet been sent. */
433 int fs_pid;
434
435 /* A readahead cache for vFile:pread. Often, reading a binary
436 involves a sequence of small reads. E.g., when parsing an ELF
437 file. A readahead cache helps mostly the case of remote
438 debugging on a connection with higher latency, due to the
439 request/reply nature of the RSP. We only cache data for a single
440 file descriptor at a time. */
441 struct readahead_cache readahead_cache;
442 };
443
444 /* Private data that we'll store in (struct thread_info)->private. */
445 struct private_thread_info
446 {
447 char *extra;
448 char *name;
449 int core;
450
451 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
452 sequence of bytes. */
453 gdb::byte_vector *thread_handle;
454
455 /* Whether the target stopped for a breakpoint/watchpoint. */
456 enum target_stop_reason stop_reason;
457
458 /* This is set to the data address of the access causing the target
459 to stop for a watchpoint. */
460 CORE_ADDR watch_data_address;
461
462 /* Fields used by the vCont action coalescing implemented in
463 remote_resume / remote_commit_resume. remote_resume stores each
464 thread's last resume request in these fields, so that a later
465 remote_commit_resume knows which is the proper action for this
466 thread to include in the vCont packet. */
467
468 /* True if the last target_resume call for this thread was a step
469 request, false if a continue request. */
470 int last_resume_step;
471
472 /* The signal specified in the last target_resume call for this
473 thread. */
474 enum gdb_signal last_resume_sig;
475
476 /* Whether this thread was already vCont-resumed on the remote
477 side. */
478 int vcont_resumed;
479 };
480
481 static void
482 free_private_thread_info (struct private_thread_info *info)
483 {
484 xfree (info->extra);
485 xfree (info->name);
486 delete info->thread_handle;
487 xfree (info);
488 }
489
490 /* This data could be associated with a target, but we do not always
491 have access to the current target when we need it, so for now it is
492 static. This will be fine for as long as only one target is in use
493 at a time. */
494 static struct remote_state *remote_state;
495
496 static struct remote_state *
497 get_remote_state_raw (void)
498 {
499 return remote_state;
500 }
501
502 /* Allocate a new struct remote_state with xmalloc, initialize it, and
503 return it. */
504
505 static struct remote_state *
506 new_remote_state (void)
507 {
508 struct remote_state *result = XCNEW (struct remote_state);
509
510 /* The default buffer size is unimportant; it will be expanded
511 whenever a larger buffer is needed. */
512 result->buf_size = 400;
513 result->buf = (char *) xmalloc (result->buf_size);
514 result->remote_traceframe_number = -1;
515 result->last_sent_signal = GDB_SIGNAL_0;
516 result->last_resume_exec_dir = EXEC_FORWARD;
517 result->fs_pid = -1;
518
519 return result;
520 }
521
522 /* Description of the remote protocol for a given architecture. */
523
524 struct packet_reg
525 {
526 long offset; /* Offset into G packet. */
527 long regnum; /* GDB's internal register number. */
528 LONGEST pnum; /* Remote protocol register number. */
529 int in_g_packet; /* Always part of G packet. */
530 /* long size in bytes; == register_size (target_gdbarch (), regnum);
531 at present. */
532 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
533 at present. */
534 };
535
536 struct remote_arch_state
537 {
538 /* Description of the remote protocol registers. */
539 long sizeof_g_packet;
540
541 /* Description of the remote protocol registers indexed by REGNUM
542 (making an array gdbarch_num_regs in size). */
543 struct packet_reg *regs;
544
545 /* This is the size (in chars) of the first response to the ``g''
546 packet. It is used as a heuristic when determining the maximum
547 size of memory-read and memory-write packets. A target will
548 typically only reserve a buffer large enough to hold the ``g''
549 packet. The size does not include packet overhead (headers and
550 trailers). */
551 long actual_register_packet_size;
552
553 /* This is the maximum size (in chars) of a non read/write packet.
554 It is also used as a cap on the size of read/write packets. */
555 long remote_packet_size;
556 };
557
558 /* Utility: generate error from an incoming stub packet. */
559 static void
560 trace_error (char *buf)
561 {
562 if (*buf++ != 'E')
563 return; /* not an error msg */
564 switch (*buf)
565 {
566 case '1': /* malformed packet error */
567 if (*++buf == '0') /* general case: */
568 error (_("remote.c: error in outgoing packet."));
569 else
570 error (_("remote.c: error in outgoing packet at field #%ld."),
571 strtol (buf, NULL, 16));
572 default:
573 error (_("Target returns error code '%s'."), buf);
574 }
575 }
576
577 /* Utility: wait for reply from stub, while accepting "O" packets. */
578 static char *
579 remote_get_noisy_reply (char **buf_p,
580 long *sizeof_buf)
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 (buf_p, sizeof_buf, 0);
588 buf = *buf_p;
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 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, *sizeof_buf, "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. */
654 static struct gdbarch_data *remote_gdbarch_data_handle;
655
656 static struct remote_arch_state *
657 get_remote_arch_state (void)
658 {
659 gdb_assert (target_gdbarch () != NULL);
660 return ((struct remote_arch_state *)
661 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
662 }
663
664 /* Fetch the global remote target state. */
665
666 static struct remote_state *
667 get_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 ();
675
676 return get_remote_state_raw ();
677 }
678
679 /* Cleanup routine for the remote module's pspace data. */
680
681 static void
682 remote_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
691 static const char *
692 get_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
707 static void
708 set_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
720 static void
721 set_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
730 static void
731 show_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
737 static int
738 compare_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
753 static int
754 map_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
802 int
803 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
804 int *pnum, int *poffset)
805 {
806 struct packet_reg *regs;
807 struct cleanup *old_chain;
808
809 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
810
811 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
812 old_chain = make_cleanup (xfree, regs);
813
814 map_regcache_remote_table (gdbarch, regs);
815
816 *pnum = regs[regnum].pnum;
817 *poffset = regs[regnum].offset;
818
819 do_cleanups (old_chain);
820
821 return *pnum != -1;
822 }
823
824 static void *
825 init_remote_state (struct gdbarch *gdbarch)
826 {
827 struct remote_state *rs = get_remote_state_raw ();
828 struct remote_arch_state *rsa;
829
830 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
831
832 /* Use the architecture to build a regnum<->pnum table, which will be
833 1:1 unless a feature set specifies otherwise. */
834 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
835 gdbarch_num_regs (gdbarch),
836 struct packet_reg);
837
838 /* Record the maximum possible size of the g packet - it may turn out
839 to be smaller. */
840 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
841
842 /* Default maximum number of characters in a packet body. Many
843 remote stubs have a hardwired buffer size of 400 bytes
844 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
845 as the maximum packet-size to ensure that the packet and an extra
846 NUL character can always fit in the buffer. This stops GDB
847 trashing stubs that try to squeeze an extra NUL into what is
848 already a full buffer (As of 1999-12-04 that was most stubs). */
849 rsa->remote_packet_size = 400 - 1;
850
851 /* This one is filled in when a ``g'' packet is received. */
852 rsa->actual_register_packet_size = 0;
853
854 /* Should rsa->sizeof_g_packet needs more space than the
855 default, adjust the size accordingly. Remember that each byte is
856 encoded as two characters. 32 is the overhead for the packet
857 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
858 (``$NN:G...#NN'') is a better guess, the below has been padded a
859 little. */
860 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
861 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
862
863 /* Make sure that the packet buffer is plenty big enough for
864 this architecture. */
865 if (rs->buf_size < rsa->remote_packet_size)
866 {
867 rs->buf_size = 2 * rsa->remote_packet_size;
868 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
869 }
870
871 return rsa;
872 }
873
874 /* Return the current allowed size of a remote packet. This is
875 inferred from the current architecture, and should be used to
876 limit the length of outgoing packets. */
877 static long
878 get_remote_packet_size (void)
879 {
880 struct remote_state *rs = get_remote_state ();
881 struct remote_arch_state *rsa = get_remote_arch_state ();
882
883 if (rs->explicit_packet_size)
884 return rs->explicit_packet_size;
885
886 return rsa->remote_packet_size;
887 }
888
889 static struct packet_reg *
890 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
891 {
892 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
893 return NULL;
894 else
895 {
896 struct packet_reg *r = &rsa->regs[regnum];
897
898 gdb_assert (r->regnum == regnum);
899 return r;
900 }
901 }
902
903 static struct packet_reg *
904 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
905 {
906 int i;
907
908 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
909 {
910 struct packet_reg *r = &rsa->regs[i];
911
912 if (r->pnum == pnum)
913 return r;
914 }
915 return NULL;
916 }
917
918 static struct target_ops remote_ops;
919
920 static struct target_ops extended_remote_ops;
921
922 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
923 ``forever'' still use the normal timeout mechanism. This is
924 currently used by the ASYNC code to guarentee that target reads
925 during the initial connect always time-out. Once getpkt has been
926 modified to return a timeout indication and, in turn
927 remote_wait()/wait_for_inferior() have gained a timeout parameter
928 this can go away. */
929 static int wait_forever_enabled_p = 1;
930
931 /* Allow the user to specify what sequence to send to the remote
932 when he requests a program interruption: Although ^C is usually
933 what remote systems expect (this is the default, here), it is
934 sometimes preferable to send a break. On other systems such
935 as the Linux kernel, a break followed by g, which is Magic SysRq g
936 is required in order to interrupt the execution. */
937 const char interrupt_sequence_control_c[] = "Ctrl-C";
938 const char interrupt_sequence_break[] = "BREAK";
939 const char interrupt_sequence_break_g[] = "BREAK-g";
940 static const char *const interrupt_sequence_modes[] =
941 {
942 interrupt_sequence_control_c,
943 interrupt_sequence_break,
944 interrupt_sequence_break_g,
945 NULL
946 };
947 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
948
949 static void
950 show_interrupt_sequence (struct ui_file *file, int from_tty,
951 struct cmd_list_element *c,
952 const char *value)
953 {
954 if (interrupt_sequence_mode == interrupt_sequence_control_c)
955 fprintf_filtered (file,
956 _("Send the ASCII ETX character (Ctrl-c) "
957 "to the remote target to interrupt the "
958 "execution of the program.\n"));
959 else if (interrupt_sequence_mode == interrupt_sequence_break)
960 fprintf_filtered (file,
961 _("send a break signal to the remote target "
962 "to interrupt the execution of the program.\n"));
963 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
964 fprintf_filtered (file,
965 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
966 "the remote target to interrupt the execution "
967 "of Linux kernel.\n"));
968 else
969 internal_error (__FILE__, __LINE__,
970 _("Invalid value for interrupt_sequence_mode: %s."),
971 interrupt_sequence_mode);
972 }
973
974 /* This boolean variable specifies whether interrupt_sequence is sent
975 to the remote target when gdb connects to it.
976 This is mostly needed when you debug the Linux kernel: The Linux kernel
977 expects BREAK g which is Magic SysRq g for connecting gdb. */
978 static int interrupt_on_connect = 0;
979
980 /* This variable is used to implement the "set/show remotebreak" commands.
981 Since these commands are now deprecated in favor of "set/show remote
982 interrupt-sequence", it no longer has any effect on the code. */
983 static int remote_break;
984
985 static void
986 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
987 {
988 if (remote_break)
989 interrupt_sequence_mode = interrupt_sequence_break;
990 else
991 interrupt_sequence_mode = interrupt_sequence_control_c;
992 }
993
994 static void
995 show_remotebreak (struct ui_file *file, int from_tty,
996 struct cmd_list_element *c,
997 const char *value)
998 {
999 }
1000
1001 /* This variable sets the number of bits in an address that are to be
1002 sent in a memory ("M" or "m") packet. Normally, after stripping
1003 leading zeros, the entire address would be sent. This variable
1004 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1005 initial implementation of remote.c restricted the address sent in
1006 memory packets to ``host::sizeof long'' bytes - (typically 32
1007 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1008 address was never sent. Since fixing this bug may cause a break in
1009 some remote targets this variable is principly provided to
1010 facilitate backward compatibility. */
1011
1012 static unsigned int remote_address_size;
1013
1014 /* Temporary to track who currently owns the terminal. See
1015 remote_terminal_* for more details. */
1016
1017 static int remote_async_terminal_ours_p;
1018
1019 \f
1020 /* User configurable variables for the number of characters in a
1021 memory read/write packet. MIN (rsa->remote_packet_size,
1022 rsa->sizeof_g_packet) is the default. Some targets need smaller
1023 values (fifo overruns, et.al.) and some users need larger values
1024 (speed up transfers). The variables ``preferred_*'' (the user
1025 request), ``current_*'' (what was actually set) and ``forced_*''
1026 (Positive - a soft limit, negative - a hard limit). */
1027
1028 struct memory_packet_config
1029 {
1030 const char *name;
1031 long size;
1032 int fixed_p;
1033 };
1034
1035 /* The default max memory-write-packet-size. The 16k is historical.
1036 (It came from older GDB's using alloca for buffers and the
1037 knowledge (folklore?) that some hosts don't cope very well with
1038 large alloca calls.) */
1039 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1040
1041 /* The minimum remote packet size for memory transfers. Ensures we
1042 can write at least one byte. */
1043 #define MIN_MEMORY_PACKET_SIZE 20
1044
1045 /* Compute the current size of a read/write packet. Since this makes
1046 use of ``actual_register_packet_size'' the computation is dynamic. */
1047
1048 static long
1049 get_memory_packet_size (struct memory_packet_config *config)
1050 {
1051 struct remote_state *rs = get_remote_state ();
1052 struct remote_arch_state *rsa = get_remote_arch_state ();
1053
1054 long what_they_get;
1055 if (config->fixed_p)
1056 {
1057 if (config->size <= 0)
1058 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1059 else
1060 what_they_get = config->size;
1061 }
1062 else
1063 {
1064 what_they_get = get_remote_packet_size ();
1065 /* Limit the packet to the size specified by the user. */
1066 if (config->size > 0
1067 && what_they_get > config->size)
1068 what_they_get = config->size;
1069
1070 /* Limit it to the size of the targets ``g'' response unless we have
1071 permission from the stub to use a larger packet size. */
1072 if (rs->explicit_packet_size == 0
1073 && rsa->actual_register_packet_size > 0
1074 && what_they_get > rsa->actual_register_packet_size)
1075 what_they_get = rsa->actual_register_packet_size;
1076 }
1077 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1078 what_they_get = MIN_MEMORY_PACKET_SIZE;
1079
1080 /* Make sure there is room in the global buffer for this packet
1081 (including its trailing NUL byte). */
1082 if (rs->buf_size < what_they_get + 1)
1083 {
1084 rs->buf_size = 2 * what_they_get;
1085 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1086 }
1087
1088 return what_they_get;
1089 }
1090
1091 /* Update the size of a read/write packet. If they user wants
1092 something really big then do a sanity check. */
1093
1094 static void
1095 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1096 {
1097 int fixed_p = config->fixed_p;
1098 long size = config->size;
1099
1100 if (args == NULL)
1101 error (_("Argument required (integer, `fixed' or `limited')."));
1102 else if (strcmp (args, "hard") == 0
1103 || strcmp (args, "fixed") == 0)
1104 fixed_p = 1;
1105 else if (strcmp (args, "soft") == 0
1106 || strcmp (args, "limit") == 0)
1107 fixed_p = 0;
1108 else
1109 {
1110 char *end;
1111
1112 size = strtoul (args, &end, 0);
1113 if (args == end)
1114 error (_("Invalid %s (bad syntax)."), config->name);
1115
1116 /* Instead of explicitly capping the size of a packet to or
1117 disallowing it, the user is allowed to set the size to
1118 something arbitrarily large. */
1119 }
1120
1121 /* So that the query shows the correct value. */
1122 if (size <= 0)
1123 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1124
1125 /* Extra checks? */
1126 if (fixed_p && !config->fixed_p)
1127 {
1128 if (! query (_("The target may not be able to correctly handle a %s\n"
1129 "of %ld bytes. Change the packet size? "),
1130 config->name, size))
1131 error (_("Packet size not changed."));
1132 }
1133 /* Update the config. */
1134 config->fixed_p = fixed_p;
1135 config->size = size;
1136 }
1137
1138 static void
1139 show_memory_packet_size (struct memory_packet_config *config)
1140 {
1141 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1142 if (config->fixed_p)
1143 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1144 get_memory_packet_size (config));
1145 else
1146 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1147 get_memory_packet_size (config));
1148 }
1149
1150 static struct memory_packet_config memory_write_packet_config =
1151 {
1152 "memory-write-packet-size",
1153 };
1154
1155 static void
1156 set_memory_write_packet_size (const char *args, int from_tty)
1157 {
1158 set_memory_packet_size (args, &memory_write_packet_config);
1159 }
1160
1161 static void
1162 show_memory_write_packet_size (const char *args, int from_tty)
1163 {
1164 show_memory_packet_size (&memory_write_packet_config);
1165 }
1166
1167 static long
1168 get_memory_write_packet_size (void)
1169 {
1170 return get_memory_packet_size (&memory_write_packet_config);
1171 }
1172
1173 static struct memory_packet_config memory_read_packet_config =
1174 {
1175 "memory-read-packet-size",
1176 };
1177
1178 static void
1179 set_memory_read_packet_size (const char *args, int from_tty)
1180 {
1181 set_memory_packet_size (args, &memory_read_packet_config);
1182 }
1183
1184 static void
1185 show_memory_read_packet_size (const char *args, int from_tty)
1186 {
1187 show_memory_packet_size (&memory_read_packet_config);
1188 }
1189
1190 static long
1191 get_memory_read_packet_size (void)
1192 {
1193 long size = get_memory_packet_size (&memory_read_packet_config);
1194
1195 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1196 extra buffer size argument before the memory read size can be
1197 increased beyond this. */
1198 if (size > get_remote_packet_size ())
1199 size = get_remote_packet_size ();
1200 return size;
1201 }
1202
1203 \f
1204 /* Generic configuration support for packets the stub optionally
1205 supports. Allows the user to specify the use of the packet as well
1206 as allowing GDB to auto-detect support in the remote stub. */
1207
1208 enum packet_support
1209 {
1210 PACKET_SUPPORT_UNKNOWN = 0,
1211 PACKET_ENABLE,
1212 PACKET_DISABLE
1213 };
1214
1215 struct packet_config
1216 {
1217 const char *name;
1218 const char *title;
1219
1220 /* If auto, GDB auto-detects support for this packet or feature,
1221 either through qSupported, or by trying the packet and looking
1222 at the response. If true, GDB assumes the target supports this
1223 packet. If false, the packet is disabled. Configs that don't
1224 have an associated command always have this set to auto. */
1225 enum auto_boolean detect;
1226
1227 /* Does the target support this packet? */
1228 enum packet_support support;
1229 };
1230
1231 /* Analyze a packet's return value and update the packet config
1232 accordingly. */
1233
1234 enum packet_result
1235 {
1236 PACKET_ERROR,
1237 PACKET_OK,
1238 PACKET_UNKNOWN
1239 };
1240
1241 static enum packet_support packet_config_support (struct packet_config *config);
1242 static enum packet_support packet_support (int packet);
1243
1244 static void
1245 show_packet_config_cmd (struct packet_config *config)
1246 {
1247 const char *support = "internal-error";
1248
1249 switch (packet_config_support (config))
1250 {
1251 case PACKET_ENABLE:
1252 support = "enabled";
1253 break;
1254 case PACKET_DISABLE:
1255 support = "disabled";
1256 break;
1257 case PACKET_SUPPORT_UNKNOWN:
1258 support = "unknown";
1259 break;
1260 }
1261 switch (config->detect)
1262 {
1263 case AUTO_BOOLEAN_AUTO:
1264 printf_filtered (_("Support for the `%s' packet "
1265 "is auto-detected, currently %s.\n"),
1266 config->name, support);
1267 break;
1268 case AUTO_BOOLEAN_TRUE:
1269 case AUTO_BOOLEAN_FALSE:
1270 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1271 config->name, support);
1272 break;
1273 }
1274 }
1275
1276 static void
1277 add_packet_config_cmd (struct packet_config *config, const char *name,
1278 const char *title, int legacy)
1279 {
1280 char *set_doc;
1281 char *show_doc;
1282 char *cmd_name;
1283
1284 config->name = name;
1285 config->title = title;
1286 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1287 name, title);
1288 show_doc = xstrprintf ("Show current use of remote "
1289 "protocol `%s' (%s) packet",
1290 name, title);
1291 /* set/show TITLE-packet {auto,on,off} */
1292 cmd_name = xstrprintf ("%s-packet", title);
1293 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1294 &config->detect, set_doc,
1295 show_doc, NULL, /* help_doc */
1296 NULL,
1297 show_remote_protocol_packet_cmd,
1298 &remote_set_cmdlist, &remote_show_cmdlist);
1299 /* The command code copies the documentation strings. */
1300 xfree (set_doc);
1301 xfree (show_doc);
1302 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1303 if (legacy)
1304 {
1305 char *legacy_name;
1306
1307 legacy_name = xstrprintf ("%s-packet", name);
1308 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1309 &remote_set_cmdlist);
1310 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1311 &remote_show_cmdlist);
1312 }
1313 }
1314
1315 static enum packet_result
1316 packet_check_result (const char *buf)
1317 {
1318 if (buf[0] != '\0')
1319 {
1320 /* The stub recognized the packet request. Check that the
1321 operation succeeded. */
1322 if (buf[0] == 'E'
1323 && isxdigit (buf[1]) && isxdigit (buf[2])
1324 && buf[3] == '\0')
1325 /* "Enn" - definitly an error. */
1326 return PACKET_ERROR;
1327
1328 /* Always treat "E." as an error. This will be used for
1329 more verbose error messages, such as E.memtypes. */
1330 if (buf[0] == 'E' && buf[1] == '.')
1331 return PACKET_ERROR;
1332
1333 /* The packet may or may not be OK. Just assume it is. */
1334 return PACKET_OK;
1335 }
1336 else
1337 /* The stub does not support the packet. */
1338 return PACKET_UNKNOWN;
1339 }
1340
1341 static enum packet_result
1342 packet_ok (const char *buf, struct packet_config *config)
1343 {
1344 enum packet_result result;
1345
1346 if (config->detect != AUTO_BOOLEAN_TRUE
1347 && config->support == PACKET_DISABLE)
1348 internal_error (__FILE__, __LINE__,
1349 _("packet_ok: attempt to use a disabled packet"));
1350
1351 result = packet_check_result (buf);
1352 switch (result)
1353 {
1354 case PACKET_OK:
1355 case PACKET_ERROR:
1356 /* The stub recognized the packet request. */
1357 if (config->support == PACKET_SUPPORT_UNKNOWN)
1358 {
1359 if (remote_debug)
1360 fprintf_unfiltered (gdb_stdlog,
1361 "Packet %s (%s) is supported\n",
1362 config->name, config->title);
1363 config->support = PACKET_ENABLE;
1364 }
1365 break;
1366 case PACKET_UNKNOWN:
1367 /* The stub does not support the packet. */
1368 if (config->detect == AUTO_BOOLEAN_AUTO
1369 && config->support == PACKET_ENABLE)
1370 {
1371 /* If the stub previously indicated that the packet was
1372 supported then there is a protocol error. */
1373 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1374 config->name, config->title);
1375 }
1376 else if (config->detect == AUTO_BOOLEAN_TRUE)
1377 {
1378 /* The user set it wrong. */
1379 error (_("Enabled packet %s (%s) not recognized by stub"),
1380 config->name, config->title);
1381 }
1382
1383 if (remote_debug)
1384 fprintf_unfiltered (gdb_stdlog,
1385 "Packet %s (%s) is NOT supported\n",
1386 config->name, config->title);
1387 config->support = PACKET_DISABLE;
1388 break;
1389 }
1390
1391 return result;
1392 }
1393
1394 enum {
1395 PACKET_vCont = 0,
1396 PACKET_X,
1397 PACKET_qSymbol,
1398 PACKET_P,
1399 PACKET_p,
1400 PACKET_Z0,
1401 PACKET_Z1,
1402 PACKET_Z2,
1403 PACKET_Z3,
1404 PACKET_Z4,
1405 PACKET_vFile_setfs,
1406 PACKET_vFile_open,
1407 PACKET_vFile_pread,
1408 PACKET_vFile_pwrite,
1409 PACKET_vFile_close,
1410 PACKET_vFile_unlink,
1411 PACKET_vFile_readlink,
1412 PACKET_vFile_fstat,
1413 PACKET_qXfer_auxv,
1414 PACKET_qXfer_features,
1415 PACKET_qXfer_exec_file,
1416 PACKET_qXfer_libraries,
1417 PACKET_qXfer_libraries_svr4,
1418 PACKET_qXfer_memory_map,
1419 PACKET_qXfer_spu_read,
1420 PACKET_qXfer_spu_write,
1421 PACKET_qXfer_osdata,
1422 PACKET_qXfer_threads,
1423 PACKET_qXfer_statictrace_read,
1424 PACKET_qXfer_traceframe_info,
1425 PACKET_qXfer_uib,
1426 PACKET_qGetTIBAddr,
1427 PACKET_qGetTLSAddr,
1428 PACKET_qSupported,
1429 PACKET_qTStatus,
1430 PACKET_QPassSignals,
1431 PACKET_QCatchSyscalls,
1432 PACKET_QProgramSignals,
1433 PACKET_QStartupWithShell,
1434 PACKET_QEnvironmentHexEncoded,
1435 PACKET_QEnvironmentReset,
1436 PACKET_QEnvironmentUnset,
1437 PACKET_qCRC,
1438 PACKET_qSearch_memory,
1439 PACKET_vAttach,
1440 PACKET_vRun,
1441 PACKET_QStartNoAckMode,
1442 PACKET_vKill,
1443 PACKET_qXfer_siginfo_read,
1444 PACKET_qXfer_siginfo_write,
1445 PACKET_qAttached,
1446
1447 /* Support for conditional tracepoints. */
1448 PACKET_ConditionalTracepoints,
1449
1450 /* Support for target-side breakpoint conditions. */
1451 PACKET_ConditionalBreakpoints,
1452
1453 /* Support for target-side breakpoint commands. */
1454 PACKET_BreakpointCommands,
1455
1456 /* Support for fast tracepoints. */
1457 PACKET_FastTracepoints,
1458
1459 /* Support for static tracepoints. */
1460 PACKET_StaticTracepoints,
1461
1462 /* Support for installing tracepoints while a trace experiment is
1463 running. */
1464 PACKET_InstallInTrace,
1465
1466 PACKET_bc,
1467 PACKET_bs,
1468 PACKET_TracepointSource,
1469 PACKET_QAllow,
1470 PACKET_qXfer_fdpic,
1471 PACKET_QDisableRandomization,
1472 PACKET_QAgent,
1473 PACKET_QTBuffer_size,
1474 PACKET_Qbtrace_off,
1475 PACKET_Qbtrace_bts,
1476 PACKET_Qbtrace_pt,
1477 PACKET_qXfer_btrace,
1478
1479 /* Support for the QNonStop packet. */
1480 PACKET_QNonStop,
1481
1482 /* Support for the QThreadEvents packet. */
1483 PACKET_QThreadEvents,
1484
1485 /* Support for multi-process extensions. */
1486 PACKET_multiprocess_feature,
1487
1488 /* Support for enabling and disabling tracepoints while a trace
1489 experiment is running. */
1490 PACKET_EnableDisableTracepoints_feature,
1491
1492 /* Support for collecting strings using the tracenz bytecode. */
1493 PACKET_tracenz_feature,
1494
1495 /* Support for continuing to run a trace experiment while GDB is
1496 disconnected. */
1497 PACKET_DisconnectedTracing_feature,
1498
1499 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1500 PACKET_augmented_libraries_svr4_read_feature,
1501
1502 /* Support for the qXfer:btrace-conf:read packet. */
1503 PACKET_qXfer_btrace_conf,
1504
1505 /* Support for the Qbtrace-conf:bts:size packet. */
1506 PACKET_Qbtrace_conf_bts_size,
1507
1508 /* Support for swbreak+ feature. */
1509 PACKET_swbreak_feature,
1510
1511 /* Support for hwbreak+ feature. */
1512 PACKET_hwbreak_feature,
1513
1514 /* Support for fork events. */
1515 PACKET_fork_event_feature,
1516
1517 /* Support for vfork events. */
1518 PACKET_vfork_event_feature,
1519
1520 /* Support for the Qbtrace-conf:pt:size packet. */
1521 PACKET_Qbtrace_conf_pt_size,
1522
1523 /* Support for exec events. */
1524 PACKET_exec_event_feature,
1525
1526 /* Support for query supported vCont actions. */
1527 PACKET_vContSupported,
1528
1529 /* Support remote CTRL-C. */
1530 PACKET_vCtrlC,
1531
1532 /* Support TARGET_WAITKIND_NO_RESUMED. */
1533 PACKET_no_resumed,
1534
1535 PACKET_MAX
1536 };
1537
1538 static struct packet_config remote_protocol_packets[PACKET_MAX];
1539
1540 /* Returns the packet's corresponding "set remote foo-packet" command
1541 state. See struct packet_config for more details. */
1542
1543 static enum auto_boolean
1544 packet_set_cmd_state (int packet)
1545 {
1546 return remote_protocol_packets[packet].detect;
1547 }
1548
1549 /* Returns whether a given packet or feature is supported. This takes
1550 into account the state of the corresponding "set remote foo-packet"
1551 command, which may be used to bypass auto-detection. */
1552
1553 static enum packet_support
1554 packet_config_support (struct packet_config *config)
1555 {
1556 switch (config->detect)
1557 {
1558 case AUTO_BOOLEAN_TRUE:
1559 return PACKET_ENABLE;
1560 case AUTO_BOOLEAN_FALSE:
1561 return PACKET_DISABLE;
1562 case AUTO_BOOLEAN_AUTO:
1563 return config->support;
1564 default:
1565 gdb_assert_not_reached (_("bad switch"));
1566 }
1567 }
1568
1569 /* Same as packet_config_support, but takes the packet's enum value as
1570 argument. */
1571
1572 static enum packet_support
1573 packet_support (int packet)
1574 {
1575 struct packet_config *config = &remote_protocol_packets[packet];
1576
1577 return packet_config_support (config);
1578 }
1579
1580 static void
1581 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1582 struct cmd_list_element *c,
1583 const char *value)
1584 {
1585 struct packet_config *packet;
1586
1587 for (packet = remote_protocol_packets;
1588 packet < &remote_protocol_packets[PACKET_MAX];
1589 packet++)
1590 {
1591 if (&packet->detect == c->var)
1592 {
1593 show_packet_config_cmd (packet);
1594 return;
1595 }
1596 }
1597 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1598 c->name);
1599 }
1600
1601 /* Should we try one of the 'Z' requests? */
1602
1603 enum Z_packet_type
1604 {
1605 Z_PACKET_SOFTWARE_BP,
1606 Z_PACKET_HARDWARE_BP,
1607 Z_PACKET_WRITE_WP,
1608 Z_PACKET_READ_WP,
1609 Z_PACKET_ACCESS_WP,
1610 NR_Z_PACKET_TYPES
1611 };
1612
1613 /* For compatibility with older distributions. Provide a ``set remote
1614 Z-packet ...'' command that updates all the Z packet types. */
1615
1616 static enum auto_boolean remote_Z_packet_detect;
1617
1618 static void
1619 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1620 struct cmd_list_element *c)
1621 {
1622 int i;
1623
1624 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1625 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1626 }
1627
1628 static void
1629 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1630 struct cmd_list_element *c,
1631 const char *value)
1632 {
1633 int i;
1634
1635 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1636 {
1637 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1638 }
1639 }
1640
1641 /* Returns true if the multi-process extensions are in effect. */
1642
1643 static int
1644 remote_multi_process_p (struct remote_state *rs)
1645 {
1646 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1647 }
1648
1649 /* Returns true if fork events are supported. */
1650
1651 static int
1652 remote_fork_event_p (struct remote_state *rs)
1653 {
1654 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1655 }
1656
1657 /* Returns true if vfork events are supported. */
1658
1659 static int
1660 remote_vfork_event_p (struct remote_state *rs)
1661 {
1662 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1663 }
1664
1665 /* Returns true if exec events are supported. */
1666
1667 static int
1668 remote_exec_event_p (struct remote_state *rs)
1669 {
1670 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1671 }
1672
1673 /* Insert fork catchpoint target routine. If fork events are enabled
1674 then return success, nothing more to do. */
1675
1676 static int
1677 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1678 {
1679 struct remote_state *rs = get_remote_state ();
1680
1681 return !remote_fork_event_p (rs);
1682 }
1683
1684 /* Remove fork catchpoint target routine. Nothing to do, just
1685 return success. */
1686
1687 static int
1688 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1689 {
1690 return 0;
1691 }
1692
1693 /* Insert vfork catchpoint target routine. If vfork events are enabled
1694 then return success, nothing more to do. */
1695
1696 static int
1697 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1698 {
1699 struct remote_state *rs = get_remote_state ();
1700
1701 return !remote_vfork_event_p (rs);
1702 }
1703
1704 /* Remove vfork catchpoint target routine. Nothing to do, just
1705 return success. */
1706
1707 static int
1708 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1709 {
1710 return 0;
1711 }
1712
1713 /* Insert exec catchpoint target routine. If exec events are
1714 enabled, just return success. */
1715
1716 static int
1717 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1718 {
1719 struct remote_state *rs = get_remote_state ();
1720
1721 return !remote_exec_event_p (rs);
1722 }
1723
1724 /* Remove exec catchpoint target routine. Nothing to do, just
1725 return success. */
1726
1727 static int
1728 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1729 {
1730 return 0;
1731 }
1732
1733 \f
1734 /* Asynchronous signal handle registered as event loop source for
1735 when we have pending events ready to be passed to the core. */
1736
1737 static struct async_event_handler *remote_async_inferior_event_token;
1738
1739 \f
1740
1741 static ptid_t magic_null_ptid;
1742 static ptid_t not_sent_ptid;
1743 static ptid_t any_thread_ptid;
1744
1745 /* Find out if the stub attached to PID (and hence GDB should offer to
1746 detach instead of killing it when bailing out). */
1747
1748 static int
1749 remote_query_attached (int pid)
1750 {
1751 struct remote_state *rs = get_remote_state ();
1752 size_t size = get_remote_packet_size ();
1753
1754 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1755 return 0;
1756
1757 if (remote_multi_process_p (rs))
1758 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1759 else
1760 xsnprintf (rs->buf, size, "qAttached");
1761
1762 putpkt (rs->buf);
1763 getpkt (&rs->buf, &rs->buf_size, 0);
1764
1765 switch (packet_ok (rs->buf,
1766 &remote_protocol_packets[PACKET_qAttached]))
1767 {
1768 case PACKET_OK:
1769 if (strcmp (rs->buf, "1") == 0)
1770 return 1;
1771 break;
1772 case PACKET_ERROR:
1773 warning (_("Remote failure reply: %s"), rs->buf);
1774 break;
1775 case PACKET_UNKNOWN:
1776 break;
1777 }
1778
1779 return 0;
1780 }
1781
1782 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1783 has been invented by GDB, instead of reported by the target. Since
1784 we can be connected to a remote system before before knowing about
1785 any inferior, mark the target with execution when we find the first
1786 inferior. If ATTACHED is 1, then we had just attached to this
1787 inferior. If it is 0, then we just created this inferior. If it
1788 is -1, then try querying the remote stub to find out if it had
1789 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1790 attempt to open this inferior's executable as the main executable
1791 if no main executable is open already. */
1792
1793 static struct inferior *
1794 remote_add_inferior (int fake_pid_p, int pid, int attached,
1795 int try_open_exec)
1796 {
1797 struct inferior *inf;
1798
1799 /* Check whether this process we're learning about is to be
1800 considered attached, or if is to be considered to have been
1801 spawned by the stub. */
1802 if (attached == -1)
1803 attached = remote_query_attached (pid);
1804
1805 if (gdbarch_has_global_solist (target_gdbarch ()))
1806 {
1807 /* If the target shares code across all inferiors, then every
1808 attach adds a new inferior. */
1809 inf = add_inferior (pid);
1810
1811 /* ... and every inferior is bound to the same program space.
1812 However, each inferior may still have its own address
1813 space. */
1814 inf->aspace = maybe_new_address_space ();
1815 inf->pspace = current_program_space;
1816 }
1817 else
1818 {
1819 /* In the traditional debugging scenario, there's a 1-1 match
1820 between program/address spaces. We simply bind the inferior
1821 to the program space's address space. */
1822 inf = current_inferior ();
1823 inferior_appeared (inf, pid);
1824 }
1825
1826 inf->attach_flag = attached;
1827 inf->fake_pid_p = fake_pid_p;
1828
1829 /* If no main executable is currently open then attempt to
1830 open the file that was executed to create this inferior. */
1831 if (try_open_exec && get_exec_file (0) == NULL)
1832 exec_file_locate_attach (pid, 0, 1);
1833
1834 return inf;
1835 }
1836
1837 static struct private_thread_info *
1838 get_private_info_thread (struct thread_info *info);
1839
1840 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1841 according to RUNNING. */
1842
1843 static void
1844 remote_add_thread (ptid_t ptid, int running, int executing)
1845 {
1846 struct remote_state *rs = get_remote_state ();
1847 struct thread_info *thread;
1848
1849 /* GDB historically didn't pull threads in the initial connection
1850 setup. If the remote target doesn't even have a concept of
1851 threads (e.g., a bare-metal target), even if internally we
1852 consider that a single-threaded target, mentioning a new thread
1853 might be confusing to the user. Be silent then, preserving the
1854 age old behavior. */
1855 if (rs->starting_up)
1856 thread = add_thread_silent (ptid);
1857 else
1858 thread = add_thread (ptid);
1859
1860 get_private_info_thread (thread)->vcont_resumed = executing;
1861 set_executing (ptid, executing);
1862 set_running (ptid, running);
1863 }
1864
1865 /* Come here when we learn about a thread id from the remote target.
1866 It may be the first time we hear about such thread, so take the
1867 opportunity to add it to GDB's thread list. In case this is the
1868 first time we're noticing its corresponding inferior, add it to
1869 GDB's inferior list as well. EXECUTING indicates whether the
1870 thread is (internally) executing or stopped. */
1871
1872 static void
1873 remote_notice_new_inferior (ptid_t currthread, int executing)
1874 {
1875 /* In non-stop mode, we assume new found threads are (externally)
1876 running until proven otherwise with a stop reply. In all-stop,
1877 we can only get here if all threads are stopped. */
1878 int running = target_is_non_stop_p () ? 1 : 0;
1879
1880 /* If this is a new thread, add it to GDB's thread list.
1881 If we leave it up to WFI to do this, bad things will happen. */
1882
1883 if (in_thread_list (currthread) && is_exited (currthread))
1884 {
1885 /* We're seeing an event on a thread id we knew had exited.
1886 This has to be a new thread reusing the old id. Add it. */
1887 remote_add_thread (currthread, running, executing);
1888 return;
1889 }
1890
1891 if (!in_thread_list (currthread))
1892 {
1893 struct inferior *inf = NULL;
1894 int pid = ptid_get_pid (currthread);
1895
1896 if (ptid_is_pid (inferior_ptid)
1897 && pid == ptid_get_pid (inferior_ptid))
1898 {
1899 /* inferior_ptid has no thread member yet. This can happen
1900 with the vAttach -> remote_wait,"TAAthread:" path if the
1901 stub doesn't support qC. This is the first stop reported
1902 after an attach, so this is the main thread. Update the
1903 ptid in the thread list. */
1904 if (in_thread_list (pid_to_ptid (pid)))
1905 thread_change_ptid (inferior_ptid, currthread);
1906 else
1907 {
1908 remote_add_thread (currthread, running, executing);
1909 inferior_ptid = currthread;
1910 }
1911 return;
1912 }
1913
1914 if (ptid_equal (magic_null_ptid, inferior_ptid))
1915 {
1916 /* inferior_ptid is not set yet. This can happen with the
1917 vRun -> remote_wait,"TAAthread:" path if the stub
1918 doesn't support qC. This is the first stop reported
1919 after an attach, so this is the main thread. Update the
1920 ptid in the thread list. */
1921 thread_change_ptid (inferior_ptid, currthread);
1922 return;
1923 }
1924
1925 /* When connecting to a target remote, or to a target
1926 extended-remote which already was debugging an inferior, we
1927 may not know about it yet. Add it before adding its child
1928 thread, so notifications are emitted in a sensible order. */
1929 if (!in_inferior_list (ptid_get_pid (currthread)))
1930 {
1931 struct remote_state *rs = get_remote_state ();
1932 int fake_pid_p = !remote_multi_process_p (rs);
1933
1934 inf = remote_add_inferior (fake_pid_p,
1935 ptid_get_pid (currthread), -1, 1);
1936 }
1937
1938 /* This is really a new thread. Add it. */
1939 remote_add_thread (currthread, running, executing);
1940
1941 /* If we found a new inferior, let the common code do whatever
1942 it needs to with it (e.g., read shared libraries, insert
1943 breakpoints), unless we're just setting up an all-stop
1944 connection. */
1945 if (inf != NULL)
1946 {
1947 struct remote_state *rs = get_remote_state ();
1948
1949 if (!rs->starting_up)
1950 notice_new_inferior (currthread, executing, 0);
1951 }
1952 }
1953 }
1954
1955 /* Return THREAD's private thread data, creating it if necessary. */
1956
1957 static struct private_thread_info *
1958 get_private_info_thread (struct thread_info *thread)
1959 {
1960 gdb_assert (thread != NULL);
1961
1962 if (thread->priv == NULL)
1963 {
1964 struct private_thread_info *priv = XNEW (struct private_thread_info);
1965
1966 thread->private_dtor = free_private_thread_info;
1967 thread->priv = priv;
1968
1969 priv->core = -1;
1970 priv->extra = NULL;
1971 priv->name = NULL;
1972 priv->name = NULL;
1973 priv->last_resume_step = 0;
1974 priv->last_resume_sig = GDB_SIGNAL_0;
1975 priv->vcont_resumed = 0;
1976 priv->thread_handle = nullptr;
1977 }
1978
1979 return thread->priv;
1980 }
1981
1982 /* Return PTID's private thread data, creating it if necessary. */
1983
1984 static struct private_thread_info *
1985 get_private_info_ptid (ptid_t ptid)
1986 {
1987 struct thread_info *info = find_thread_ptid (ptid);
1988
1989 return get_private_info_thread (info);
1990 }
1991
1992 /* Call this function as a result of
1993 1) A halt indication (T packet) containing a thread id
1994 2) A direct query of currthread
1995 3) Successful execution of set thread */
1996
1997 static void
1998 record_currthread (struct remote_state *rs, ptid_t currthread)
1999 {
2000 rs->general_thread = currthread;
2001 }
2002
2003 /* If 'QPassSignals' is supported, tell the remote stub what signals
2004 it can simply pass through to the inferior without reporting. */
2005
2006 static void
2007 remote_pass_signals (struct target_ops *self,
2008 int numsigs, unsigned char *pass_signals)
2009 {
2010 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2011 {
2012 char *pass_packet, *p;
2013 int count = 0, i;
2014 struct remote_state *rs = get_remote_state ();
2015
2016 gdb_assert (numsigs < 256);
2017 for (i = 0; i < numsigs; i++)
2018 {
2019 if (pass_signals[i])
2020 count++;
2021 }
2022 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2023 strcpy (pass_packet, "QPassSignals:");
2024 p = pass_packet + strlen (pass_packet);
2025 for (i = 0; i < numsigs; i++)
2026 {
2027 if (pass_signals[i])
2028 {
2029 if (i >= 16)
2030 *p++ = tohex (i >> 4);
2031 *p++ = tohex (i & 15);
2032 if (count)
2033 *p++ = ';';
2034 else
2035 break;
2036 count--;
2037 }
2038 }
2039 *p = 0;
2040 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2041 {
2042 putpkt (pass_packet);
2043 getpkt (&rs->buf, &rs->buf_size, 0);
2044 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2045 if (rs->last_pass_packet)
2046 xfree (rs->last_pass_packet);
2047 rs->last_pass_packet = pass_packet;
2048 }
2049 else
2050 xfree (pass_packet);
2051 }
2052 }
2053
2054 /* If 'QCatchSyscalls' is supported, tell the remote stub
2055 to report syscalls to GDB. */
2056
2057 static int
2058 remote_set_syscall_catchpoint (struct target_ops *self,
2059 int pid, int needed, int any_count,
2060 int table_size, int *table)
2061 {
2062 char *catch_packet;
2063 enum packet_result result;
2064 int n_sysno = 0;
2065
2066 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2067 {
2068 /* Not supported. */
2069 return 1;
2070 }
2071
2072 if (needed && !any_count)
2073 {
2074 int i;
2075
2076 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2077 for (i = 0; i < table_size; i++)
2078 {
2079 if (table[i] != 0)
2080 n_sysno++;
2081 }
2082 }
2083
2084 if (remote_debug)
2085 {
2086 fprintf_unfiltered (gdb_stdlog,
2087 "remote_set_syscall_catchpoint "
2088 "pid %d needed %d any_count %d n_sysno %d\n",
2089 pid, needed, any_count, n_sysno);
2090 }
2091
2092 if (needed)
2093 {
2094 /* Prepare a packet with the sysno list, assuming max 8+1
2095 characters for a sysno. If the resulting packet size is too
2096 big, fallback on the non-selective packet. */
2097 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2098
2099 catch_packet = (char *) xmalloc (maxpktsz);
2100 strcpy (catch_packet, "QCatchSyscalls:1");
2101 if (!any_count)
2102 {
2103 int i;
2104 char *p;
2105
2106 p = catch_packet;
2107 p += strlen (p);
2108
2109 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2110 for (i = 0; i < table_size; i++)
2111 {
2112 if (table[i] != 0)
2113 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2114 }
2115 }
2116 if (strlen (catch_packet) > get_remote_packet_size ())
2117 {
2118 /* catch_packet too big. Fallback to less efficient
2119 non selective mode, with GDB doing the filtering. */
2120 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2121 }
2122 }
2123 else
2124 catch_packet = xstrdup ("QCatchSyscalls:0");
2125
2126 {
2127 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2128 struct remote_state *rs = get_remote_state ();
2129
2130 putpkt (catch_packet);
2131 getpkt (&rs->buf, &rs->buf_size, 0);
2132 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2133 do_cleanups (old_chain);
2134 if (result == PACKET_OK)
2135 return 0;
2136 else
2137 return -1;
2138 }
2139 }
2140
2141 /* If 'QProgramSignals' is supported, tell the remote stub what
2142 signals it should pass through to the inferior when detaching. */
2143
2144 static void
2145 remote_program_signals (struct target_ops *self,
2146 int numsigs, unsigned char *signals)
2147 {
2148 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2149 {
2150 char *packet, *p;
2151 int count = 0, i;
2152 struct remote_state *rs = get_remote_state ();
2153
2154 gdb_assert (numsigs < 256);
2155 for (i = 0; i < numsigs; i++)
2156 {
2157 if (signals[i])
2158 count++;
2159 }
2160 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2161 strcpy (packet, "QProgramSignals:");
2162 p = packet + strlen (packet);
2163 for (i = 0; i < numsigs; i++)
2164 {
2165 if (signal_pass_state (i))
2166 {
2167 if (i >= 16)
2168 *p++ = tohex (i >> 4);
2169 *p++ = tohex (i & 15);
2170 if (count)
2171 *p++ = ';';
2172 else
2173 break;
2174 count--;
2175 }
2176 }
2177 *p = 0;
2178 if (!rs->last_program_signals_packet
2179 || strcmp (rs->last_program_signals_packet, packet) != 0)
2180 {
2181 putpkt (packet);
2182 getpkt (&rs->buf, &rs->buf_size, 0);
2183 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2184 xfree (rs->last_program_signals_packet);
2185 rs->last_program_signals_packet = packet;
2186 }
2187 else
2188 xfree (packet);
2189 }
2190 }
2191
2192 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2193 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2194 thread. If GEN is set, set the general thread, if not, then set
2195 the step/continue thread. */
2196 static void
2197 set_thread (ptid_t ptid, int gen)
2198 {
2199 struct remote_state *rs = get_remote_state ();
2200 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2201 char *buf = rs->buf;
2202 char *endbuf = rs->buf + get_remote_packet_size ();
2203
2204 if (ptid_equal (state, ptid))
2205 return;
2206
2207 *buf++ = 'H';
2208 *buf++ = gen ? 'g' : 'c';
2209 if (ptid_equal (ptid, magic_null_ptid))
2210 xsnprintf (buf, endbuf - buf, "0");
2211 else if (ptid_equal (ptid, any_thread_ptid))
2212 xsnprintf (buf, endbuf - buf, "0");
2213 else if (ptid_equal (ptid, minus_one_ptid))
2214 xsnprintf (buf, endbuf - buf, "-1");
2215 else
2216 write_ptid (buf, endbuf, ptid);
2217 putpkt (rs->buf);
2218 getpkt (&rs->buf, &rs->buf_size, 0);
2219 if (gen)
2220 rs->general_thread = ptid;
2221 else
2222 rs->continue_thread = ptid;
2223 }
2224
2225 static void
2226 set_general_thread (ptid_t ptid)
2227 {
2228 set_thread (ptid, 1);
2229 }
2230
2231 static void
2232 set_continue_thread (ptid_t ptid)
2233 {
2234 set_thread (ptid, 0);
2235 }
2236
2237 /* Change the remote current process. Which thread within the process
2238 ends up selected isn't important, as long as it is the same process
2239 as what INFERIOR_PTID points to.
2240
2241 This comes from that fact that there is no explicit notion of
2242 "selected process" in the protocol. The selected process for
2243 general operations is the process the selected general thread
2244 belongs to. */
2245
2246 static void
2247 set_general_process (void)
2248 {
2249 struct remote_state *rs = get_remote_state ();
2250
2251 /* If the remote can't handle multiple processes, don't bother. */
2252 if (!remote_multi_process_p (rs))
2253 return;
2254
2255 /* We only need to change the remote current thread if it's pointing
2256 at some other process. */
2257 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2258 set_general_thread (inferior_ptid);
2259 }
2260
2261 \f
2262 /* Return nonzero if this is the main thread that we made up ourselves
2263 to model non-threaded targets as single-threaded. */
2264
2265 static int
2266 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2267 {
2268 if (ptid_equal (ptid, magic_null_ptid))
2269 /* The main thread is always alive. */
2270 return 1;
2271
2272 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2273 /* The main thread is always alive. This can happen after a
2274 vAttach, if the remote side doesn't support
2275 multi-threading. */
2276 return 1;
2277
2278 return 0;
2279 }
2280
2281 /* Return nonzero if the thread PTID is still alive on the remote
2282 system. */
2283
2284 static int
2285 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2286 {
2287 struct remote_state *rs = get_remote_state ();
2288 char *p, *endp;
2289
2290 /* Check if this is a thread that we made up ourselves to model
2291 non-threaded targets as single-threaded. */
2292 if (remote_thread_always_alive (ops, ptid))
2293 return 1;
2294
2295 p = rs->buf;
2296 endp = rs->buf + get_remote_packet_size ();
2297
2298 *p++ = 'T';
2299 write_ptid (p, endp, ptid);
2300
2301 putpkt (rs->buf);
2302 getpkt (&rs->buf, &rs->buf_size, 0);
2303 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2304 }
2305
2306 /* Return a pointer to a thread name if we know it and NULL otherwise.
2307 The thread_info object owns the memory for the name. */
2308
2309 static const char *
2310 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2311 {
2312 if (info->priv != NULL)
2313 return info->priv->name;
2314
2315 return NULL;
2316 }
2317
2318 /* About these extended threadlist and threadinfo packets. They are
2319 variable length packets but, the fields within them are often fixed
2320 length. They are redundent enough to send over UDP as is the
2321 remote protocol in general. There is a matching unit test module
2322 in libstub. */
2323
2324 /* WARNING: This threadref data structure comes from the remote O.S.,
2325 libstub protocol encoding, and remote.c. It is not particularly
2326 changable. */
2327
2328 /* Right now, the internal structure is int. We want it to be bigger.
2329 Plan to fix this. */
2330
2331 typedef int gdb_threadref; /* Internal GDB thread reference. */
2332
2333 /* gdb_ext_thread_info is an internal GDB data structure which is
2334 equivalent to the reply of the remote threadinfo packet. */
2335
2336 struct gdb_ext_thread_info
2337 {
2338 threadref threadid; /* External form of thread reference. */
2339 int active; /* Has state interesting to GDB?
2340 regs, stack. */
2341 char display[256]; /* Brief state display, name,
2342 blocked/suspended. */
2343 char shortname[32]; /* To be used to name threads. */
2344 char more_display[256]; /* Long info, statistics, queue depth,
2345 whatever. */
2346 };
2347
2348 /* The volume of remote transfers can be limited by submitting
2349 a mask containing bits specifying the desired information.
2350 Use a union of these values as the 'selection' parameter to
2351 get_thread_info. FIXME: Make these TAG names more thread specific. */
2352
2353 #define TAG_THREADID 1
2354 #define TAG_EXISTS 2
2355 #define TAG_DISPLAY 4
2356 #define TAG_THREADNAME 8
2357 #define TAG_MOREDISPLAY 16
2358
2359 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2360
2361 static char *unpack_nibble (char *buf, int *val);
2362
2363 static char *unpack_byte (char *buf, int *value);
2364
2365 static char *pack_int (char *buf, int value);
2366
2367 static char *unpack_int (char *buf, int *value);
2368
2369 static char *unpack_string (char *src, char *dest, int length);
2370
2371 static char *pack_threadid (char *pkt, threadref *id);
2372
2373 static char *unpack_threadid (char *inbuf, threadref *id);
2374
2375 void int_to_threadref (threadref *id, int value);
2376
2377 static int threadref_to_int (threadref *ref);
2378
2379 static void copy_threadref (threadref *dest, threadref *src);
2380
2381 static int threadmatch (threadref *dest, threadref *src);
2382
2383 static char *pack_threadinfo_request (char *pkt, int mode,
2384 threadref *id);
2385
2386 static int remote_unpack_thread_info_response (char *pkt,
2387 threadref *expectedref,
2388 struct gdb_ext_thread_info
2389 *info);
2390
2391
2392 static int remote_get_threadinfo (threadref *threadid,
2393 int fieldset, /*TAG mask */
2394 struct gdb_ext_thread_info *info);
2395
2396 static char *pack_threadlist_request (char *pkt, int startflag,
2397 int threadcount,
2398 threadref *nextthread);
2399
2400 static int parse_threadlist_response (char *pkt,
2401 int result_limit,
2402 threadref *original_echo,
2403 threadref *resultlist,
2404 int *doneflag);
2405
2406 static int remote_get_threadlist (int startflag,
2407 threadref *nextthread,
2408 int result_limit,
2409 int *done,
2410 int *result_count,
2411 threadref *threadlist);
2412
2413 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2414
2415 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2416 void *context, int looplimit);
2417
2418 static int remote_newthread_step (threadref *ref, void *context);
2419
2420
2421 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2422 buffer we're allowed to write to. Returns
2423 BUF+CHARACTERS_WRITTEN. */
2424
2425 static char *
2426 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2427 {
2428 int pid, tid;
2429 struct remote_state *rs = get_remote_state ();
2430
2431 if (remote_multi_process_p (rs))
2432 {
2433 pid = ptid_get_pid (ptid);
2434 if (pid < 0)
2435 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2436 else
2437 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2438 }
2439 tid = ptid_get_lwp (ptid);
2440 if (tid < 0)
2441 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2442 else
2443 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2444
2445 return buf;
2446 }
2447
2448 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2449 passed the last parsed char. Returns null_ptid on error. */
2450
2451 static ptid_t
2452 read_ptid (char *buf, char **obuf)
2453 {
2454 char *p = buf;
2455 char *pp;
2456 ULONGEST pid = 0, tid = 0;
2457
2458 if (*p == 'p')
2459 {
2460 /* Multi-process ptid. */
2461 pp = unpack_varlen_hex (p + 1, &pid);
2462 if (*pp != '.')
2463 error (_("invalid remote ptid: %s"), p);
2464
2465 p = pp;
2466 pp = unpack_varlen_hex (p + 1, &tid);
2467 if (obuf)
2468 *obuf = pp;
2469 return ptid_build (pid, tid, 0);
2470 }
2471
2472 /* No multi-process. Just a tid. */
2473 pp = unpack_varlen_hex (p, &tid);
2474
2475 /* Return null_ptid when no thread id is found. */
2476 if (p == pp)
2477 {
2478 if (obuf)
2479 *obuf = pp;
2480 return null_ptid;
2481 }
2482
2483 /* Since the stub is not sending a process id, then default to
2484 what's in inferior_ptid, unless it's null at this point. If so,
2485 then since there's no way to know the pid of the reported
2486 threads, use the magic number. */
2487 if (ptid_equal (inferior_ptid, null_ptid))
2488 pid = ptid_get_pid (magic_null_ptid);
2489 else
2490 pid = ptid_get_pid (inferior_ptid);
2491
2492 if (obuf)
2493 *obuf = pp;
2494 return ptid_build (pid, tid, 0);
2495 }
2496
2497 static int
2498 stubhex (int ch)
2499 {
2500 if (ch >= 'a' && ch <= 'f')
2501 return ch - 'a' + 10;
2502 if (ch >= '0' && ch <= '9')
2503 return ch - '0';
2504 if (ch >= 'A' && ch <= 'F')
2505 return ch - 'A' + 10;
2506 return -1;
2507 }
2508
2509 static int
2510 stub_unpack_int (char *buff, int fieldlength)
2511 {
2512 int nibble;
2513 int retval = 0;
2514
2515 while (fieldlength)
2516 {
2517 nibble = stubhex (*buff++);
2518 retval |= nibble;
2519 fieldlength--;
2520 if (fieldlength)
2521 retval = retval << 4;
2522 }
2523 return retval;
2524 }
2525
2526 static char *
2527 unpack_nibble (char *buf, int *val)
2528 {
2529 *val = fromhex (*buf++);
2530 return buf;
2531 }
2532
2533 static char *
2534 unpack_byte (char *buf, int *value)
2535 {
2536 *value = stub_unpack_int (buf, 2);
2537 return buf + 2;
2538 }
2539
2540 static char *
2541 pack_int (char *buf, int value)
2542 {
2543 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2544 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2545 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2546 buf = pack_hex_byte (buf, (value & 0xff));
2547 return buf;
2548 }
2549
2550 static char *
2551 unpack_int (char *buf, int *value)
2552 {
2553 *value = stub_unpack_int (buf, 8);
2554 return buf + 8;
2555 }
2556
2557 #if 0 /* Currently unused, uncomment when needed. */
2558 static char *pack_string (char *pkt, char *string);
2559
2560 static char *
2561 pack_string (char *pkt, char *string)
2562 {
2563 char ch;
2564 int len;
2565
2566 len = strlen (string);
2567 if (len > 200)
2568 len = 200; /* Bigger than most GDB packets, junk??? */
2569 pkt = pack_hex_byte (pkt, len);
2570 while (len-- > 0)
2571 {
2572 ch = *string++;
2573 if ((ch == '\0') || (ch == '#'))
2574 ch = '*'; /* Protect encapsulation. */
2575 *pkt++ = ch;
2576 }
2577 return pkt;
2578 }
2579 #endif /* 0 (unused) */
2580
2581 static char *
2582 unpack_string (char *src, char *dest, int length)
2583 {
2584 while (length--)
2585 *dest++ = *src++;
2586 *dest = '\0';
2587 return src;
2588 }
2589
2590 static char *
2591 pack_threadid (char *pkt, threadref *id)
2592 {
2593 char *limit;
2594 unsigned char *altid;
2595
2596 altid = (unsigned char *) id;
2597 limit = pkt + BUF_THREAD_ID_SIZE;
2598 while (pkt < limit)
2599 pkt = pack_hex_byte (pkt, *altid++);
2600 return pkt;
2601 }
2602
2603
2604 static char *
2605 unpack_threadid (char *inbuf, threadref *id)
2606 {
2607 char *altref;
2608 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2609 int x, y;
2610
2611 altref = (char *) id;
2612
2613 while (inbuf < limit)
2614 {
2615 x = stubhex (*inbuf++);
2616 y = stubhex (*inbuf++);
2617 *altref++ = (x << 4) | y;
2618 }
2619 return inbuf;
2620 }
2621
2622 /* Externally, threadrefs are 64 bits but internally, they are still
2623 ints. This is due to a mismatch of specifications. We would like
2624 to use 64bit thread references internally. This is an adapter
2625 function. */
2626
2627 void
2628 int_to_threadref (threadref *id, int value)
2629 {
2630 unsigned char *scan;
2631
2632 scan = (unsigned char *) id;
2633 {
2634 int i = 4;
2635 while (i--)
2636 *scan++ = 0;
2637 }
2638 *scan++ = (value >> 24) & 0xff;
2639 *scan++ = (value >> 16) & 0xff;
2640 *scan++ = (value >> 8) & 0xff;
2641 *scan++ = (value & 0xff);
2642 }
2643
2644 static int
2645 threadref_to_int (threadref *ref)
2646 {
2647 int i, value = 0;
2648 unsigned char *scan;
2649
2650 scan = *ref;
2651 scan += 4;
2652 i = 4;
2653 while (i-- > 0)
2654 value = (value << 8) | ((*scan++) & 0xff);
2655 return value;
2656 }
2657
2658 static void
2659 copy_threadref (threadref *dest, threadref *src)
2660 {
2661 int i;
2662 unsigned char *csrc, *cdest;
2663
2664 csrc = (unsigned char *) src;
2665 cdest = (unsigned char *) dest;
2666 i = 8;
2667 while (i--)
2668 *cdest++ = *csrc++;
2669 }
2670
2671 static int
2672 threadmatch (threadref *dest, threadref *src)
2673 {
2674 /* Things are broken right now, so just assume we got a match. */
2675 #if 0
2676 unsigned char *srcp, *destp;
2677 int i, result;
2678 srcp = (char *) src;
2679 destp = (char *) dest;
2680
2681 result = 1;
2682 while (i-- > 0)
2683 result &= (*srcp++ == *destp++) ? 1 : 0;
2684 return result;
2685 #endif
2686 return 1;
2687 }
2688
2689 /*
2690 threadid:1, # always request threadid
2691 context_exists:2,
2692 display:4,
2693 unique_name:8,
2694 more_display:16
2695 */
2696
2697 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2698
2699 static char *
2700 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2701 {
2702 *pkt++ = 'q'; /* Info Query */
2703 *pkt++ = 'P'; /* process or thread info */
2704 pkt = pack_int (pkt, mode); /* mode */
2705 pkt = pack_threadid (pkt, id); /* threadid */
2706 *pkt = '\0'; /* terminate */
2707 return pkt;
2708 }
2709
2710 /* These values tag the fields in a thread info response packet. */
2711 /* Tagging the fields allows us to request specific fields and to
2712 add more fields as time goes by. */
2713
2714 #define TAG_THREADID 1 /* Echo the thread identifier. */
2715 #define TAG_EXISTS 2 /* Is this process defined enough to
2716 fetch registers and its stack? */
2717 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2718 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2719 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2720 the process. */
2721
2722 static int
2723 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2724 struct gdb_ext_thread_info *info)
2725 {
2726 struct remote_state *rs = get_remote_state ();
2727 int mask, length;
2728 int tag;
2729 threadref ref;
2730 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2731 int retval = 1;
2732
2733 /* info->threadid = 0; FIXME: implement zero_threadref. */
2734 info->active = 0;
2735 info->display[0] = '\0';
2736 info->shortname[0] = '\0';
2737 info->more_display[0] = '\0';
2738
2739 /* Assume the characters indicating the packet type have been
2740 stripped. */
2741 pkt = unpack_int (pkt, &mask); /* arg mask */
2742 pkt = unpack_threadid (pkt, &ref);
2743
2744 if (mask == 0)
2745 warning (_("Incomplete response to threadinfo request."));
2746 if (!threadmatch (&ref, expectedref))
2747 { /* This is an answer to a different request. */
2748 warning (_("ERROR RMT Thread info mismatch."));
2749 return 0;
2750 }
2751 copy_threadref (&info->threadid, &ref);
2752
2753 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2754
2755 /* Packets are terminated with nulls. */
2756 while ((pkt < limit) && mask && *pkt)
2757 {
2758 pkt = unpack_int (pkt, &tag); /* tag */
2759 pkt = unpack_byte (pkt, &length); /* length */
2760 if (!(tag & mask)) /* Tags out of synch with mask. */
2761 {
2762 warning (_("ERROR RMT: threadinfo tag mismatch."));
2763 retval = 0;
2764 break;
2765 }
2766 if (tag == TAG_THREADID)
2767 {
2768 if (length != 16)
2769 {
2770 warning (_("ERROR RMT: length of threadid is not 16."));
2771 retval = 0;
2772 break;
2773 }
2774 pkt = unpack_threadid (pkt, &ref);
2775 mask = mask & ~TAG_THREADID;
2776 continue;
2777 }
2778 if (tag == TAG_EXISTS)
2779 {
2780 info->active = stub_unpack_int (pkt, length);
2781 pkt += length;
2782 mask = mask & ~(TAG_EXISTS);
2783 if (length > 8)
2784 {
2785 warning (_("ERROR RMT: 'exists' length too long."));
2786 retval = 0;
2787 break;
2788 }
2789 continue;
2790 }
2791 if (tag == TAG_THREADNAME)
2792 {
2793 pkt = unpack_string (pkt, &info->shortname[0], length);
2794 mask = mask & ~TAG_THREADNAME;
2795 continue;
2796 }
2797 if (tag == TAG_DISPLAY)
2798 {
2799 pkt = unpack_string (pkt, &info->display[0], length);
2800 mask = mask & ~TAG_DISPLAY;
2801 continue;
2802 }
2803 if (tag == TAG_MOREDISPLAY)
2804 {
2805 pkt = unpack_string (pkt, &info->more_display[0], length);
2806 mask = mask & ~TAG_MOREDISPLAY;
2807 continue;
2808 }
2809 warning (_("ERROR RMT: unknown thread info tag."));
2810 break; /* Not a tag we know about. */
2811 }
2812 return retval;
2813 }
2814
2815 static int
2816 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2817 struct gdb_ext_thread_info *info)
2818 {
2819 struct remote_state *rs = get_remote_state ();
2820 int result;
2821
2822 pack_threadinfo_request (rs->buf, fieldset, threadid);
2823 putpkt (rs->buf);
2824 getpkt (&rs->buf, &rs->buf_size, 0);
2825
2826 if (rs->buf[0] == '\0')
2827 return 0;
2828
2829 result = remote_unpack_thread_info_response (rs->buf + 2,
2830 threadid, info);
2831 return result;
2832 }
2833
2834 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2835
2836 static char *
2837 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2838 threadref *nextthread)
2839 {
2840 *pkt++ = 'q'; /* info query packet */
2841 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2842 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2843 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2844 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2845 *pkt = '\0';
2846 return pkt;
2847 }
2848
2849 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2850
2851 static int
2852 parse_threadlist_response (char *pkt, int result_limit,
2853 threadref *original_echo, threadref *resultlist,
2854 int *doneflag)
2855 {
2856 struct remote_state *rs = get_remote_state ();
2857 char *limit;
2858 int count, resultcount, done;
2859
2860 resultcount = 0;
2861 /* Assume the 'q' and 'M chars have been stripped. */
2862 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2863 /* done parse past here */
2864 pkt = unpack_byte (pkt, &count); /* count field */
2865 pkt = unpack_nibble (pkt, &done);
2866 /* The first threadid is the argument threadid. */
2867 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2868 while ((count-- > 0) && (pkt < limit))
2869 {
2870 pkt = unpack_threadid (pkt, resultlist++);
2871 if (resultcount++ >= result_limit)
2872 break;
2873 }
2874 if (doneflag)
2875 *doneflag = done;
2876 return resultcount;
2877 }
2878
2879 /* Fetch the next batch of threads from the remote. Returns -1 if the
2880 qL packet is not supported, 0 on error and 1 on success. */
2881
2882 static int
2883 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2884 int *done, int *result_count, threadref *threadlist)
2885 {
2886 struct remote_state *rs = get_remote_state ();
2887 int result = 1;
2888
2889 /* Trancate result limit to be smaller than the packet size. */
2890 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2891 >= get_remote_packet_size ())
2892 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2893
2894 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2895 putpkt (rs->buf);
2896 getpkt (&rs->buf, &rs->buf_size, 0);
2897 if (*rs->buf == '\0')
2898 {
2899 /* Packet not supported. */
2900 return -1;
2901 }
2902
2903 *result_count =
2904 parse_threadlist_response (rs->buf + 2, result_limit,
2905 &rs->echo_nextthread, threadlist, done);
2906
2907 if (!threadmatch (&rs->echo_nextthread, nextthread))
2908 {
2909 /* FIXME: This is a good reason to drop the packet. */
2910 /* Possably, there is a duplicate response. */
2911 /* Possabilities :
2912 retransmit immediatly - race conditions
2913 retransmit after timeout - yes
2914 exit
2915 wait for packet, then exit
2916 */
2917 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2918 return 0; /* I choose simply exiting. */
2919 }
2920 if (*result_count <= 0)
2921 {
2922 if (*done != 1)
2923 {
2924 warning (_("RMT ERROR : failed to get remote thread list."));
2925 result = 0;
2926 }
2927 return result; /* break; */
2928 }
2929 if (*result_count > result_limit)
2930 {
2931 *result_count = 0;
2932 warning (_("RMT ERROR: threadlist response longer than requested."));
2933 return 0;
2934 }
2935 return result;
2936 }
2937
2938 /* Fetch the list of remote threads, with the qL packet, and call
2939 STEPFUNCTION for each thread found. Stops iterating and returns 1
2940 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2941 STEPFUNCTION returns false. If the packet is not supported,
2942 returns -1. */
2943
2944 static int
2945 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2946 int looplimit)
2947 {
2948 struct remote_state *rs = get_remote_state ();
2949 int done, i, result_count;
2950 int startflag = 1;
2951 int result = 1;
2952 int loopcount = 0;
2953
2954 done = 0;
2955 while (!done)
2956 {
2957 if (loopcount++ > looplimit)
2958 {
2959 result = 0;
2960 warning (_("Remote fetch threadlist -infinite loop-."));
2961 break;
2962 }
2963 result = remote_get_threadlist (startflag, &rs->nextthread,
2964 MAXTHREADLISTRESULTS,
2965 &done, &result_count,
2966 rs->resultthreadlist);
2967 if (result <= 0)
2968 break;
2969 /* Clear for later iterations. */
2970 startflag = 0;
2971 /* Setup to resume next batch of thread references, set nextthread. */
2972 if (result_count >= 1)
2973 copy_threadref (&rs->nextthread,
2974 &rs->resultthreadlist[result_count - 1]);
2975 i = 0;
2976 while (result_count--)
2977 {
2978 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2979 {
2980 result = 0;
2981 break;
2982 }
2983 }
2984 }
2985 return result;
2986 }
2987
2988 /* A thread found on the remote target. */
2989
2990 typedef struct thread_item
2991 {
2992 /* The thread's PTID. */
2993 ptid_t ptid;
2994
2995 /* The thread's extra info. May be NULL. */
2996 char *extra;
2997
2998 /* The thread's name. May be NULL. */
2999 char *name;
3000
3001 /* The core the thread was running on. -1 if not known. */
3002 int core;
3003
3004 /* The thread handle associated with the thread. */
3005 gdb::byte_vector *thread_handle;
3006
3007 } thread_item_t;
3008 DEF_VEC_O(thread_item_t);
3009
3010 /* Context passed around to the various methods listing remote
3011 threads. As new threads are found, they're added to the ITEMS
3012 vector. */
3013
3014 struct threads_listing_context
3015 {
3016 /* The threads found on the remote target. */
3017 VEC (thread_item_t) *items;
3018 };
3019
3020 /* Discard the contents of the constructed thread listing context. */
3021
3022 static void
3023 clear_threads_listing_context (void *p)
3024 {
3025 struct threads_listing_context *context
3026 = (struct threads_listing_context *) p;
3027 int i;
3028 struct thread_item *item;
3029
3030 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3031 {
3032 xfree (item->extra);
3033 xfree (item->name);
3034 delete item->thread_handle;
3035 }
3036
3037 VEC_free (thread_item_t, context->items);
3038 }
3039
3040 /* Remove the thread specified as the related_pid field of WS
3041 from the CONTEXT list. */
3042
3043 static void
3044 threads_listing_context_remove (struct target_waitstatus *ws,
3045 struct threads_listing_context *context)
3046 {
3047 struct thread_item *item;
3048 int i;
3049 ptid_t child_ptid = ws->value.related_pid;
3050
3051 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3052 {
3053 if (ptid_equal (item->ptid, child_ptid))
3054 {
3055 VEC_ordered_remove (thread_item_t, context->items, i);
3056 break;
3057 }
3058 }
3059 }
3060
3061 static int
3062 remote_newthread_step (threadref *ref, void *data)
3063 {
3064 struct threads_listing_context *context
3065 = (struct threads_listing_context *) data;
3066 struct thread_item item;
3067 int pid = ptid_get_pid (inferior_ptid);
3068
3069 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3070 item.core = -1;
3071 item.name = NULL;
3072 item.extra = NULL;
3073 item.thread_handle = nullptr;
3074
3075 VEC_safe_push (thread_item_t, context->items, &item);
3076
3077 return 1; /* continue iterator */
3078 }
3079
3080 #define CRAZY_MAX_THREADS 1000
3081
3082 static ptid_t
3083 remote_current_thread (ptid_t oldpid)
3084 {
3085 struct remote_state *rs = get_remote_state ();
3086
3087 putpkt ("qC");
3088 getpkt (&rs->buf, &rs->buf_size, 0);
3089 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3090 {
3091 char *obuf;
3092 ptid_t result;
3093
3094 result = read_ptid (&rs->buf[2], &obuf);
3095 if (*obuf != '\0' && remote_debug)
3096 fprintf_unfiltered (gdb_stdlog,
3097 "warning: garbage in qC reply\n");
3098
3099 return result;
3100 }
3101 else
3102 return oldpid;
3103 }
3104
3105 /* List remote threads using the deprecated qL packet. */
3106
3107 static int
3108 remote_get_threads_with_ql (struct target_ops *ops,
3109 struct threads_listing_context *context)
3110 {
3111 if (remote_threadlist_iterator (remote_newthread_step, context,
3112 CRAZY_MAX_THREADS) >= 0)
3113 return 1;
3114
3115 return 0;
3116 }
3117
3118 #if defined(HAVE_LIBEXPAT)
3119
3120 static void
3121 start_thread (struct gdb_xml_parser *parser,
3122 const struct gdb_xml_element *element,
3123 void *user_data, VEC(gdb_xml_value_s) *attributes)
3124 {
3125 struct threads_listing_context *data
3126 = (struct threads_listing_context *) user_data;
3127
3128 struct thread_item item;
3129 char *id;
3130 struct gdb_xml_value *attr;
3131
3132 id = (char *) xml_find_attribute (attributes, "id")->value;
3133 item.ptid = read_ptid (id, NULL);
3134
3135 attr = xml_find_attribute (attributes, "core");
3136 if (attr != NULL)
3137 item.core = *(ULONGEST *) attr->value;
3138 else
3139 item.core = -1;
3140
3141 attr = xml_find_attribute (attributes, "name");
3142 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3143
3144 attr = xml_find_attribute (attributes, "handle");
3145 if (attr != NULL)
3146 {
3147 item.thread_handle = new gdb::byte_vector
3148 (strlen ((const char *) attr->value) / 2);
3149 hex2bin ((const char *) attr->value, item.thread_handle->data (),
3150 item.thread_handle->size ());
3151 }
3152 else
3153 item.thread_handle = nullptr;
3154
3155 item.extra = 0;
3156
3157 VEC_safe_push (thread_item_t, data->items, &item);
3158 }
3159
3160 static void
3161 end_thread (struct gdb_xml_parser *parser,
3162 const struct gdb_xml_element *element,
3163 void *user_data, const char *body_text)
3164 {
3165 struct threads_listing_context *data
3166 = (struct threads_listing_context *) user_data;
3167
3168 if (body_text && *body_text)
3169 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3170 }
3171
3172 const struct gdb_xml_attribute thread_attributes[] = {
3173 { "id", GDB_XML_AF_NONE, NULL, NULL },
3174 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3175 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3176 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3177 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3178 };
3179
3180 const struct gdb_xml_element thread_children[] = {
3181 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3182 };
3183
3184 const struct gdb_xml_element threads_children[] = {
3185 { "thread", thread_attributes, thread_children,
3186 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3187 start_thread, end_thread },
3188 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3189 };
3190
3191 const struct gdb_xml_element threads_elements[] = {
3192 { "threads", NULL, threads_children,
3193 GDB_XML_EF_NONE, NULL, NULL },
3194 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3195 };
3196
3197 #endif
3198
3199 /* List remote threads using qXfer:threads:read. */
3200
3201 static int
3202 remote_get_threads_with_qxfer (struct target_ops *ops,
3203 struct threads_listing_context *context)
3204 {
3205 #if defined(HAVE_LIBEXPAT)
3206 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3207 {
3208 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3209 struct cleanup *back_to = make_cleanup (xfree, xml);
3210
3211 if (xml != NULL && *xml != '\0')
3212 {
3213 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3214 threads_elements, xml, context);
3215 }
3216
3217 do_cleanups (back_to);
3218 return 1;
3219 }
3220 #endif
3221
3222 return 0;
3223 }
3224
3225 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3226
3227 static int
3228 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3229 struct threads_listing_context *context)
3230 {
3231 struct remote_state *rs = get_remote_state ();
3232
3233 if (rs->use_threadinfo_query)
3234 {
3235 char *bufp;
3236
3237 putpkt ("qfThreadInfo");
3238 getpkt (&rs->buf, &rs->buf_size, 0);
3239 bufp = rs->buf;
3240 if (bufp[0] != '\0') /* q packet recognized */
3241 {
3242 while (*bufp++ == 'm') /* reply contains one or more TID */
3243 {
3244 do
3245 {
3246 struct thread_item item;
3247
3248 item.ptid = read_ptid (bufp, &bufp);
3249 item.core = -1;
3250 item.name = NULL;
3251 item.extra = NULL;
3252 item.thread_handle = nullptr;
3253
3254 VEC_safe_push (thread_item_t, context->items, &item);
3255 }
3256 while (*bufp++ == ','); /* comma-separated list */
3257 putpkt ("qsThreadInfo");
3258 getpkt (&rs->buf, &rs->buf_size, 0);
3259 bufp = rs->buf;
3260 }
3261 return 1;
3262 }
3263 else
3264 {
3265 /* Packet not recognized. */
3266 rs->use_threadinfo_query = 0;
3267 }
3268 }
3269
3270 return 0;
3271 }
3272
3273 /* Implement the to_update_thread_list function for the remote
3274 targets. */
3275
3276 static void
3277 remote_update_thread_list (struct target_ops *ops)
3278 {
3279 struct threads_listing_context context;
3280 struct cleanup *old_chain;
3281 int got_list = 0;
3282
3283 context.items = NULL;
3284 old_chain = make_cleanup (clear_threads_listing_context, &context);
3285
3286 /* We have a few different mechanisms to fetch the thread list. Try
3287 them all, starting with the most preferred one first, falling
3288 back to older methods. */
3289 if (remote_get_threads_with_qxfer (ops, &context)
3290 || remote_get_threads_with_qthreadinfo (ops, &context)
3291 || remote_get_threads_with_ql (ops, &context))
3292 {
3293 int i;
3294 struct thread_item *item;
3295 struct thread_info *tp, *tmp;
3296
3297 got_list = 1;
3298
3299 if (VEC_empty (thread_item_t, context.items)
3300 && remote_thread_always_alive (ops, inferior_ptid))
3301 {
3302 /* Some targets don't really support threads, but still
3303 reply an (empty) thread list in response to the thread
3304 listing packets, instead of replying "packet not
3305 supported". Exit early so we don't delete the main
3306 thread. */
3307 do_cleanups (old_chain);
3308 return;
3309 }
3310
3311 /* CONTEXT now holds the current thread list on the remote
3312 target end. Delete GDB-side threads no longer found on the
3313 target. */
3314 ALL_THREADS_SAFE (tp, tmp)
3315 {
3316 for (i = 0;
3317 VEC_iterate (thread_item_t, context.items, i, item);
3318 ++i)
3319 {
3320 if (ptid_equal (item->ptid, tp->ptid))
3321 break;
3322 }
3323
3324 if (i == VEC_length (thread_item_t, context.items))
3325 {
3326 /* Not found. */
3327 delete_thread (tp->ptid);
3328 }
3329 }
3330
3331 /* Remove any unreported fork child threads from CONTEXT so
3332 that we don't interfere with follow fork, which is where
3333 creation of such threads is handled. */
3334 remove_new_fork_children (&context);
3335
3336 /* And now add threads we don't know about yet to our list. */
3337 for (i = 0;
3338 VEC_iterate (thread_item_t, context.items, i, item);
3339 ++i)
3340 {
3341 if (!ptid_equal (item->ptid, null_ptid))
3342 {
3343 struct private_thread_info *info;
3344 /* In non-stop mode, we assume new found threads are
3345 executing until proven otherwise with a stop reply.
3346 In all-stop, we can only get here if all threads are
3347 stopped. */
3348 int executing = target_is_non_stop_p () ? 1 : 0;
3349
3350 remote_notice_new_inferior (item->ptid, executing);
3351
3352 info = get_private_info_ptid (item->ptid);
3353 info->core = item->core;
3354 info->extra = item->extra;
3355 item->extra = NULL;
3356 info->name = item->name;
3357 item->name = NULL;
3358 info->thread_handle = item->thread_handle;
3359 item->thread_handle = nullptr;
3360 }
3361 }
3362 }
3363
3364 if (!got_list)
3365 {
3366 /* If no thread listing method is supported, then query whether
3367 each known thread is alive, one by one, with the T packet.
3368 If the target doesn't support threads at all, then this is a
3369 no-op. See remote_thread_alive. */
3370 prune_threads ();
3371 }
3372
3373 do_cleanups (old_chain);
3374 }
3375
3376 /*
3377 * Collect a descriptive string about the given thread.
3378 * The target may say anything it wants to about the thread
3379 * (typically info about its blocked / runnable state, name, etc.).
3380 * This string will appear in the info threads display.
3381 *
3382 * Optional: targets are not required to implement this function.
3383 */
3384
3385 static const char *
3386 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3387 {
3388 struct remote_state *rs = get_remote_state ();
3389 int result;
3390 int set;
3391 threadref id;
3392 struct gdb_ext_thread_info threadinfo;
3393 static char display_buf[100]; /* arbitrary... */
3394 int n = 0; /* position in display_buf */
3395
3396 if (rs->remote_desc == 0) /* paranoia */
3397 internal_error (__FILE__, __LINE__,
3398 _("remote_threads_extra_info"));
3399
3400 if (ptid_equal (tp->ptid, magic_null_ptid)
3401 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3402 /* This is the main thread which was added by GDB. The remote
3403 server doesn't know about it. */
3404 return NULL;
3405
3406 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3407 {
3408 struct thread_info *info = find_thread_ptid (tp->ptid);
3409
3410 if (info && info->priv)
3411 return info->priv->extra;
3412 else
3413 return NULL;
3414 }
3415
3416 if (rs->use_threadextra_query)
3417 {
3418 char *b = rs->buf;
3419 char *endb = rs->buf + get_remote_packet_size ();
3420
3421 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3422 b += strlen (b);
3423 write_ptid (b, endb, tp->ptid);
3424
3425 putpkt (rs->buf);
3426 getpkt (&rs->buf, &rs->buf_size, 0);
3427 if (rs->buf[0] != 0)
3428 {
3429 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3430 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3431 display_buf [result] = '\0';
3432 return display_buf;
3433 }
3434 }
3435
3436 /* If the above query fails, fall back to the old method. */
3437 rs->use_threadextra_query = 0;
3438 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3439 | TAG_MOREDISPLAY | TAG_DISPLAY;
3440 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3441 if (remote_get_threadinfo (&id, set, &threadinfo))
3442 if (threadinfo.active)
3443 {
3444 if (*threadinfo.shortname)
3445 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3446 " Name: %s,", threadinfo.shortname);
3447 if (*threadinfo.display)
3448 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3449 " State: %s,", threadinfo.display);
3450 if (*threadinfo.more_display)
3451 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3452 " Priority: %s", threadinfo.more_display);
3453
3454 if (n > 0)
3455 {
3456 /* For purely cosmetic reasons, clear up trailing commas. */
3457 if (',' == display_buf[n-1])
3458 display_buf[n-1] = ' ';
3459 return display_buf;
3460 }
3461 }
3462 return NULL;
3463 }
3464 \f
3465
3466 static int
3467 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3468 struct static_tracepoint_marker *marker)
3469 {
3470 struct remote_state *rs = get_remote_state ();
3471 char *p = rs->buf;
3472
3473 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3474 p += strlen (p);
3475 p += hexnumstr (p, addr);
3476 putpkt (rs->buf);
3477 getpkt (&rs->buf, &rs->buf_size, 0);
3478 p = rs->buf;
3479
3480 if (*p == 'E')
3481 error (_("Remote failure reply: %s"), p);
3482
3483 if (*p++ == 'm')
3484 {
3485 parse_static_tracepoint_marker_definition (p, &p, marker);
3486 return 1;
3487 }
3488
3489 return 0;
3490 }
3491
3492 static VEC(static_tracepoint_marker_p) *
3493 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3494 const char *strid)
3495 {
3496 struct remote_state *rs = get_remote_state ();
3497 VEC(static_tracepoint_marker_p) *markers = NULL;
3498 struct static_tracepoint_marker *marker = NULL;
3499 struct cleanup *old_chain;
3500 char *p;
3501
3502 /* Ask for a first packet of static tracepoint marker
3503 definition. */
3504 putpkt ("qTfSTM");
3505 getpkt (&rs->buf, &rs->buf_size, 0);
3506 p = rs->buf;
3507 if (*p == 'E')
3508 error (_("Remote failure reply: %s"), p);
3509
3510 old_chain = make_cleanup (free_current_marker, &marker);
3511
3512 while (*p++ == 'm')
3513 {
3514 if (marker == NULL)
3515 marker = XCNEW (struct static_tracepoint_marker);
3516
3517 do
3518 {
3519 parse_static_tracepoint_marker_definition (p, &p, marker);
3520
3521 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3522 {
3523 VEC_safe_push (static_tracepoint_marker_p,
3524 markers, marker);
3525 marker = NULL;
3526 }
3527 else
3528 {
3529 release_static_tracepoint_marker (marker);
3530 memset (marker, 0, sizeof (*marker));
3531 }
3532 }
3533 while (*p++ == ','); /* comma-separated list */
3534 /* Ask for another packet of static tracepoint definition. */
3535 putpkt ("qTsSTM");
3536 getpkt (&rs->buf, &rs->buf_size, 0);
3537 p = rs->buf;
3538 }
3539
3540 do_cleanups (old_chain);
3541 return markers;
3542 }
3543
3544 \f
3545 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3546
3547 static ptid_t
3548 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3549 {
3550 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3551 }
3552 \f
3553
3554 /* Restart the remote side; this is an extended protocol operation. */
3555
3556 static void
3557 extended_remote_restart (void)
3558 {
3559 struct remote_state *rs = get_remote_state ();
3560
3561 /* Send the restart command; for reasons I don't understand the
3562 remote side really expects a number after the "R". */
3563 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3564 putpkt (rs->buf);
3565
3566 remote_fileio_reset ();
3567 }
3568 \f
3569 /* Clean up connection to a remote debugger. */
3570
3571 static void
3572 remote_close (struct target_ops *self)
3573 {
3574 struct remote_state *rs = get_remote_state ();
3575
3576 if (rs->remote_desc == NULL)
3577 return; /* already closed */
3578
3579 /* Make sure we leave stdin registered in the event loop. */
3580 remote_terminal_ours (self);
3581
3582 serial_close (rs->remote_desc);
3583 rs->remote_desc = NULL;
3584
3585 /* We don't have a connection to the remote stub anymore. Get rid
3586 of all the inferiors and their threads we were controlling.
3587 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3588 will be unable to find the thread corresponding to (pid, 0, 0). */
3589 inferior_ptid = null_ptid;
3590 discard_all_inferiors ();
3591
3592 /* We are closing the remote target, so we should discard
3593 everything of this target. */
3594 discard_pending_stop_replies_in_queue (rs);
3595
3596 if (remote_async_inferior_event_token)
3597 delete_async_event_handler (&remote_async_inferior_event_token);
3598
3599 remote_notif_state_xfree (rs->notif_state);
3600
3601 trace_reset_local_state ();
3602 }
3603
3604 /* Query the remote side for the text, data and bss offsets. */
3605
3606 static void
3607 get_offsets (void)
3608 {
3609 struct remote_state *rs = get_remote_state ();
3610 char *buf;
3611 char *ptr;
3612 int lose, num_segments = 0, do_sections, do_segments;
3613 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3614 struct section_offsets *offs;
3615 struct symfile_segment_data *data;
3616
3617 if (symfile_objfile == NULL)
3618 return;
3619
3620 putpkt ("qOffsets");
3621 getpkt (&rs->buf, &rs->buf_size, 0);
3622 buf = rs->buf;
3623
3624 if (buf[0] == '\000')
3625 return; /* Return silently. Stub doesn't support
3626 this command. */
3627 if (buf[0] == 'E')
3628 {
3629 warning (_("Remote failure reply: %s"), buf);
3630 return;
3631 }
3632
3633 /* Pick up each field in turn. This used to be done with scanf, but
3634 scanf will make trouble if CORE_ADDR size doesn't match
3635 conversion directives correctly. The following code will work
3636 with any size of CORE_ADDR. */
3637 text_addr = data_addr = bss_addr = 0;
3638 ptr = buf;
3639 lose = 0;
3640
3641 if (startswith (ptr, "Text="))
3642 {
3643 ptr += 5;
3644 /* Don't use strtol, could lose on big values. */
3645 while (*ptr && *ptr != ';')
3646 text_addr = (text_addr << 4) + fromhex (*ptr++);
3647
3648 if (startswith (ptr, ";Data="))
3649 {
3650 ptr += 6;
3651 while (*ptr && *ptr != ';')
3652 data_addr = (data_addr << 4) + fromhex (*ptr++);
3653 }
3654 else
3655 lose = 1;
3656
3657 if (!lose && startswith (ptr, ";Bss="))
3658 {
3659 ptr += 5;
3660 while (*ptr && *ptr != ';')
3661 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3662
3663 if (bss_addr != data_addr)
3664 warning (_("Target reported unsupported offsets: %s"), buf);
3665 }
3666 else
3667 lose = 1;
3668 }
3669 else if (startswith (ptr, "TextSeg="))
3670 {
3671 ptr += 8;
3672 /* Don't use strtol, could lose on big values. */
3673 while (*ptr && *ptr != ';')
3674 text_addr = (text_addr << 4) + fromhex (*ptr++);
3675 num_segments = 1;
3676
3677 if (startswith (ptr, ";DataSeg="))
3678 {
3679 ptr += 9;
3680 while (*ptr && *ptr != ';')
3681 data_addr = (data_addr << 4) + fromhex (*ptr++);
3682 num_segments++;
3683 }
3684 }
3685 else
3686 lose = 1;
3687
3688 if (lose)
3689 error (_("Malformed response to offset query, %s"), buf);
3690 else if (*ptr != '\0')
3691 warning (_("Target reported unsupported offsets: %s"), buf);
3692
3693 offs = ((struct section_offsets *)
3694 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3695 memcpy (offs, symfile_objfile->section_offsets,
3696 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3697
3698 data = get_symfile_segment_data (symfile_objfile->obfd);
3699 do_segments = (data != NULL);
3700 do_sections = num_segments == 0;
3701
3702 if (num_segments > 0)
3703 {
3704 segments[0] = text_addr;
3705 segments[1] = data_addr;
3706 }
3707 /* If we have two segments, we can still try to relocate everything
3708 by assuming that the .text and .data offsets apply to the whole
3709 text and data segments. Convert the offsets given in the packet
3710 to base addresses for symfile_map_offsets_to_segments. */
3711 else if (data && data->num_segments == 2)
3712 {
3713 segments[0] = data->segment_bases[0] + text_addr;
3714 segments[1] = data->segment_bases[1] + data_addr;
3715 num_segments = 2;
3716 }
3717 /* If the object file has only one segment, assume that it is text
3718 rather than data; main programs with no writable data are rare,
3719 but programs with no code are useless. Of course the code might
3720 have ended up in the data segment... to detect that we would need
3721 the permissions here. */
3722 else if (data && data->num_segments == 1)
3723 {
3724 segments[0] = data->segment_bases[0] + text_addr;
3725 num_segments = 1;
3726 }
3727 /* There's no way to relocate by segment. */
3728 else
3729 do_segments = 0;
3730
3731 if (do_segments)
3732 {
3733 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3734 offs, num_segments, segments);
3735
3736 if (ret == 0 && !do_sections)
3737 error (_("Can not handle qOffsets TextSeg "
3738 "response with this symbol file"));
3739
3740 if (ret > 0)
3741 do_sections = 0;
3742 }
3743
3744 if (data)
3745 free_symfile_segment_data (data);
3746
3747 if (do_sections)
3748 {
3749 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3750
3751 /* This is a temporary kludge to force data and bss to use the
3752 same offsets because that's what nlmconv does now. The real
3753 solution requires changes to the stub and remote.c that I
3754 don't have time to do right now. */
3755
3756 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3757 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3758 }
3759
3760 objfile_relocate (symfile_objfile, offs);
3761 }
3762
3763 /* Send interrupt_sequence to remote target. */
3764 static void
3765 send_interrupt_sequence (void)
3766 {
3767 struct remote_state *rs = get_remote_state ();
3768
3769 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3770 remote_serial_write ("\x03", 1);
3771 else if (interrupt_sequence_mode == interrupt_sequence_break)
3772 serial_send_break (rs->remote_desc);
3773 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3774 {
3775 serial_send_break (rs->remote_desc);
3776 remote_serial_write ("g", 1);
3777 }
3778 else
3779 internal_error (__FILE__, __LINE__,
3780 _("Invalid value for interrupt_sequence_mode: %s."),
3781 interrupt_sequence_mode);
3782 }
3783
3784
3785 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3786 and extract the PTID. Returns NULL_PTID if not found. */
3787
3788 static ptid_t
3789 stop_reply_extract_thread (char *stop_reply)
3790 {
3791 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3792 {
3793 char *p;
3794
3795 /* Txx r:val ; r:val (...) */
3796 p = &stop_reply[3];
3797
3798 /* Look for "register" named "thread". */
3799 while (*p != '\0')
3800 {
3801 char *p1;
3802
3803 p1 = strchr (p, ':');
3804 if (p1 == NULL)
3805 return null_ptid;
3806
3807 if (strncmp (p, "thread", p1 - p) == 0)
3808 return read_ptid (++p1, &p);
3809
3810 p1 = strchr (p, ';');
3811 if (p1 == NULL)
3812 return null_ptid;
3813 p1++;
3814
3815 p = p1;
3816 }
3817 }
3818
3819 return null_ptid;
3820 }
3821
3822 /* Determine the remote side's current thread. If we have a stop
3823 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3824 "thread" register we can extract the current thread from. If not,
3825 ask the remote which is the current thread with qC. The former
3826 method avoids a roundtrip. */
3827
3828 static ptid_t
3829 get_current_thread (char *wait_status)
3830 {
3831 ptid_t ptid = null_ptid;
3832
3833 /* Note we don't use remote_parse_stop_reply as that makes use of
3834 the target architecture, which we haven't yet fully determined at
3835 this point. */
3836 if (wait_status != NULL)
3837 ptid = stop_reply_extract_thread (wait_status);
3838 if (ptid_equal (ptid, null_ptid))
3839 ptid = remote_current_thread (inferior_ptid);
3840
3841 return ptid;
3842 }
3843
3844 /* Query the remote target for which is the current thread/process,
3845 add it to our tables, and update INFERIOR_PTID. The caller is
3846 responsible for setting the state such that the remote end is ready
3847 to return the current thread.
3848
3849 This function is called after handling the '?' or 'vRun' packets,
3850 whose response is a stop reply from which we can also try
3851 extracting the thread. If the target doesn't support the explicit
3852 qC query, we infer the current thread from that stop reply, passed
3853 in in WAIT_STATUS, which may be NULL. */
3854
3855 static void
3856 add_current_inferior_and_thread (char *wait_status)
3857 {
3858 struct remote_state *rs = get_remote_state ();
3859 int fake_pid_p = 0;
3860
3861 inferior_ptid = null_ptid;
3862
3863 /* Now, if we have thread information, update inferior_ptid. */
3864 ptid_t curr_ptid = get_current_thread (wait_status);
3865
3866 if (curr_ptid != null_ptid)
3867 {
3868 if (!remote_multi_process_p (rs))
3869 fake_pid_p = 1;
3870 }
3871 else
3872 {
3873 /* Without this, some commands which require an active target
3874 (such as kill) won't work. This variable serves (at least)
3875 double duty as both the pid of the target process (if it has
3876 such), and as a flag indicating that a target is active. */
3877 curr_ptid = magic_null_ptid;
3878 fake_pid_p = 1;
3879 }
3880
3881 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
3882
3883 /* Add the main thread and switch to it. Don't try reading
3884 registers yet, since we haven't fetched the target description
3885 yet. */
3886 thread_info *tp = add_thread_silent (curr_ptid);
3887 switch_to_thread_no_regs (tp);
3888 }
3889
3890 /* Print info about a thread that was found already stopped on
3891 connection. */
3892
3893 static void
3894 print_one_stopped_thread (struct thread_info *thread)
3895 {
3896 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3897
3898 switch_to_thread (thread->ptid);
3899 stop_pc = get_frame_pc (get_current_frame ());
3900 set_current_sal_from_frame (get_current_frame ());
3901
3902 thread->suspend.waitstatus_pending_p = 0;
3903
3904 if (ws->kind == TARGET_WAITKIND_STOPPED)
3905 {
3906 enum gdb_signal sig = ws->value.sig;
3907
3908 if (signal_print_state (sig))
3909 observer_notify_signal_received (sig);
3910 }
3911 observer_notify_normal_stop (NULL, 1);
3912 }
3913
3914 /* Process all initial stop replies the remote side sent in response
3915 to the ? packet. These indicate threads that were already stopped
3916 on initial connection. We mark these threads as stopped and print
3917 their current frame before giving the user the prompt. */
3918
3919 static void
3920 process_initial_stop_replies (int from_tty)
3921 {
3922 int pending_stop_replies = stop_reply_queue_length ();
3923 struct inferior *inf;
3924 struct thread_info *thread;
3925 struct thread_info *selected = NULL;
3926 struct thread_info *lowest_stopped = NULL;
3927 struct thread_info *first = NULL;
3928
3929 /* Consume the initial pending events. */
3930 while (pending_stop_replies-- > 0)
3931 {
3932 ptid_t waiton_ptid = minus_one_ptid;
3933 ptid_t event_ptid;
3934 struct target_waitstatus ws;
3935 int ignore_event = 0;
3936 struct thread_info *thread;
3937
3938 memset (&ws, 0, sizeof (ws));
3939 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3940 if (remote_debug)
3941 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3942
3943 switch (ws.kind)
3944 {
3945 case TARGET_WAITKIND_IGNORE:
3946 case TARGET_WAITKIND_NO_RESUMED:
3947 case TARGET_WAITKIND_SIGNALLED:
3948 case TARGET_WAITKIND_EXITED:
3949 /* We shouldn't see these, but if we do, just ignore. */
3950 if (remote_debug)
3951 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3952 ignore_event = 1;
3953 break;
3954
3955 case TARGET_WAITKIND_EXECD:
3956 xfree (ws.value.execd_pathname);
3957 break;
3958 default:
3959 break;
3960 }
3961
3962 if (ignore_event)
3963 continue;
3964
3965 thread = find_thread_ptid (event_ptid);
3966
3967 if (ws.kind == TARGET_WAITKIND_STOPPED)
3968 {
3969 enum gdb_signal sig = ws.value.sig;
3970
3971 /* Stubs traditionally report SIGTRAP as initial signal,
3972 instead of signal 0. Suppress it. */
3973 if (sig == GDB_SIGNAL_TRAP)
3974 sig = GDB_SIGNAL_0;
3975 thread->suspend.stop_signal = sig;
3976 ws.value.sig = sig;
3977 }
3978
3979 thread->suspend.waitstatus = ws;
3980
3981 if (ws.kind != TARGET_WAITKIND_STOPPED
3982 || ws.value.sig != GDB_SIGNAL_0)
3983 thread->suspend.waitstatus_pending_p = 1;
3984
3985 set_executing (event_ptid, 0);
3986 set_running (event_ptid, 0);
3987 thread->priv->vcont_resumed = 0;
3988 }
3989
3990 /* "Notice" the new inferiors before anything related to
3991 registers/memory. */
3992 ALL_INFERIORS (inf)
3993 {
3994 if (inf->pid == 0)
3995 continue;
3996
3997 inf->needs_setup = 1;
3998
3999 if (non_stop)
4000 {
4001 thread = any_live_thread_of_process (inf->pid);
4002 notice_new_inferior (thread->ptid,
4003 thread->state == THREAD_RUNNING,
4004 from_tty);
4005 }
4006 }
4007
4008 /* If all-stop on top of non-stop, pause all threads. Note this
4009 records the threads' stop pc, so must be done after "noticing"
4010 the inferiors. */
4011 if (!non_stop)
4012 {
4013 stop_all_threads ();
4014
4015 /* If all threads of an inferior were already stopped, we
4016 haven't setup the inferior yet. */
4017 ALL_INFERIORS (inf)
4018 {
4019 if (inf->pid == 0)
4020 continue;
4021
4022 if (inf->needs_setup)
4023 {
4024 thread = any_live_thread_of_process (inf->pid);
4025 switch_to_thread_no_regs (thread);
4026 setup_inferior (0);
4027 }
4028 }
4029 }
4030
4031 /* Now go over all threads that are stopped, and print their current
4032 frame. If all-stop, then if there's a signalled thread, pick
4033 that as current. */
4034 ALL_NON_EXITED_THREADS (thread)
4035 {
4036 if (first == NULL)
4037 first = thread;
4038
4039 if (!non_stop)
4040 set_running (thread->ptid, 0);
4041 else if (thread->state != THREAD_STOPPED)
4042 continue;
4043
4044 if (selected == NULL
4045 && thread->suspend.waitstatus_pending_p)
4046 selected = thread;
4047
4048 if (lowest_stopped == NULL
4049 || thread->inf->num < lowest_stopped->inf->num
4050 || thread->per_inf_num < lowest_stopped->per_inf_num)
4051 lowest_stopped = thread;
4052
4053 if (non_stop)
4054 print_one_stopped_thread (thread);
4055 }
4056
4057 /* In all-stop, we only print the status of one thread, and leave
4058 others with their status pending. */
4059 if (!non_stop)
4060 {
4061 thread = selected;
4062 if (thread == NULL)
4063 thread = lowest_stopped;
4064 if (thread == NULL)
4065 thread = first;
4066
4067 print_one_stopped_thread (thread);
4068 }
4069
4070 /* For "info program". */
4071 thread = inferior_thread ();
4072 if (thread->state == THREAD_STOPPED)
4073 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4074 }
4075
4076 /* Start the remote connection and sync state. */
4077
4078 static void
4079 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4080 {
4081 struct remote_state *rs = get_remote_state ();
4082 struct packet_config *noack_config;
4083 char *wait_status = NULL;
4084
4085 /* Signal other parts that we're going through the initial setup,
4086 and so things may not be stable yet. E.g., we don't try to
4087 install tracepoints until we've relocated symbols. Also, a
4088 Ctrl-C before we're connected and synced up can't interrupt the
4089 target. Instead, it offers to drop the (potentially wedged)
4090 connection. */
4091 rs->starting_up = 1;
4092
4093 QUIT;
4094
4095 if (interrupt_on_connect)
4096 send_interrupt_sequence ();
4097
4098 /* Ack any packet which the remote side has already sent. */
4099 remote_serial_write ("+", 1);
4100
4101 /* The first packet we send to the target is the optional "supported
4102 packets" request. If the target can answer this, it will tell us
4103 which later probes to skip. */
4104 remote_query_supported ();
4105
4106 /* If the stub wants to get a QAllow, compose one and send it. */
4107 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4108 remote_set_permissions (target);
4109
4110 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4111 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4112 as a reply to known packet. For packet "vFile:setfs:" it is an
4113 invalid reply and GDB would return error in
4114 remote_hostio_set_filesystem, making remote files access impossible.
4115 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4116 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4117 {
4118 const char v_mustreplyempty[] = "vMustReplyEmpty";
4119
4120 putpkt (v_mustreplyempty);
4121 getpkt (&rs->buf, &rs->buf_size, 0);
4122 if (strcmp (rs->buf, "OK") == 0)
4123 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4124 else if (strcmp (rs->buf, "") != 0)
4125 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4126 rs->buf);
4127 }
4128
4129 /* Next, we possibly activate noack mode.
4130
4131 If the QStartNoAckMode packet configuration is set to AUTO,
4132 enable noack mode if the stub reported a wish for it with
4133 qSupported.
4134
4135 If set to TRUE, then enable noack mode even if the stub didn't
4136 report it in qSupported. If the stub doesn't reply OK, the
4137 session ends with an error.
4138
4139 If FALSE, then don't activate noack mode, regardless of what the
4140 stub claimed should be the default with qSupported. */
4141
4142 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4143 if (packet_config_support (noack_config) != PACKET_DISABLE)
4144 {
4145 putpkt ("QStartNoAckMode");
4146 getpkt (&rs->buf, &rs->buf_size, 0);
4147 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4148 rs->noack_mode = 1;
4149 }
4150
4151 if (extended_p)
4152 {
4153 /* Tell the remote that we are using the extended protocol. */
4154 putpkt ("!");
4155 getpkt (&rs->buf, &rs->buf_size, 0);
4156 }
4157
4158 /* Let the target know which signals it is allowed to pass down to
4159 the program. */
4160 update_signals_program_target ();
4161
4162 /* Next, if the target can specify a description, read it. We do
4163 this before anything involving memory or registers. */
4164 target_find_description ();
4165
4166 /* Next, now that we know something about the target, update the
4167 address spaces in the program spaces. */
4168 update_address_spaces ();
4169
4170 /* On OSs where the list of libraries is global to all
4171 processes, we fetch them early. */
4172 if (gdbarch_has_global_solist (target_gdbarch ()))
4173 solib_add (NULL, from_tty, auto_solib_add);
4174
4175 if (target_is_non_stop_p ())
4176 {
4177 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4178 error (_("Non-stop mode requested, but remote "
4179 "does not support non-stop"));
4180
4181 putpkt ("QNonStop:1");
4182 getpkt (&rs->buf, &rs->buf_size, 0);
4183
4184 if (strcmp (rs->buf, "OK") != 0)
4185 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4186
4187 /* Find about threads and processes the stub is already
4188 controlling. We default to adding them in the running state.
4189 The '?' query below will then tell us about which threads are
4190 stopped. */
4191 remote_update_thread_list (target);
4192 }
4193 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4194 {
4195 /* Don't assume that the stub can operate in all-stop mode.
4196 Request it explicitly. */
4197 putpkt ("QNonStop:0");
4198 getpkt (&rs->buf, &rs->buf_size, 0);
4199
4200 if (strcmp (rs->buf, "OK") != 0)
4201 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4202 }
4203
4204 /* Upload TSVs regardless of whether the target is running or not. The
4205 remote stub, such as GDBserver, may have some predefined or builtin
4206 TSVs, even if the target is not running. */
4207 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4208 {
4209 struct uploaded_tsv *uploaded_tsvs = NULL;
4210
4211 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4212 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4213 }
4214
4215 /* Check whether the target is running now. */
4216 putpkt ("?");
4217 getpkt (&rs->buf, &rs->buf_size, 0);
4218
4219 if (!target_is_non_stop_p ())
4220 {
4221 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4222 {
4223 if (!extended_p)
4224 error (_("The target is not running (try extended-remote?)"));
4225
4226 /* We're connected, but not running. Drop out before we
4227 call start_remote. */
4228 rs->starting_up = 0;
4229 return;
4230 }
4231 else
4232 {
4233 /* Save the reply for later. */
4234 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4235 strcpy (wait_status, rs->buf);
4236 }
4237
4238 /* Fetch thread list. */
4239 target_update_thread_list ();
4240
4241 /* Let the stub know that we want it to return the thread. */
4242 set_continue_thread (minus_one_ptid);
4243
4244 if (thread_count () == 0)
4245 {
4246 /* Target has no concept of threads at all. GDB treats
4247 non-threaded target as single-threaded; add a main
4248 thread. */
4249 add_current_inferior_and_thread (wait_status);
4250 }
4251 else
4252 {
4253 /* We have thread information; select the thread the target
4254 says should be current. If we're reconnecting to a
4255 multi-threaded program, this will ideally be the thread
4256 that last reported an event before GDB disconnected. */
4257 inferior_ptid = get_current_thread (wait_status);
4258 if (ptid_equal (inferior_ptid, null_ptid))
4259 {
4260 /* Odd... The target was able to list threads, but not
4261 tell us which thread was current (no "thread"
4262 register in T stop reply?). Just pick the first
4263 thread in the thread list then. */
4264
4265 if (remote_debug)
4266 fprintf_unfiltered (gdb_stdlog,
4267 "warning: couldn't determine remote "
4268 "current thread; picking first in list.\n");
4269
4270 inferior_ptid = thread_list->ptid;
4271 }
4272 }
4273
4274 /* init_wait_for_inferior should be called before get_offsets in order
4275 to manage `inserted' flag in bp loc in a correct state.
4276 breakpoint_init_inferior, called from init_wait_for_inferior, set
4277 `inserted' flag to 0, while before breakpoint_re_set, called from
4278 start_remote, set `inserted' flag to 1. In the initialization of
4279 inferior, breakpoint_init_inferior should be called first, and then
4280 breakpoint_re_set can be called. If this order is broken, state of
4281 `inserted' flag is wrong, and cause some problems on breakpoint
4282 manipulation. */
4283 init_wait_for_inferior ();
4284
4285 get_offsets (); /* Get text, data & bss offsets. */
4286
4287 /* If we could not find a description using qXfer, and we know
4288 how to do it some other way, try again. This is not
4289 supported for non-stop; it could be, but it is tricky if
4290 there are no stopped threads when we connect. */
4291 if (remote_read_description_p (target)
4292 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4293 {
4294 target_clear_description ();
4295 target_find_description ();
4296 }
4297
4298 /* Use the previously fetched status. */
4299 gdb_assert (wait_status != NULL);
4300 strcpy (rs->buf, wait_status);
4301 rs->cached_wait_status = 1;
4302
4303 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4304 }
4305 else
4306 {
4307 /* Clear WFI global state. Do this before finding about new
4308 threads and inferiors, and setting the current inferior.
4309 Otherwise we would clear the proceed status of the current
4310 inferior when we want its stop_soon state to be preserved
4311 (see notice_new_inferior). */
4312 init_wait_for_inferior ();
4313
4314 /* In non-stop, we will either get an "OK", meaning that there
4315 are no stopped threads at this time; or, a regular stop
4316 reply. In the latter case, there may be more than one thread
4317 stopped --- we pull them all out using the vStopped
4318 mechanism. */
4319 if (strcmp (rs->buf, "OK") != 0)
4320 {
4321 struct notif_client *notif = &notif_client_stop;
4322
4323 /* remote_notif_get_pending_replies acks this one, and gets
4324 the rest out. */
4325 rs->notif_state->pending_event[notif_client_stop.id]
4326 = remote_notif_parse (notif, rs->buf);
4327 remote_notif_get_pending_events (notif);
4328 }
4329
4330 if (thread_count () == 0)
4331 {
4332 if (!extended_p)
4333 error (_("The target is not running (try extended-remote?)"));
4334
4335 /* We're connected, but not running. Drop out before we
4336 call start_remote. */
4337 rs->starting_up = 0;
4338 return;
4339 }
4340
4341 /* In non-stop mode, any cached wait status will be stored in
4342 the stop reply queue. */
4343 gdb_assert (wait_status == NULL);
4344
4345 /* Report all signals during attach/startup. */
4346 remote_pass_signals (target, 0, NULL);
4347
4348 /* If there are already stopped threads, mark them stopped and
4349 report their stops before giving the prompt to the user. */
4350 process_initial_stop_replies (from_tty);
4351
4352 if (target_can_async_p ())
4353 target_async (1);
4354 }
4355
4356 /* If we connected to a live target, do some additional setup. */
4357 if (target_has_execution)
4358 {
4359 if (symfile_objfile) /* No use without a symbol-file. */
4360 remote_check_symbols ();
4361 }
4362
4363 /* Possibly the target has been engaged in a trace run started
4364 previously; find out where things are at. */
4365 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4366 {
4367 struct uploaded_tp *uploaded_tps = NULL;
4368
4369 if (current_trace_status ()->running)
4370 printf_filtered (_("Trace is already running on the target.\n"));
4371
4372 remote_upload_tracepoints (target, &uploaded_tps);
4373
4374 merge_uploaded_tracepoints (&uploaded_tps);
4375 }
4376
4377 /* Possibly the target has been engaged in a btrace record started
4378 previously; find out where things are at. */
4379 remote_btrace_maybe_reopen ();
4380
4381 /* The thread and inferior lists are now synchronized with the
4382 target, our symbols have been relocated, and we're merged the
4383 target's tracepoints with ours. We're done with basic start
4384 up. */
4385 rs->starting_up = 0;
4386
4387 /* Maybe breakpoints are global and need to be inserted now. */
4388 if (breakpoints_should_be_inserted_now ())
4389 insert_breakpoints ();
4390 }
4391
4392 /* Open a connection to a remote debugger.
4393 NAME is the filename used for communication. */
4394
4395 static void
4396 remote_open (const char *name, int from_tty)
4397 {
4398 remote_open_1 (name, from_tty, &remote_ops, 0);
4399 }
4400
4401 /* Open a connection to a remote debugger using the extended
4402 remote gdb protocol. NAME is the filename used for communication. */
4403
4404 static void
4405 extended_remote_open (const char *name, int from_tty)
4406 {
4407 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4408 }
4409
4410 /* Reset all packets back to "unknown support". Called when opening a
4411 new connection to a remote target. */
4412
4413 static void
4414 reset_all_packet_configs_support (void)
4415 {
4416 int i;
4417
4418 for (i = 0; i < PACKET_MAX; i++)
4419 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4420 }
4421
4422 /* Initialize all packet configs. */
4423
4424 static void
4425 init_all_packet_configs (void)
4426 {
4427 int i;
4428
4429 for (i = 0; i < PACKET_MAX; i++)
4430 {
4431 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4432 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4433 }
4434 }
4435
4436 /* Symbol look-up. */
4437
4438 static void
4439 remote_check_symbols (void)
4440 {
4441 struct remote_state *rs = get_remote_state ();
4442 char *msg, *reply, *tmp;
4443 int end;
4444 long reply_size;
4445 struct cleanup *old_chain;
4446
4447 /* The remote side has no concept of inferiors that aren't running
4448 yet, it only knows about running processes. If we're connected
4449 but our current inferior is not running, we should not invite the
4450 remote target to request symbol lookups related to its
4451 (unrelated) current process. */
4452 if (!target_has_execution)
4453 return;
4454
4455 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4456 return;
4457
4458 /* Make sure the remote is pointing at the right process. Note
4459 there's no way to select "no process". */
4460 set_general_process ();
4461
4462 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4463 because we need both at the same time. */
4464 msg = (char *) xmalloc (get_remote_packet_size ());
4465 old_chain = make_cleanup (xfree, msg);
4466 reply = (char *) xmalloc (get_remote_packet_size ());
4467 make_cleanup (free_current_contents, &reply);
4468 reply_size = get_remote_packet_size ();
4469
4470 /* Invite target to request symbol lookups. */
4471
4472 putpkt ("qSymbol::");
4473 getpkt (&reply, &reply_size, 0);
4474 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4475
4476 while (startswith (reply, "qSymbol:"))
4477 {
4478 struct bound_minimal_symbol sym;
4479
4480 tmp = &reply[8];
4481 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4482 msg[end] = '\0';
4483 sym = lookup_minimal_symbol (msg, NULL, NULL);
4484 if (sym.minsym == NULL)
4485 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4486 else
4487 {
4488 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4489 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4490
4491 /* If this is a function address, return the start of code
4492 instead of any data function descriptor. */
4493 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4494 sym_addr,
4495 &current_target);
4496
4497 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4498 phex_nz (sym_addr, addr_size), &reply[8]);
4499 }
4500
4501 putpkt (msg);
4502 getpkt (&reply, &reply_size, 0);
4503 }
4504
4505 do_cleanups (old_chain);
4506 }
4507
4508 static struct serial *
4509 remote_serial_open (const char *name)
4510 {
4511 static int udp_warning = 0;
4512
4513 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4514 of in ser-tcp.c, because it is the remote protocol assuming that the
4515 serial connection is reliable and not the serial connection promising
4516 to be. */
4517 if (!udp_warning && startswith (name, "udp:"))
4518 {
4519 warning (_("The remote protocol may be unreliable over UDP.\n"
4520 "Some events may be lost, rendering further debugging "
4521 "impossible."));
4522 udp_warning = 1;
4523 }
4524
4525 return serial_open (name);
4526 }
4527
4528 /* Inform the target of our permission settings. The permission flags
4529 work without this, but if the target knows the settings, it can do
4530 a couple things. First, it can add its own check, to catch cases
4531 that somehow manage to get by the permissions checks in target
4532 methods. Second, if the target is wired to disallow particular
4533 settings (for instance, a system in the field that is not set up to
4534 be able to stop at a breakpoint), it can object to any unavailable
4535 permissions. */
4536
4537 void
4538 remote_set_permissions (struct target_ops *self)
4539 {
4540 struct remote_state *rs = get_remote_state ();
4541
4542 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4543 "WriteReg:%x;WriteMem:%x;"
4544 "InsertBreak:%x;InsertTrace:%x;"
4545 "InsertFastTrace:%x;Stop:%x",
4546 may_write_registers, may_write_memory,
4547 may_insert_breakpoints, may_insert_tracepoints,
4548 may_insert_fast_tracepoints, may_stop);
4549 putpkt (rs->buf);
4550 getpkt (&rs->buf, &rs->buf_size, 0);
4551
4552 /* If the target didn't like the packet, warn the user. Do not try
4553 to undo the user's settings, that would just be maddening. */
4554 if (strcmp (rs->buf, "OK") != 0)
4555 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4556 }
4557
4558 /* This type describes each known response to the qSupported
4559 packet. */
4560 struct protocol_feature
4561 {
4562 /* The name of this protocol feature. */
4563 const char *name;
4564
4565 /* The default for this protocol feature. */
4566 enum packet_support default_support;
4567
4568 /* The function to call when this feature is reported, or after
4569 qSupported processing if the feature is not supported.
4570 The first argument points to this structure. The second
4571 argument indicates whether the packet requested support be
4572 enabled, disabled, or probed (or the default, if this function
4573 is being called at the end of processing and this feature was
4574 not reported). The third argument may be NULL; if not NULL, it
4575 is a NUL-terminated string taken from the packet following
4576 this feature's name and an equals sign. */
4577 void (*func) (const struct protocol_feature *, enum packet_support,
4578 const char *);
4579
4580 /* The corresponding packet for this feature. Only used if
4581 FUNC is remote_supported_packet. */
4582 int packet;
4583 };
4584
4585 static void
4586 remote_supported_packet (const struct protocol_feature *feature,
4587 enum packet_support support,
4588 const char *argument)
4589 {
4590 if (argument)
4591 {
4592 warning (_("Remote qSupported response supplied an unexpected value for"
4593 " \"%s\"."), feature->name);
4594 return;
4595 }
4596
4597 remote_protocol_packets[feature->packet].support = support;
4598 }
4599
4600 static void
4601 remote_packet_size (const struct protocol_feature *feature,
4602 enum packet_support support, const char *value)
4603 {
4604 struct remote_state *rs = get_remote_state ();
4605
4606 int packet_size;
4607 char *value_end;
4608
4609 if (support != PACKET_ENABLE)
4610 return;
4611
4612 if (value == NULL || *value == '\0')
4613 {
4614 warning (_("Remote target reported \"%s\" without a size."),
4615 feature->name);
4616 return;
4617 }
4618
4619 errno = 0;
4620 packet_size = strtol (value, &value_end, 16);
4621 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4622 {
4623 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4624 feature->name, value);
4625 return;
4626 }
4627
4628 /* Record the new maximum packet size. */
4629 rs->explicit_packet_size = packet_size;
4630 }
4631
4632 static const struct protocol_feature remote_protocol_features[] = {
4633 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4634 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4635 PACKET_qXfer_auxv },
4636 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4637 PACKET_qXfer_exec_file },
4638 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4639 PACKET_qXfer_features },
4640 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4641 PACKET_qXfer_libraries },
4642 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4643 PACKET_qXfer_libraries_svr4 },
4644 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4645 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4646 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4647 PACKET_qXfer_memory_map },
4648 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4649 PACKET_qXfer_spu_read },
4650 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4651 PACKET_qXfer_spu_write },
4652 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4653 PACKET_qXfer_osdata },
4654 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4655 PACKET_qXfer_threads },
4656 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4657 PACKET_qXfer_traceframe_info },
4658 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4659 PACKET_QPassSignals },
4660 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4661 PACKET_QCatchSyscalls },
4662 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4663 PACKET_QProgramSignals },
4664 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4665 PACKET_QStartupWithShell },
4666 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4667 PACKET_QEnvironmentHexEncoded },
4668 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4669 PACKET_QEnvironmentReset },
4670 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4671 PACKET_QEnvironmentUnset },
4672 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4673 PACKET_QStartNoAckMode },
4674 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4675 PACKET_multiprocess_feature },
4676 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4677 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4678 PACKET_qXfer_siginfo_read },
4679 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4680 PACKET_qXfer_siginfo_write },
4681 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4682 PACKET_ConditionalTracepoints },
4683 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4684 PACKET_ConditionalBreakpoints },
4685 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4686 PACKET_BreakpointCommands },
4687 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4688 PACKET_FastTracepoints },
4689 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4690 PACKET_StaticTracepoints },
4691 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4692 PACKET_InstallInTrace},
4693 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4694 PACKET_DisconnectedTracing_feature },
4695 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4696 PACKET_bc },
4697 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4698 PACKET_bs },
4699 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4700 PACKET_TracepointSource },
4701 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4702 PACKET_QAllow },
4703 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4704 PACKET_EnableDisableTracepoints_feature },
4705 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4706 PACKET_qXfer_fdpic },
4707 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4708 PACKET_qXfer_uib },
4709 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4710 PACKET_QDisableRandomization },
4711 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4712 { "QTBuffer:size", PACKET_DISABLE,
4713 remote_supported_packet, PACKET_QTBuffer_size},
4714 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4715 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4716 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4717 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4718 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4719 PACKET_qXfer_btrace },
4720 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4721 PACKET_qXfer_btrace_conf },
4722 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4723 PACKET_Qbtrace_conf_bts_size },
4724 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4725 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4726 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4727 PACKET_fork_event_feature },
4728 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4729 PACKET_vfork_event_feature },
4730 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4731 PACKET_exec_event_feature },
4732 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4733 PACKET_Qbtrace_conf_pt_size },
4734 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4735 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4736 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4737 };
4738
4739 static char *remote_support_xml;
4740
4741 /* Register string appended to "xmlRegisters=" in qSupported query. */
4742
4743 void
4744 register_remote_support_xml (const char *xml)
4745 {
4746 #if defined(HAVE_LIBEXPAT)
4747 if (remote_support_xml == NULL)
4748 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4749 else
4750 {
4751 char *copy = xstrdup (remote_support_xml + 13);
4752 char *p = strtok (copy, ",");
4753
4754 do
4755 {
4756 if (strcmp (p, xml) == 0)
4757 {
4758 /* already there */
4759 xfree (copy);
4760 return;
4761 }
4762 }
4763 while ((p = strtok (NULL, ",")) != NULL);
4764 xfree (copy);
4765
4766 remote_support_xml = reconcat (remote_support_xml,
4767 remote_support_xml, ",", xml,
4768 (char *) NULL);
4769 }
4770 #endif
4771 }
4772
4773 static char *
4774 remote_query_supported_append (char *msg, const char *append)
4775 {
4776 if (msg)
4777 return reconcat (msg, msg, ";", append, (char *) NULL);
4778 else
4779 return xstrdup (append);
4780 }
4781
4782 static void
4783 remote_query_supported (void)
4784 {
4785 struct remote_state *rs = get_remote_state ();
4786 char *next;
4787 int i;
4788 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4789
4790 /* The packet support flags are handled differently for this packet
4791 than for most others. We treat an error, a disabled packet, and
4792 an empty response identically: any features which must be reported
4793 to be used will be automatically disabled. An empty buffer
4794 accomplishes this, since that is also the representation for a list
4795 containing no features. */
4796
4797 rs->buf[0] = 0;
4798 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4799 {
4800 char *q = NULL;
4801 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4802
4803 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4804 q = remote_query_supported_append (q, "multiprocess+");
4805
4806 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4807 q = remote_query_supported_append (q, "swbreak+");
4808 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4809 q = remote_query_supported_append (q, "hwbreak+");
4810
4811 q = remote_query_supported_append (q, "qRelocInsn+");
4812
4813 if (packet_set_cmd_state (PACKET_fork_event_feature)
4814 != AUTO_BOOLEAN_FALSE)
4815 q = remote_query_supported_append (q, "fork-events+");
4816 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4817 != AUTO_BOOLEAN_FALSE)
4818 q = remote_query_supported_append (q, "vfork-events+");
4819 if (packet_set_cmd_state (PACKET_exec_event_feature)
4820 != AUTO_BOOLEAN_FALSE)
4821 q = remote_query_supported_append (q, "exec-events+");
4822
4823 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4824 q = remote_query_supported_append (q, "vContSupported+");
4825
4826 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4827 q = remote_query_supported_append (q, "QThreadEvents+");
4828
4829 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4830 q = remote_query_supported_append (q, "no-resumed+");
4831
4832 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4833 the qSupported:xmlRegisters=i386 handling. */
4834 if (remote_support_xml != NULL)
4835 q = remote_query_supported_append (q, remote_support_xml);
4836
4837 q = reconcat (q, "qSupported:", q, (char *) NULL);
4838 putpkt (q);
4839
4840 do_cleanups (old_chain);
4841
4842 getpkt (&rs->buf, &rs->buf_size, 0);
4843
4844 /* If an error occured, warn, but do not return - just reset the
4845 buffer to empty and go on to disable features. */
4846 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4847 == PACKET_ERROR)
4848 {
4849 warning (_("Remote failure reply: %s"), rs->buf);
4850 rs->buf[0] = 0;
4851 }
4852 }
4853
4854 memset (seen, 0, sizeof (seen));
4855
4856 next = rs->buf;
4857 while (*next)
4858 {
4859 enum packet_support is_supported;
4860 char *p, *end, *name_end, *value;
4861
4862 /* First separate out this item from the rest of the packet. If
4863 there's another item after this, we overwrite the separator
4864 (terminated strings are much easier to work with). */
4865 p = next;
4866 end = strchr (p, ';');
4867 if (end == NULL)
4868 {
4869 end = p + strlen (p);
4870 next = end;
4871 }
4872 else
4873 {
4874 *end = '\0';
4875 next = end + 1;
4876
4877 if (end == p)
4878 {
4879 warning (_("empty item in \"qSupported\" response"));
4880 continue;
4881 }
4882 }
4883
4884 name_end = strchr (p, '=');
4885 if (name_end)
4886 {
4887 /* This is a name=value entry. */
4888 is_supported = PACKET_ENABLE;
4889 value = name_end + 1;
4890 *name_end = '\0';
4891 }
4892 else
4893 {
4894 value = NULL;
4895 switch (end[-1])
4896 {
4897 case '+':
4898 is_supported = PACKET_ENABLE;
4899 break;
4900
4901 case '-':
4902 is_supported = PACKET_DISABLE;
4903 break;
4904
4905 case '?':
4906 is_supported = PACKET_SUPPORT_UNKNOWN;
4907 break;
4908
4909 default:
4910 warning (_("unrecognized item \"%s\" "
4911 "in \"qSupported\" response"), p);
4912 continue;
4913 }
4914 end[-1] = '\0';
4915 }
4916
4917 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4918 if (strcmp (remote_protocol_features[i].name, p) == 0)
4919 {
4920 const struct protocol_feature *feature;
4921
4922 seen[i] = 1;
4923 feature = &remote_protocol_features[i];
4924 feature->func (feature, is_supported, value);
4925 break;
4926 }
4927 }
4928
4929 /* If we increased the packet size, make sure to increase the global
4930 buffer size also. We delay this until after parsing the entire
4931 qSupported packet, because this is the same buffer we were
4932 parsing. */
4933 if (rs->buf_size < rs->explicit_packet_size)
4934 {
4935 rs->buf_size = rs->explicit_packet_size;
4936 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4937 }
4938
4939 /* Handle the defaults for unmentioned features. */
4940 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4941 if (!seen[i])
4942 {
4943 const struct protocol_feature *feature;
4944
4945 feature = &remote_protocol_features[i];
4946 feature->func (feature, feature->default_support, NULL);
4947 }
4948 }
4949
4950 /* Serial QUIT handler for the remote serial descriptor.
4951
4952 Defers handling a Ctrl-C until we're done with the current
4953 command/response packet sequence, unless:
4954
4955 - We're setting up the connection. Don't send a remote interrupt
4956 request, as we're not fully synced yet. Quit immediately
4957 instead.
4958
4959 - The target has been resumed in the foreground
4960 (target_terminal::is_ours is false) with a synchronous resume
4961 packet, and we're blocked waiting for the stop reply, thus a
4962 Ctrl-C should be immediately sent to the target.
4963
4964 - We get a second Ctrl-C while still within the same serial read or
4965 write. In that case the serial is seemingly wedged --- offer to
4966 quit/disconnect.
4967
4968 - We see a second Ctrl-C without target response, after having
4969 previously interrupted the target. In that case the target/stub
4970 is probably wedged --- offer to quit/disconnect.
4971 */
4972
4973 static void
4974 remote_serial_quit_handler (void)
4975 {
4976 struct remote_state *rs = get_remote_state ();
4977
4978 if (check_quit_flag ())
4979 {
4980 /* If we're starting up, we're not fully synced yet. Quit
4981 immediately. */
4982 if (rs->starting_up)
4983 quit ();
4984 else if (rs->got_ctrlc_during_io)
4985 {
4986 if (query (_("The target is not responding to GDB commands.\n"
4987 "Stop debugging it? ")))
4988 remote_unpush_and_throw ();
4989 }
4990 /* If ^C has already been sent once, offer to disconnect. */
4991 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
4992 interrupt_query ();
4993 /* All-stop protocol, and blocked waiting for stop reply. Send
4994 an interrupt request. */
4995 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
4996 target_interrupt (inferior_ptid);
4997 else
4998 rs->got_ctrlc_during_io = 1;
4999 }
5000 }
5001
5002 /* Remove any of the remote.c targets from target stack. Upper targets depend
5003 on it so remove them first. */
5004
5005 static void
5006 remote_unpush_target (void)
5007 {
5008 pop_all_targets_at_and_above (process_stratum);
5009 }
5010
5011 static void
5012 remote_unpush_and_throw (void)
5013 {
5014 remote_unpush_target ();
5015 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5016 }
5017
5018 static void
5019 remote_open_1 (const char *name, int from_tty,
5020 struct target_ops *target, int extended_p)
5021 {
5022 struct remote_state *rs = get_remote_state ();
5023
5024 if (name == 0)
5025 error (_("To open a remote debug connection, you need to specify what\n"
5026 "serial device is attached to the remote system\n"
5027 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5028
5029 /* See FIXME above. */
5030 if (!target_async_permitted)
5031 wait_forever_enabled_p = 1;
5032
5033 /* If we're connected to a running target, target_preopen will kill it.
5034 Ask this question first, before target_preopen has a chance to kill
5035 anything. */
5036 if (rs->remote_desc != NULL && !have_inferiors ())
5037 {
5038 if (from_tty
5039 && !query (_("Already connected to a remote target. Disconnect? ")))
5040 error (_("Still connected."));
5041 }
5042
5043 /* Here the possibly existing remote target gets unpushed. */
5044 target_preopen (from_tty);
5045
5046 /* Make sure we send the passed signals list the next time we resume. */
5047 xfree (rs->last_pass_packet);
5048 rs->last_pass_packet = NULL;
5049
5050 /* Make sure we send the program signals list the next time we
5051 resume. */
5052 xfree (rs->last_program_signals_packet);
5053 rs->last_program_signals_packet = NULL;
5054
5055 remote_fileio_reset ();
5056 reopen_exec_file ();
5057 reread_symbols ();
5058
5059 rs->remote_desc = remote_serial_open (name);
5060 if (!rs->remote_desc)
5061 perror_with_name (name);
5062
5063 if (baud_rate != -1)
5064 {
5065 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5066 {
5067 /* The requested speed could not be set. Error out to
5068 top level after closing remote_desc. Take care to
5069 set remote_desc to NULL to avoid closing remote_desc
5070 more than once. */
5071 serial_close (rs->remote_desc);
5072 rs->remote_desc = NULL;
5073 perror_with_name (name);
5074 }
5075 }
5076
5077 serial_setparity (rs->remote_desc, serial_parity);
5078 serial_raw (rs->remote_desc);
5079
5080 /* If there is something sitting in the buffer we might take it as a
5081 response to a command, which would be bad. */
5082 serial_flush_input (rs->remote_desc);
5083
5084 if (from_tty)
5085 {
5086 puts_filtered ("Remote debugging using ");
5087 puts_filtered (name);
5088 puts_filtered ("\n");
5089 }
5090 push_target (target); /* Switch to using remote target now. */
5091
5092 /* Register extra event sources in the event loop. */
5093 remote_async_inferior_event_token
5094 = create_async_event_handler (remote_async_inferior_event_handler,
5095 NULL);
5096 rs->notif_state = remote_notif_state_allocate ();
5097
5098 /* Reset the target state; these things will be queried either by
5099 remote_query_supported or as they are needed. */
5100 reset_all_packet_configs_support ();
5101 rs->cached_wait_status = 0;
5102 rs->explicit_packet_size = 0;
5103 rs->noack_mode = 0;
5104 rs->extended = extended_p;
5105 rs->waiting_for_stop_reply = 0;
5106 rs->ctrlc_pending_p = 0;
5107 rs->got_ctrlc_during_io = 0;
5108
5109 rs->general_thread = not_sent_ptid;
5110 rs->continue_thread = not_sent_ptid;
5111 rs->remote_traceframe_number = -1;
5112
5113 rs->last_resume_exec_dir = EXEC_FORWARD;
5114
5115 /* Probe for ability to use "ThreadInfo" query, as required. */
5116 rs->use_threadinfo_query = 1;
5117 rs->use_threadextra_query = 1;
5118
5119 readahead_cache_invalidate ();
5120
5121 /* Start out by owning the terminal. */
5122 remote_async_terminal_ours_p = 1;
5123
5124 if (target_async_permitted)
5125 {
5126 /* FIXME: cagney/1999-09-23: During the initial connection it is
5127 assumed that the target is already ready and able to respond to
5128 requests. Unfortunately remote_start_remote() eventually calls
5129 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5130 around this. Eventually a mechanism that allows
5131 wait_for_inferior() to expect/get timeouts will be
5132 implemented. */
5133 wait_forever_enabled_p = 0;
5134 }
5135
5136 /* First delete any symbols previously loaded from shared libraries. */
5137 no_shared_libraries (NULL, 0);
5138
5139 /* Start afresh. */
5140 init_thread_list ();
5141
5142 /* Start the remote connection. If error() or QUIT, discard this
5143 target (we'd otherwise be in an inconsistent state) and then
5144 propogate the error on up the exception chain. This ensures that
5145 the caller doesn't stumble along blindly assuming that the
5146 function succeeded. The CLI doesn't have this problem but other
5147 UI's, such as MI do.
5148
5149 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5150 this function should return an error indication letting the
5151 caller restore the previous state. Unfortunately the command
5152 ``target remote'' is directly wired to this function making that
5153 impossible. On a positive note, the CLI side of this problem has
5154 been fixed - the function set_cmd_context() makes it possible for
5155 all the ``target ....'' commands to share a common callback
5156 function. See cli-dump.c. */
5157 {
5158
5159 TRY
5160 {
5161 remote_start_remote (from_tty, target, extended_p);
5162 }
5163 CATCH (ex, RETURN_MASK_ALL)
5164 {
5165 /* Pop the partially set up target - unless something else did
5166 already before throwing the exception. */
5167 if (rs->remote_desc != NULL)
5168 remote_unpush_target ();
5169 if (target_async_permitted)
5170 wait_forever_enabled_p = 1;
5171 throw_exception (ex);
5172 }
5173 END_CATCH
5174 }
5175
5176 remote_btrace_reset ();
5177
5178 if (target_async_permitted)
5179 wait_forever_enabled_p = 1;
5180 }
5181
5182 /* Detach the specified process. */
5183
5184 static void
5185 remote_detach_pid (int pid)
5186 {
5187 struct remote_state *rs = get_remote_state ();
5188
5189 if (remote_multi_process_p (rs))
5190 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5191 else
5192 strcpy (rs->buf, "D");
5193
5194 putpkt (rs->buf);
5195 getpkt (&rs->buf, &rs->buf_size, 0);
5196
5197 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5198 ;
5199 else if (rs->buf[0] == '\0')
5200 error (_("Remote doesn't know how to detach"));
5201 else
5202 error (_("Can't detach process."));
5203 }
5204
5205 /* This detaches a program to which we previously attached, using
5206 inferior_ptid to identify the process. After this is done, GDB
5207 can be used to debug some other program. We better not have left
5208 any breakpoints in the target program or it'll die when it hits
5209 one. */
5210
5211 static void
5212 remote_detach_1 (const char *args, int from_tty)
5213 {
5214 int pid = ptid_get_pid (inferior_ptid);
5215 struct remote_state *rs = get_remote_state ();
5216 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5217 int is_fork_parent;
5218
5219 if (args)
5220 error (_("Argument given to \"detach\" when remotely debugging."));
5221
5222 if (!target_has_execution)
5223 error (_("No process to detach from."));
5224
5225 target_announce_detach (from_tty);
5226
5227 /* Tell the remote target to detach. */
5228 remote_detach_pid (pid);
5229
5230 /* Exit only if this is the only active inferior. */
5231 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5232 puts_filtered (_("Ending remote debugging.\n"));
5233
5234 /* Check to see if we are detaching a fork parent. Note that if we
5235 are detaching a fork child, tp == NULL. */
5236 is_fork_parent = (tp != NULL
5237 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5238
5239 /* If doing detach-on-fork, we don't mourn, because that will delete
5240 breakpoints that should be available for the followed inferior. */
5241 if (!is_fork_parent)
5242 target_mourn_inferior (inferior_ptid);
5243 else
5244 {
5245 inferior_ptid = null_ptid;
5246 detach_inferior (pid);
5247 }
5248 }
5249
5250 static void
5251 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5252 {
5253 remote_detach_1 (args, from_tty);
5254 }
5255
5256 static void
5257 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5258 {
5259 remote_detach_1 (args, from_tty);
5260 }
5261
5262 /* Target follow-fork function for remote targets. On entry, and
5263 at return, the current inferior is the fork parent.
5264
5265 Note that although this is currently only used for extended-remote,
5266 it is named remote_follow_fork in anticipation of using it for the
5267 remote target as well. */
5268
5269 static int
5270 remote_follow_fork (struct target_ops *ops, int follow_child,
5271 int detach_fork)
5272 {
5273 struct remote_state *rs = get_remote_state ();
5274 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5275
5276 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5277 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5278 {
5279 /* When following the parent and detaching the child, we detach
5280 the child here. For the case of following the child and
5281 detaching the parent, the detach is done in the target-
5282 independent follow fork code in infrun.c. We can't use
5283 target_detach when detaching an unfollowed child because
5284 the client side doesn't know anything about the child. */
5285 if (detach_fork && !follow_child)
5286 {
5287 /* Detach the fork child. */
5288 ptid_t child_ptid;
5289 pid_t child_pid;
5290
5291 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5292 child_pid = ptid_get_pid (child_ptid);
5293
5294 remote_detach_pid (child_pid);
5295 detach_inferior (child_pid);
5296 }
5297 }
5298 return 0;
5299 }
5300
5301 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5302 in the program space of the new inferior. On entry and at return the
5303 current inferior is the exec'ing inferior. INF is the new exec'd
5304 inferior, which may be the same as the exec'ing inferior unless
5305 follow-exec-mode is "new". */
5306
5307 static void
5308 remote_follow_exec (struct target_ops *ops,
5309 struct inferior *inf, char *execd_pathname)
5310 {
5311 /* We know that this is a target file name, so if it has the "target:"
5312 prefix we strip it off before saving it in the program space. */
5313 if (is_target_filename (execd_pathname))
5314 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5315
5316 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5317 }
5318
5319 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5320
5321 static void
5322 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5323 {
5324 if (args)
5325 error (_("Argument given to \"disconnect\" when remotely debugging."));
5326
5327 /* Make sure we unpush even the extended remote targets. Calling
5328 target_mourn_inferior won't unpush, and remote_mourn won't
5329 unpush if there is more than one inferior left. */
5330 unpush_target (target);
5331 generic_mourn_inferior ();
5332
5333 if (from_tty)
5334 puts_filtered ("Ending remote debugging.\n");
5335 }
5336
5337 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5338 be chatty about it. */
5339
5340 static void
5341 extended_remote_attach (struct target_ops *target, const char *args,
5342 int from_tty)
5343 {
5344 struct remote_state *rs = get_remote_state ();
5345 int pid;
5346 char *wait_status = NULL;
5347
5348 pid = parse_pid_to_attach (args);
5349
5350 /* Remote PID can be freely equal to getpid, do not check it here the same
5351 way as in other targets. */
5352
5353 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5354 error (_("This target does not support attaching to a process"));
5355
5356 if (from_tty)
5357 {
5358 char *exec_file = get_exec_file (0);
5359
5360 if (exec_file)
5361 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5362 target_pid_to_str (pid_to_ptid (pid)));
5363 else
5364 printf_unfiltered (_("Attaching to %s\n"),
5365 target_pid_to_str (pid_to_ptid (pid)));
5366
5367 gdb_flush (gdb_stdout);
5368 }
5369
5370 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5371 putpkt (rs->buf);
5372 getpkt (&rs->buf, &rs->buf_size, 0);
5373
5374 switch (packet_ok (rs->buf,
5375 &remote_protocol_packets[PACKET_vAttach]))
5376 {
5377 case PACKET_OK:
5378 if (!target_is_non_stop_p ())
5379 {
5380 /* Save the reply for later. */
5381 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5382 strcpy (wait_status, rs->buf);
5383 }
5384 else if (strcmp (rs->buf, "OK") != 0)
5385 error (_("Attaching to %s failed with: %s"),
5386 target_pid_to_str (pid_to_ptid (pid)),
5387 rs->buf);
5388 break;
5389 case PACKET_UNKNOWN:
5390 error (_("This target does not support attaching to a process"));
5391 default:
5392 error (_("Attaching to %s failed"),
5393 target_pid_to_str (pid_to_ptid (pid)));
5394 }
5395
5396 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5397
5398 inferior_ptid = pid_to_ptid (pid);
5399
5400 if (target_is_non_stop_p ())
5401 {
5402 struct thread_info *thread;
5403
5404 /* Get list of threads. */
5405 remote_update_thread_list (target);
5406
5407 thread = first_thread_of_process (pid);
5408 if (thread)
5409 inferior_ptid = thread->ptid;
5410 else
5411 inferior_ptid = pid_to_ptid (pid);
5412
5413 /* Invalidate our notion of the remote current thread. */
5414 record_currthread (rs, minus_one_ptid);
5415 }
5416 else
5417 {
5418 /* Now, if we have thread information, update inferior_ptid. */
5419 inferior_ptid = remote_current_thread (inferior_ptid);
5420
5421 /* Add the main thread to the thread list. */
5422 add_thread_silent (inferior_ptid);
5423 }
5424
5425 /* Next, if the target can specify a description, read it. We do
5426 this before anything involving memory or registers. */
5427 target_find_description ();
5428
5429 if (!target_is_non_stop_p ())
5430 {
5431 /* Use the previously fetched status. */
5432 gdb_assert (wait_status != NULL);
5433
5434 if (target_can_async_p ())
5435 {
5436 struct notif_event *reply
5437 = remote_notif_parse (&notif_client_stop, wait_status);
5438
5439 push_stop_reply ((struct stop_reply *) reply);
5440
5441 target_async (1);
5442 }
5443 else
5444 {
5445 gdb_assert (wait_status != NULL);
5446 strcpy (rs->buf, wait_status);
5447 rs->cached_wait_status = 1;
5448 }
5449 }
5450 else
5451 gdb_assert (wait_status == NULL);
5452 }
5453
5454 /* Implementation of the to_post_attach method. */
5455
5456 static void
5457 extended_remote_post_attach (struct target_ops *ops, int pid)
5458 {
5459 /* Get text, data & bss offsets. */
5460 get_offsets ();
5461
5462 /* In certain cases GDB might not have had the chance to start
5463 symbol lookup up until now. This could happen if the debugged
5464 binary is not using shared libraries, the vsyscall page is not
5465 present (on Linux) and the binary itself hadn't changed since the
5466 debugging process was started. */
5467 if (symfile_objfile != NULL)
5468 remote_check_symbols();
5469 }
5470
5471 \f
5472 /* Check for the availability of vCont. This function should also check
5473 the response. */
5474
5475 static void
5476 remote_vcont_probe (struct remote_state *rs)
5477 {
5478 char *buf;
5479
5480 strcpy (rs->buf, "vCont?");
5481 putpkt (rs->buf);
5482 getpkt (&rs->buf, &rs->buf_size, 0);
5483 buf = rs->buf;
5484
5485 /* Make sure that the features we assume are supported. */
5486 if (startswith (buf, "vCont"))
5487 {
5488 char *p = &buf[5];
5489 int support_c, support_C;
5490
5491 rs->supports_vCont.s = 0;
5492 rs->supports_vCont.S = 0;
5493 support_c = 0;
5494 support_C = 0;
5495 rs->supports_vCont.t = 0;
5496 rs->supports_vCont.r = 0;
5497 while (p && *p == ';')
5498 {
5499 p++;
5500 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5501 rs->supports_vCont.s = 1;
5502 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5503 rs->supports_vCont.S = 1;
5504 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5505 support_c = 1;
5506 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5507 support_C = 1;
5508 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5509 rs->supports_vCont.t = 1;
5510 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5511 rs->supports_vCont.r = 1;
5512
5513 p = strchr (p, ';');
5514 }
5515
5516 /* If c, and C are not all supported, we can't use vCont. Clearing
5517 BUF will make packet_ok disable the packet. */
5518 if (!support_c || !support_C)
5519 buf[0] = 0;
5520 }
5521
5522 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5523 }
5524
5525 /* Helper function for building "vCont" resumptions. Write a
5526 resumption to P. ENDP points to one-passed-the-end of the buffer
5527 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5528 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5529 resumed thread should be single-stepped and/or signalled. If PTID
5530 equals minus_one_ptid, then all threads are resumed; if PTID
5531 represents a process, then all threads of the process are resumed;
5532 the thread to be stepped and/or signalled is given in the global
5533 INFERIOR_PTID. */
5534
5535 static char *
5536 append_resumption (char *p, char *endp,
5537 ptid_t ptid, int step, enum gdb_signal siggnal)
5538 {
5539 struct remote_state *rs = get_remote_state ();
5540
5541 if (step && siggnal != GDB_SIGNAL_0)
5542 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5543 else if (step
5544 /* GDB is willing to range step. */
5545 && use_range_stepping
5546 /* Target supports range stepping. */
5547 && rs->supports_vCont.r
5548 /* We don't currently support range stepping multiple
5549 threads with a wildcard (though the protocol allows it,
5550 so stubs shouldn't make an active effort to forbid
5551 it). */
5552 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5553 {
5554 struct thread_info *tp;
5555
5556 if (ptid_equal (ptid, minus_one_ptid))
5557 {
5558 /* If we don't know about the target thread's tid, then
5559 we're resuming magic_null_ptid (see caller). */
5560 tp = find_thread_ptid (magic_null_ptid);
5561 }
5562 else
5563 tp = find_thread_ptid (ptid);
5564 gdb_assert (tp != NULL);
5565
5566 if (tp->control.may_range_step)
5567 {
5568 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5569
5570 p += xsnprintf (p, endp - p, ";r%s,%s",
5571 phex_nz (tp->control.step_range_start,
5572 addr_size),
5573 phex_nz (tp->control.step_range_end,
5574 addr_size));
5575 }
5576 else
5577 p += xsnprintf (p, endp - p, ";s");
5578 }
5579 else if (step)
5580 p += xsnprintf (p, endp - p, ";s");
5581 else if (siggnal != GDB_SIGNAL_0)
5582 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5583 else
5584 p += xsnprintf (p, endp - p, ";c");
5585
5586 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5587 {
5588 ptid_t nptid;
5589
5590 /* All (-1) threads of process. */
5591 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5592
5593 p += xsnprintf (p, endp - p, ":");
5594 p = write_ptid (p, endp, nptid);
5595 }
5596 else if (!ptid_equal (ptid, minus_one_ptid))
5597 {
5598 p += xsnprintf (p, endp - p, ":");
5599 p = write_ptid (p, endp, ptid);
5600 }
5601
5602 return p;
5603 }
5604
5605 /* Clear the thread's private info on resume. */
5606
5607 static void
5608 resume_clear_thread_private_info (struct thread_info *thread)
5609 {
5610 if (thread->priv != NULL)
5611 {
5612 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5613 thread->priv->watch_data_address = 0;
5614 }
5615 }
5616
5617 /* Append a vCont continue-with-signal action for threads that have a
5618 non-zero stop signal. */
5619
5620 static char *
5621 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5622 {
5623 struct thread_info *thread;
5624
5625 ALL_NON_EXITED_THREADS (thread)
5626 if (ptid_match (thread->ptid, ptid)
5627 && !ptid_equal (inferior_ptid, thread->ptid)
5628 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5629 {
5630 p = append_resumption (p, endp, thread->ptid,
5631 0, thread->suspend.stop_signal);
5632 thread->suspend.stop_signal = GDB_SIGNAL_0;
5633 resume_clear_thread_private_info (thread);
5634 }
5635
5636 return p;
5637 }
5638
5639 /* Set the target running, using the packets that use Hc
5640 (c/s/C/S). */
5641
5642 static void
5643 remote_resume_with_hc (struct target_ops *ops,
5644 ptid_t ptid, int step, enum gdb_signal siggnal)
5645 {
5646 struct remote_state *rs = get_remote_state ();
5647 struct thread_info *thread;
5648 char *buf;
5649
5650 rs->last_sent_signal = siggnal;
5651 rs->last_sent_step = step;
5652
5653 /* The c/s/C/S resume packets use Hc, so set the continue
5654 thread. */
5655 if (ptid_equal (ptid, minus_one_ptid))
5656 set_continue_thread (any_thread_ptid);
5657 else
5658 set_continue_thread (ptid);
5659
5660 ALL_NON_EXITED_THREADS (thread)
5661 resume_clear_thread_private_info (thread);
5662
5663 buf = rs->buf;
5664 if (execution_direction == EXEC_REVERSE)
5665 {
5666 /* We don't pass signals to the target in reverse exec mode. */
5667 if (info_verbose && siggnal != GDB_SIGNAL_0)
5668 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5669 siggnal);
5670
5671 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5672 error (_("Remote reverse-step not supported."));
5673 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5674 error (_("Remote reverse-continue not supported."));
5675
5676 strcpy (buf, step ? "bs" : "bc");
5677 }
5678 else if (siggnal != GDB_SIGNAL_0)
5679 {
5680 buf[0] = step ? 'S' : 'C';
5681 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5682 buf[2] = tohex (((int) siggnal) & 0xf);
5683 buf[3] = '\0';
5684 }
5685 else
5686 strcpy (buf, step ? "s" : "c");
5687
5688 putpkt (buf);
5689 }
5690
5691 /* Resume the remote inferior by using a "vCont" packet. The thread
5692 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5693 resumed thread should be single-stepped and/or signalled. If PTID
5694 equals minus_one_ptid, then all threads are resumed; the thread to
5695 be stepped and/or signalled is given in the global INFERIOR_PTID.
5696 This function returns non-zero iff it resumes the inferior.
5697
5698 This function issues a strict subset of all possible vCont commands
5699 at the moment. */
5700
5701 static int
5702 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5703 {
5704 struct remote_state *rs = get_remote_state ();
5705 char *p;
5706 char *endp;
5707
5708 /* No reverse execution actions defined for vCont. */
5709 if (execution_direction == EXEC_REVERSE)
5710 return 0;
5711
5712 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5713 remote_vcont_probe (rs);
5714
5715 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5716 return 0;
5717
5718 p = rs->buf;
5719 endp = rs->buf + get_remote_packet_size ();
5720
5721 /* If we could generate a wider range of packets, we'd have to worry
5722 about overflowing BUF. Should there be a generic
5723 "multi-part-packet" packet? */
5724
5725 p += xsnprintf (p, endp - p, "vCont");
5726
5727 if (ptid_equal (ptid, magic_null_ptid))
5728 {
5729 /* MAGIC_NULL_PTID means that we don't have any active threads,
5730 so we don't have any TID numbers the inferior will
5731 understand. Make sure to only send forms that do not specify
5732 a TID. */
5733 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5734 }
5735 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5736 {
5737 /* Resume all threads (of all processes, or of a single
5738 process), with preference for INFERIOR_PTID. This assumes
5739 inferior_ptid belongs to the set of all threads we are about
5740 to resume. */
5741 if (step || siggnal != GDB_SIGNAL_0)
5742 {
5743 /* Step inferior_ptid, with or without signal. */
5744 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5745 }
5746
5747 /* Also pass down any pending signaled resumption for other
5748 threads not the current. */
5749 p = append_pending_thread_resumptions (p, endp, ptid);
5750
5751 /* And continue others without a signal. */
5752 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5753 }
5754 else
5755 {
5756 /* Scheduler locking; resume only PTID. */
5757 append_resumption (p, endp, ptid, step, siggnal);
5758 }
5759
5760 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5761 putpkt (rs->buf);
5762
5763 if (target_is_non_stop_p ())
5764 {
5765 /* In non-stop, the stub replies to vCont with "OK". The stop
5766 reply will be reported asynchronously by means of a `%Stop'
5767 notification. */
5768 getpkt (&rs->buf, &rs->buf_size, 0);
5769 if (strcmp (rs->buf, "OK") != 0)
5770 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5771 }
5772
5773 return 1;
5774 }
5775
5776 /* Tell the remote machine to resume. */
5777
5778 static void
5779 remote_resume (struct target_ops *ops,
5780 ptid_t ptid, int step, enum gdb_signal siggnal)
5781 {
5782 struct remote_state *rs = get_remote_state ();
5783
5784 /* When connected in non-stop mode, the core resumes threads
5785 individually. Resuming remote threads directly in target_resume
5786 would thus result in sending one packet per thread. Instead, to
5787 minimize roundtrip latency, here we just store the resume
5788 request; the actual remote resumption will be done in
5789 target_commit_resume / remote_commit_resume, where we'll be able
5790 to do vCont action coalescing. */
5791 if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5792 {
5793 struct private_thread_info *remote_thr;
5794
5795 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5796 remote_thr = get_private_info_ptid (inferior_ptid);
5797 else
5798 remote_thr = get_private_info_ptid (ptid);
5799 remote_thr->last_resume_step = step;
5800 remote_thr->last_resume_sig = siggnal;
5801 return;
5802 }
5803
5804 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5805 (explained in remote-notif.c:handle_notification) so
5806 remote_notif_process is not called. We need find a place where
5807 it is safe to start a 'vNotif' sequence. It is good to do it
5808 before resuming inferior, because inferior was stopped and no RSP
5809 traffic at that moment. */
5810 if (!target_is_non_stop_p ())
5811 remote_notif_process (rs->notif_state, &notif_client_stop);
5812
5813 rs->last_resume_exec_dir = execution_direction;
5814
5815 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
5816 if (!remote_resume_with_vcont (ptid, step, siggnal))
5817 remote_resume_with_hc (ops, ptid, step, siggnal);
5818
5819 /* We are about to start executing the inferior, let's register it
5820 with the event loop. NOTE: this is the one place where all the
5821 execution commands end up. We could alternatively do this in each
5822 of the execution commands in infcmd.c. */
5823 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5824 into infcmd.c in order to allow inferior function calls to work
5825 NOT asynchronously. */
5826 if (target_can_async_p ())
5827 target_async (1);
5828
5829 /* We've just told the target to resume. The remote server will
5830 wait for the inferior to stop, and then send a stop reply. In
5831 the mean time, we can't start another command/query ourselves
5832 because the stub wouldn't be ready to process it. This applies
5833 only to the base all-stop protocol, however. In non-stop (which
5834 only supports vCont), the stub replies with an "OK", and is
5835 immediate able to process further serial input. */
5836 if (!target_is_non_stop_p ())
5837 rs->waiting_for_stop_reply = 1;
5838 }
5839
5840 static void check_pending_events_prevent_wildcard_vcont
5841 (int *may_global_wildcard_vcont);
5842 static int is_pending_fork_parent_thread (struct thread_info *thread);
5843
5844 /* Private per-inferior info for target remote processes. */
5845
5846 struct private_inferior
5847 {
5848 /* Whether we can send a wildcard vCont for this process. */
5849 int may_wildcard_vcont;
5850 };
5851
5852 /* Structure used to track the construction of a vCont packet in the
5853 outgoing packet buffer. This is used to send multiple vCont
5854 packets if we have more actions than would fit a single packet. */
5855
5856 struct vcont_builder
5857 {
5858 /* Pointer to the first action. P points here if no action has been
5859 appended yet. */
5860 char *first_action;
5861
5862 /* Where the next action will be appended. */
5863 char *p;
5864
5865 /* The end of the buffer. Must never write past this. */
5866 char *endp;
5867 };
5868
5869 /* Prepare the outgoing buffer for a new vCont packet. */
5870
5871 static void
5872 vcont_builder_restart (struct vcont_builder *builder)
5873 {
5874 struct remote_state *rs = get_remote_state ();
5875
5876 builder->p = rs->buf;
5877 builder->endp = rs->buf + get_remote_packet_size ();
5878 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5879 builder->first_action = builder->p;
5880 }
5881
5882 /* If the vCont packet being built has any action, send it to the
5883 remote end. */
5884
5885 static void
5886 vcont_builder_flush (struct vcont_builder *builder)
5887 {
5888 struct remote_state *rs;
5889
5890 if (builder->p == builder->first_action)
5891 return;
5892
5893 rs = get_remote_state ();
5894 putpkt (rs->buf);
5895 getpkt (&rs->buf, &rs->buf_size, 0);
5896 if (strcmp (rs->buf, "OK") != 0)
5897 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5898 }
5899
5900 /* The largest action is range-stepping, with its two addresses. This
5901 is more than sufficient. If a new, bigger action is created, it'll
5902 quickly trigger a failed assertion in append_resumption (and we'll
5903 just bump this). */
5904 #define MAX_ACTION_SIZE 200
5905
5906 /* Append a new vCont action in the outgoing packet being built. If
5907 the action doesn't fit the packet along with previous actions, push
5908 what we've got so far to the remote end and start over a new vCont
5909 packet (with the new action). */
5910
5911 static void
5912 vcont_builder_push_action (struct vcont_builder *builder,
5913 ptid_t ptid, int step, enum gdb_signal siggnal)
5914 {
5915 char buf[MAX_ACTION_SIZE + 1];
5916 char *endp;
5917 size_t rsize;
5918
5919 endp = append_resumption (buf, buf + sizeof (buf),
5920 ptid, step, siggnal);
5921
5922 /* Check whether this new action would fit in the vCont packet along
5923 with previous actions. If not, send what we've got so far and
5924 start a new vCont packet. */
5925 rsize = endp - buf;
5926 if (rsize > builder->endp - builder->p)
5927 {
5928 vcont_builder_flush (builder);
5929 vcont_builder_restart (builder);
5930
5931 /* Should now fit. */
5932 gdb_assert (rsize <= builder->endp - builder->p);
5933 }
5934
5935 memcpy (builder->p, buf, rsize);
5936 builder->p += rsize;
5937 *builder->p = '\0';
5938 }
5939
5940 /* to_commit_resume implementation. */
5941
5942 static void
5943 remote_commit_resume (struct target_ops *ops)
5944 {
5945 struct remote_state *rs = get_remote_state ();
5946 struct inferior *inf;
5947 struct thread_info *tp;
5948 int any_process_wildcard;
5949 int may_global_wildcard_vcont;
5950 struct vcont_builder vcont_builder;
5951
5952 /* If connected in all-stop mode, we'd send the remote resume
5953 request directly from remote_resume. Likewise if
5954 reverse-debugging, as there are no defined vCont actions for
5955 reverse execution. */
5956 if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5957 return;
5958
5959 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5960 instead of resuming all threads of each process individually.
5961 However, if any thread of a process must remain halted, we can't
5962 send wildcard resumes and must send one action per thread.
5963
5964 Care must be taken to not resume threads/processes the server
5965 side already told us are stopped, but the core doesn't know about
5966 yet, because the events are still in the vStopped notification
5967 queue. For example:
5968
5969 #1 => vCont s:p1.1;c
5970 #2 <= OK
5971 #3 <= %Stopped T05 p1.1
5972 #4 => vStopped
5973 #5 <= T05 p1.2
5974 #6 => vStopped
5975 #7 <= OK
5976 #8 (infrun handles the stop for p1.1 and continues stepping)
5977 #9 => vCont s:p1.1;c
5978
5979 The last vCont above would resume thread p1.2 by mistake, because
5980 the server has no idea that the event for p1.2 had not been
5981 handled yet.
5982
5983 The server side must similarly ignore resume actions for the
5984 thread that has a pending %Stopped notification (and any other
5985 threads with events pending), until GDB acks the notification
5986 with vStopped. Otherwise, e.g., the following case is
5987 mishandled:
5988
5989 #1 => g (or any other packet)
5990 #2 <= [registers]
5991 #3 <= %Stopped T05 p1.2
5992 #4 => vCont s:p1.1;c
5993 #5 <= OK
5994
5995 Above, the server must not resume thread p1.2. GDB can't know
5996 that p1.2 stopped until it acks the %Stopped notification, and
5997 since from GDB's perspective all threads should be running, it
5998 sends a "c" action.
5999
6000 Finally, special care must also be given to handling fork/vfork
6001 events. A (v)fork event actually tells us that two processes
6002 stopped -- the parent and the child. Until we follow the fork,
6003 we must not resume the child. Therefore, if we have a pending
6004 fork follow, we must not send a global wildcard resume action
6005 (vCont;c). We can still send process-wide wildcards though. */
6006
6007 /* Start by assuming a global wildcard (vCont;c) is possible. */
6008 may_global_wildcard_vcont = 1;
6009
6010 /* And assume every process is individually wildcard-able too. */
6011 ALL_NON_EXITED_INFERIORS (inf)
6012 {
6013 if (inf->priv == NULL)
6014 inf->priv = XNEW (struct private_inferior);
6015 inf->priv->may_wildcard_vcont = 1;
6016 }
6017
6018 /* Check for any pending events (not reported or processed yet) and
6019 disable process and global wildcard resumes appropriately. */
6020 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6021
6022 ALL_NON_EXITED_THREADS (tp)
6023 {
6024 /* If a thread of a process is not meant to be resumed, then we
6025 can't wildcard that process. */
6026 if (!tp->executing)
6027 {
6028 tp->inf->priv->may_wildcard_vcont = 0;
6029
6030 /* And if we can't wildcard a process, we can't wildcard
6031 everything either. */
6032 may_global_wildcard_vcont = 0;
6033 continue;
6034 }
6035
6036 /* If a thread is the parent of an unfollowed fork, then we
6037 can't do a global wildcard, as that would resume the fork
6038 child. */
6039 if (is_pending_fork_parent_thread (tp))
6040 may_global_wildcard_vcont = 0;
6041 }
6042
6043 /* Now let's build the vCont packet(s). Actions must be appended
6044 from narrower to wider scopes (thread -> process -> global). If
6045 we end up with too many actions for a single packet vcont_builder
6046 flushes the current vCont packet to the remote side and starts a
6047 new one. */
6048 vcont_builder_restart (&vcont_builder);
6049
6050 /* Threads first. */
6051 ALL_NON_EXITED_THREADS (tp)
6052 {
6053 struct private_thread_info *remote_thr = tp->priv;
6054
6055 if (!tp->executing || remote_thr->vcont_resumed)
6056 continue;
6057
6058 gdb_assert (!thread_is_in_step_over_chain (tp));
6059
6060 if (!remote_thr->last_resume_step
6061 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6062 && tp->inf->priv->may_wildcard_vcont)
6063 {
6064 /* We'll send a wildcard resume instead. */
6065 remote_thr->vcont_resumed = 1;
6066 continue;
6067 }
6068
6069 vcont_builder_push_action (&vcont_builder, tp->ptid,
6070 remote_thr->last_resume_step,
6071 remote_thr->last_resume_sig);
6072 remote_thr->vcont_resumed = 1;
6073 }
6074
6075 /* Now check whether we can send any process-wide wildcard. This is
6076 to avoid sending a global wildcard in the case nothing is
6077 supposed to be resumed. */
6078 any_process_wildcard = 0;
6079
6080 ALL_NON_EXITED_INFERIORS (inf)
6081 {
6082 if (inf->priv->may_wildcard_vcont)
6083 {
6084 any_process_wildcard = 1;
6085 break;
6086 }
6087 }
6088
6089 if (any_process_wildcard)
6090 {
6091 /* If all processes are wildcard-able, then send a single "c"
6092 action, otherwise, send an "all (-1) threads of process"
6093 continue action for each running process, if any. */
6094 if (may_global_wildcard_vcont)
6095 {
6096 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6097 0, GDB_SIGNAL_0);
6098 }
6099 else
6100 {
6101 ALL_NON_EXITED_INFERIORS (inf)
6102 {
6103 if (inf->priv->may_wildcard_vcont)
6104 {
6105 vcont_builder_push_action (&vcont_builder,
6106 pid_to_ptid (inf->pid),
6107 0, GDB_SIGNAL_0);
6108 }
6109 }
6110 }
6111 }
6112
6113 vcont_builder_flush (&vcont_builder);
6114 }
6115
6116 \f
6117
6118 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6119 thread, all threads of a remote process, or all threads of all
6120 processes. */
6121
6122 static void
6123 remote_stop_ns (ptid_t ptid)
6124 {
6125 struct remote_state *rs = get_remote_state ();
6126 char *p = rs->buf;
6127 char *endp = rs->buf + get_remote_packet_size ();
6128
6129 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6130 remote_vcont_probe (rs);
6131
6132 if (!rs->supports_vCont.t)
6133 error (_("Remote server does not support stopping threads"));
6134
6135 if (ptid_equal (ptid, minus_one_ptid)
6136 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6137 p += xsnprintf (p, endp - p, "vCont;t");
6138 else
6139 {
6140 ptid_t nptid;
6141
6142 p += xsnprintf (p, endp - p, "vCont;t:");
6143
6144 if (ptid_is_pid (ptid))
6145 /* All (-1) threads of process. */
6146 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6147 else
6148 {
6149 /* Small optimization: if we already have a stop reply for
6150 this thread, no use in telling the stub we want this
6151 stopped. */
6152 if (peek_stop_reply (ptid))
6153 return;
6154
6155 nptid = ptid;
6156 }
6157
6158 write_ptid (p, endp, nptid);
6159 }
6160
6161 /* In non-stop, we get an immediate OK reply. The stop reply will
6162 come in asynchronously by notification. */
6163 putpkt (rs->buf);
6164 getpkt (&rs->buf, &rs->buf_size, 0);
6165 if (strcmp (rs->buf, "OK") != 0)
6166 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6167 }
6168
6169 /* All-stop version of target_interrupt. Sends a break or a ^C to
6170 interrupt the remote target. It is undefined which thread of which
6171 process reports the interrupt. */
6172
6173 static void
6174 remote_interrupt_as (void)
6175 {
6176 struct remote_state *rs = get_remote_state ();
6177
6178 rs->ctrlc_pending_p = 1;
6179
6180 /* If the inferior is stopped already, but the core didn't know
6181 about it yet, just ignore the request. The cached wait status
6182 will be collected in remote_wait. */
6183 if (rs->cached_wait_status)
6184 return;
6185
6186 /* Send interrupt_sequence to remote target. */
6187 send_interrupt_sequence ();
6188 }
6189
6190 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6191 the remote target. It is undefined which thread of which process
6192 reports the interrupt. Throws an error if the packet is not
6193 supported by the server. */
6194
6195 static void
6196 remote_interrupt_ns (void)
6197 {
6198 struct remote_state *rs = get_remote_state ();
6199 char *p = rs->buf;
6200 char *endp = rs->buf + get_remote_packet_size ();
6201
6202 xsnprintf (p, endp - p, "vCtrlC");
6203
6204 /* In non-stop, we get an immediate OK reply. The stop reply will
6205 come in asynchronously by notification. */
6206 putpkt (rs->buf);
6207 getpkt (&rs->buf, &rs->buf_size, 0);
6208
6209 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6210 {
6211 case PACKET_OK:
6212 break;
6213 case PACKET_UNKNOWN:
6214 error (_("No support for interrupting the remote target."));
6215 case PACKET_ERROR:
6216 error (_("Interrupting target failed: %s"), rs->buf);
6217 }
6218 }
6219
6220 /* Implement the to_stop function for the remote targets. */
6221
6222 static void
6223 remote_stop (struct target_ops *self, ptid_t ptid)
6224 {
6225 if (remote_debug)
6226 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6227
6228 if (target_is_non_stop_p ())
6229 remote_stop_ns (ptid);
6230 else
6231 {
6232 /* We don't currently have a way to transparently pause the
6233 remote target in all-stop mode. Interrupt it instead. */
6234 remote_interrupt_as ();
6235 }
6236 }
6237
6238 /* Implement the to_interrupt function for the remote targets. */
6239
6240 static void
6241 remote_interrupt (struct target_ops *self, ptid_t ptid)
6242 {
6243 struct remote_state *rs = get_remote_state ();
6244
6245 if (remote_debug)
6246 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6247
6248 if (target_is_non_stop_p ())
6249 remote_interrupt_ns ();
6250 else
6251 remote_interrupt_as ();
6252 }
6253
6254 /* Implement the to_pass_ctrlc function for the remote targets. */
6255
6256 static void
6257 remote_pass_ctrlc (struct target_ops *self)
6258 {
6259 struct remote_state *rs = get_remote_state ();
6260
6261 if (remote_debug)
6262 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6263
6264 /* If we're starting up, we're not fully synced yet. Quit
6265 immediately. */
6266 if (rs->starting_up)
6267 quit ();
6268 /* If ^C has already been sent once, offer to disconnect. */
6269 else if (rs->ctrlc_pending_p)
6270 interrupt_query ();
6271 else
6272 target_interrupt (inferior_ptid);
6273 }
6274
6275 /* Ask the user what to do when an interrupt is received. */
6276
6277 static void
6278 interrupt_query (void)
6279 {
6280 struct remote_state *rs = get_remote_state ();
6281
6282 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6283 {
6284 if (query (_("The target is not responding to interrupt requests.\n"
6285 "Stop debugging it? ")))
6286 {
6287 remote_unpush_target ();
6288 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6289 }
6290 }
6291 else
6292 {
6293 if (query (_("Interrupted while waiting for the program.\n"
6294 "Give up waiting? ")))
6295 quit ();
6296 }
6297 }
6298
6299 /* Enable/disable target terminal ownership. Most targets can use
6300 terminal groups to control terminal ownership. Remote targets are
6301 different in that explicit transfer of ownership to/from GDB/target
6302 is required. */
6303
6304 static void
6305 remote_terminal_inferior (struct target_ops *self)
6306 {
6307 /* FIXME: cagney/1999-09-27: Make calls to target_terminal::*()
6308 idempotent. The event-loop GDB talking to an asynchronous target
6309 with a synchronous command calls this function from both
6310 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
6311 transfer the terminal to the target when it shouldn't this guard
6312 can go away. */
6313 if (!remote_async_terminal_ours_p)
6314 return;
6315 remote_async_terminal_ours_p = 0;
6316 /* NOTE: At this point we could also register our selves as the
6317 recipient of all input. Any characters typed could then be
6318 passed on down to the target. */
6319 }
6320
6321 static void
6322 remote_terminal_ours (struct target_ops *self)
6323 {
6324 /* See FIXME in remote_terminal_inferior. */
6325 if (remote_async_terminal_ours_p)
6326 return;
6327 remote_async_terminal_ours_p = 1;
6328 }
6329
6330 static void
6331 remote_console_output (char *msg)
6332 {
6333 char *p;
6334
6335 for (p = msg; p[0] && p[1]; p += 2)
6336 {
6337 char tb[2];
6338 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6339
6340 tb[0] = c;
6341 tb[1] = 0;
6342 fputs_unfiltered (tb, gdb_stdtarg);
6343 }
6344 gdb_flush (gdb_stdtarg);
6345 }
6346
6347 DEF_VEC_O(cached_reg_t);
6348
6349 typedef struct stop_reply
6350 {
6351 struct notif_event base;
6352
6353 /* The identifier of the thread about this event */
6354 ptid_t ptid;
6355
6356 /* The remote state this event is associated with. When the remote
6357 connection, represented by a remote_state object, is closed,
6358 all the associated stop_reply events should be released. */
6359 struct remote_state *rs;
6360
6361 struct target_waitstatus ws;
6362
6363 /* Expedited registers. This makes remote debugging a bit more
6364 efficient for those targets that provide critical registers as
6365 part of their normal status mechanism (as another roundtrip to
6366 fetch them is avoided). */
6367 VEC(cached_reg_t) *regcache;
6368
6369 enum target_stop_reason stop_reason;
6370
6371 CORE_ADDR watch_data_address;
6372
6373 int core;
6374 } *stop_reply_p;
6375
6376 DECLARE_QUEUE_P (stop_reply_p);
6377 DEFINE_QUEUE_P (stop_reply_p);
6378 /* The list of already fetched and acknowledged stop events. This
6379 queue is used for notification Stop, and other notifications
6380 don't need queue for their events, because the notification events
6381 of Stop can't be consumed immediately, so that events should be
6382 queued first, and be consumed by remote_wait_{ns,as} one per
6383 time. Other notifications can consume their events immediately,
6384 so queue is not needed for them. */
6385 static QUEUE (stop_reply_p) *stop_reply_queue;
6386
6387 static void
6388 stop_reply_xfree (struct stop_reply *r)
6389 {
6390 notif_event_xfree ((struct notif_event *) r);
6391 }
6392
6393 /* Return the length of the stop reply queue. */
6394
6395 static int
6396 stop_reply_queue_length (void)
6397 {
6398 return QUEUE_length (stop_reply_p, stop_reply_queue);
6399 }
6400
6401 static void
6402 remote_notif_stop_parse (struct notif_client *self, char *buf,
6403 struct notif_event *event)
6404 {
6405 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6406 }
6407
6408 static void
6409 remote_notif_stop_ack (struct notif_client *self, char *buf,
6410 struct notif_event *event)
6411 {
6412 struct stop_reply *stop_reply = (struct stop_reply *) event;
6413
6414 /* acknowledge */
6415 putpkt (self->ack_command);
6416
6417 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6418 /* We got an unknown stop reply. */
6419 error (_("Unknown stop reply"));
6420
6421 push_stop_reply (stop_reply);
6422 }
6423
6424 static int
6425 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6426 {
6427 /* We can't get pending events in remote_notif_process for
6428 notification stop, and we have to do this in remote_wait_ns
6429 instead. If we fetch all queued events from stub, remote stub
6430 may exit and we have no chance to process them back in
6431 remote_wait_ns. */
6432 mark_async_event_handler (remote_async_inferior_event_token);
6433 return 0;
6434 }
6435
6436 static void
6437 stop_reply_dtr (struct notif_event *event)
6438 {
6439 struct stop_reply *r = (struct stop_reply *) event;
6440 cached_reg_t *reg;
6441 int ix;
6442
6443 for (ix = 0;
6444 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6445 ix++)
6446 xfree (reg->data);
6447
6448 VEC_free (cached_reg_t, r->regcache);
6449 }
6450
6451 static struct notif_event *
6452 remote_notif_stop_alloc_reply (void)
6453 {
6454 /* We cast to a pointer to the "base class". */
6455 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6456
6457 r->dtr = stop_reply_dtr;
6458
6459 return r;
6460 }
6461
6462 /* A client of notification Stop. */
6463
6464 struct notif_client notif_client_stop =
6465 {
6466 "Stop",
6467 "vStopped",
6468 remote_notif_stop_parse,
6469 remote_notif_stop_ack,
6470 remote_notif_stop_can_get_pending_events,
6471 remote_notif_stop_alloc_reply,
6472 REMOTE_NOTIF_STOP,
6473 };
6474
6475 /* A parameter to pass data in and out. */
6476
6477 struct queue_iter_param
6478 {
6479 void *input;
6480 struct stop_reply *output;
6481 };
6482
6483 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6484 the pid of the process that owns the threads we want to check, or
6485 -1 if we want to check all threads. */
6486
6487 static int
6488 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6489 ptid_t thread_ptid)
6490 {
6491 if (ws->kind == TARGET_WAITKIND_FORKED
6492 || ws->kind == TARGET_WAITKIND_VFORKED)
6493 {
6494 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6495 return 1;
6496 }
6497
6498 return 0;
6499 }
6500
6501 /* Return the thread's pending status used to determine whether the
6502 thread is a fork parent stopped at a fork event. */
6503
6504 static struct target_waitstatus *
6505 thread_pending_fork_status (struct thread_info *thread)
6506 {
6507 if (thread->suspend.waitstatus_pending_p)
6508 return &thread->suspend.waitstatus;
6509 else
6510 return &thread->pending_follow;
6511 }
6512
6513 /* Determine if THREAD is a pending fork parent thread. */
6514
6515 static int
6516 is_pending_fork_parent_thread (struct thread_info *thread)
6517 {
6518 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6519 int pid = -1;
6520
6521 return is_pending_fork_parent (ws, pid, thread->ptid);
6522 }
6523
6524 /* Check whether EVENT is a fork event, and if it is, remove the
6525 fork child from the context list passed in DATA. */
6526
6527 static int
6528 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6529 QUEUE_ITER (stop_reply_p) *iter,
6530 stop_reply_p event,
6531 void *data)
6532 {
6533 struct queue_iter_param *param = (struct queue_iter_param *) data;
6534 struct threads_listing_context *context
6535 = (struct threads_listing_context *) param->input;
6536
6537 if (event->ws.kind == TARGET_WAITKIND_FORKED
6538 || event->ws.kind == TARGET_WAITKIND_VFORKED
6539 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6540 threads_listing_context_remove (&event->ws, context);
6541
6542 return 1;
6543 }
6544
6545 /* If CONTEXT contains any fork child threads that have not been
6546 reported yet, remove them from the CONTEXT list. If such a
6547 thread exists it is because we are stopped at a fork catchpoint
6548 and have not yet called follow_fork, which will set up the
6549 host-side data structures for the new process. */
6550
6551 static void
6552 remove_new_fork_children (struct threads_listing_context *context)
6553 {
6554 struct thread_info * thread;
6555 int pid = -1;
6556 struct notif_client *notif = &notif_client_stop;
6557 struct queue_iter_param param;
6558
6559 /* For any threads stopped at a fork event, remove the corresponding
6560 fork child threads from the CONTEXT list. */
6561 ALL_NON_EXITED_THREADS (thread)
6562 {
6563 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6564
6565 if (is_pending_fork_parent (ws, pid, thread->ptid))
6566 {
6567 threads_listing_context_remove (ws, context);
6568 }
6569 }
6570
6571 /* Check for any pending fork events (not reported or processed yet)
6572 in process PID and remove those fork child threads from the
6573 CONTEXT list as well. */
6574 remote_notif_get_pending_events (notif);
6575 param.input = context;
6576 param.output = NULL;
6577 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6578 remove_child_of_pending_fork, &param);
6579 }
6580
6581 /* Check whether EVENT would prevent a global or process wildcard
6582 vCont action. */
6583
6584 static int
6585 check_pending_event_prevents_wildcard_vcont_callback
6586 (QUEUE (stop_reply_p) *q,
6587 QUEUE_ITER (stop_reply_p) *iter,
6588 stop_reply_p event,
6589 void *data)
6590 {
6591 struct inferior *inf;
6592 int *may_global_wildcard_vcont = (int *) data;
6593
6594 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6595 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6596 return 1;
6597
6598 if (event->ws.kind == TARGET_WAITKIND_FORKED
6599 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6600 *may_global_wildcard_vcont = 0;
6601
6602 inf = find_inferior_ptid (event->ptid);
6603
6604 /* This may be the first time we heard about this process.
6605 Regardless, we must not do a global wildcard resume, otherwise
6606 we'd resume this process too. */
6607 *may_global_wildcard_vcont = 0;
6608 if (inf != NULL)
6609 inf->priv->may_wildcard_vcont = 0;
6610
6611 return 1;
6612 }
6613
6614 /* Check whether any event pending in the vStopped queue would prevent
6615 a global or process wildcard vCont action. Clear
6616 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6617 and clear the event inferior's may_wildcard_vcont flag if we can't
6618 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6619
6620 static void
6621 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6622 {
6623 struct notif_client *notif = &notif_client_stop;
6624
6625 remote_notif_get_pending_events (notif);
6626 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6627 check_pending_event_prevents_wildcard_vcont_callback,
6628 may_global_wildcard);
6629 }
6630
6631 /* Remove stop replies in the queue if its pid is equal to the given
6632 inferior's pid. */
6633
6634 static int
6635 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6636 QUEUE_ITER (stop_reply_p) *iter,
6637 stop_reply_p event,
6638 void *data)
6639 {
6640 struct queue_iter_param *param = (struct queue_iter_param *) data;
6641 struct inferior *inf = (struct inferior *) param->input;
6642
6643 if (ptid_get_pid (event->ptid) == inf->pid)
6644 {
6645 stop_reply_xfree (event);
6646 QUEUE_remove_elem (stop_reply_p, q, iter);
6647 }
6648
6649 return 1;
6650 }
6651
6652 /* Discard all pending stop replies of inferior INF. */
6653
6654 static void
6655 discard_pending_stop_replies (struct inferior *inf)
6656 {
6657 struct queue_iter_param param;
6658 struct stop_reply *reply;
6659 struct remote_state *rs = get_remote_state ();
6660 struct remote_notif_state *rns = rs->notif_state;
6661
6662 /* This function can be notified when an inferior exists. When the
6663 target is not remote, the notification state is NULL. */
6664 if (rs->remote_desc == NULL)
6665 return;
6666
6667 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6668
6669 /* Discard the in-flight notification. */
6670 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6671 {
6672 stop_reply_xfree (reply);
6673 rns->pending_event[notif_client_stop.id] = NULL;
6674 }
6675
6676 param.input = inf;
6677 param.output = NULL;
6678 /* Discard the stop replies we have already pulled with
6679 vStopped. */
6680 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6681 remove_stop_reply_for_inferior, &param);
6682 }
6683
6684 /* If its remote state is equal to the given remote state,
6685 remove EVENT from the stop reply queue. */
6686
6687 static int
6688 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6689 QUEUE_ITER (stop_reply_p) *iter,
6690 stop_reply_p event,
6691 void *data)
6692 {
6693 struct queue_iter_param *param = (struct queue_iter_param *) data;
6694 struct remote_state *rs = (struct remote_state *) param->input;
6695
6696 if (event->rs == rs)
6697 {
6698 stop_reply_xfree (event);
6699 QUEUE_remove_elem (stop_reply_p, q, iter);
6700 }
6701
6702 return 1;
6703 }
6704
6705 /* Discard the stop replies for RS in stop_reply_queue. */
6706
6707 static void
6708 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6709 {
6710 struct queue_iter_param param;
6711
6712 param.input = rs;
6713 param.output = NULL;
6714 /* Discard the stop replies we have already pulled with
6715 vStopped. */
6716 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6717 remove_stop_reply_of_remote_state, &param);
6718 }
6719
6720 /* A parameter to pass data in and out. */
6721
6722 static int
6723 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6724 QUEUE_ITER (stop_reply_p) *iter,
6725 stop_reply_p event,
6726 void *data)
6727 {
6728 struct queue_iter_param *param = (struct queue_iter_param *) data;
6729 ptid_t *ptid = (ptid_t *) param->input;
6730
6731 if (ptid_match (event->ptid, *ptid))
6732 {
6733 param->output = event;
6734 QUEUE_remove_elem (stop_reply_p, q, iter);
6735 return 0;
6736 }
6737
6738 return 1;
6739 }
6740
6741 /* Remove the first reply in 'stop_reply_queue' which matches
6742 PTID. */
6743
6744 static struct stop_reply *
6745 remote_notif_remove_queued_reply (ptid_t ptid)
6746 {
6747 struct queue_iter_param param;
6748
6749 param.input = &ptid;
6750 param.output = NULL;
6751
6752 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6753 remote_notif_remove_once_on_match, &param);
6754 if (notif_debug)
6755 fprintf_unfiltered (gdb_stdlog,
6756 "notif: discard queued event: 'Stop' in %s\n",
6757 target_pid_to_str (ptid));
6758
6759 return param.output;
6760 }
6761
6762 /* Look for a queued stop reply belonging to PTID. If one is found,
6763 remove it from the queue, and return it. Returns NULL if none is
6764 found. If there are still queued events left to process, tell the
6765 event loop to get back to target_wait soon. */
6766
6767 static struct stop_reply *
6768 queued_stop_reply (ptid_t ptid)
6769 {
6770 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6771
6772 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6773 /* There's still at least an event left. */
6774 mark_async_event_handler (remote_async_inferior_event_token);
6775
6776 return r;
6777 }
6778
6779 /* Push a fully parsed stop reply in the stop reply queue. Since we
6780 know that we now have at least one queued event left to pass to the
6781 core side, tell the event loop to get back to target_wait soon. */
6782
6783 static void
6784 push_stop_reply (struct stop_reply *new_event)
6785 {
6786 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6787
6788 if (notif_debug)
6789 fprintf_unfiltered (gdb_stdlog,
6790 "notif: push 'Stop' %s to queue %d\n",
6791 target_pid_to_str (new_event->ptid),
6792 QUEUE_length (stop_reply_p,
6793 stop_reply_queue));
6794
6795 mark_async_event_handler (remote_async_inferior_event_token);
6796 }
6797
6798 static int
6799 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6800 QUEUE_ITER (stop_reply_p) *iter,
6801 struct stop_reply *event,
6802 void *data)
6803 {
6804 ptid_t *ptid = (ptid_t *) data;
6805
6806 return !(ptid_equal (*ptid, event->ptid)
6807 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6808 }
6809
6810 /* Returns true if we have a stop reply for PTID. */
6811
6812 static int
6813 peek_stop_reply (ptid_t ptid)
6814 {
6815 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6816 stop_reply_match_ptid_and_ws, &ptid);
6817 }
6818
6819 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6820 starting with P and ending with PEND matches PREFIX. */
6821
6822 static int
6823 strprefix (const char *p, const char *pend, const char *prefix)
6824 {
6825 for ( ; p < pend; p++, prefix++)
6826 if (*p != *prefix)
6827 return 0;
6828 return *prefix == '\0';
6829 }
6830
6831 /* Parse the stop reply in BUF. Either the function succeeds, and the
6832 result is stored in EVENT, or throws an error. */
6833
6834 static void
6835 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6836 {
6837 struct remote_arch_state *rsa = get_remote_arch_state ();
6838 ULONGEST addr;
6839 char *p;
6840 int skipregs = 0;
6841
6842 event->ptid = null_ptid;
6843 event->rs = get_remote_state ();
6844 event->ws.kind = TARGET_WAITKIND_IGNORE;
6845 event->ws.value.integer = 0;
6846 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6847 event->regcache = NULL;
6848 event->core = -1;
6849
6850 switch (buf[0])
6851 {
6852 case 'T': /* Status with PC, SP, FP, ... */
6853 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6854 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6855 ss = signal number
6856 n... = register number
6857 r... = register contents
6858 */
6859
6860 p = &buf[3]; /* after Txx */
6861 while (*p)
6862 {
6863 char *p1;
6864 int fieldsize;
6865
6866 p1 = strchr (p, ':');
6867 if (p1 == NULL)
6868 error (_("Malformed packet(a) (missing colon): %s\n\
6869 Packet: '%s'\n"),
6870 p, buf);
6871 if (p == p1)
6872 error (_("Malformed packet(a) (missing register number): %s\n\
6873 Packet: '%s'\n"),
6874 p, buf);
6875
6876 /* Some "registers" are actually extended stop information.
6877 Note if you're adding a new entry here: GDB 7.9 and
6878 earlier assume that all register "numbers" that start
6879 with an hex digit are real register numbers. Make sure
6880 the server only sends such a packet if it knows the
6881 client understands it. */
6882
6883 if (strprefix (p, p1, "thread"))
6884 event->ptid = read_ptid (++p1, &p);
6885 else if (strprefix (p, p1, "syscall_entry"))
6886 {
6887 ULONGEST sysno;
6888
6889 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6890 p = unpack_varlen_hex (++p1, &sysno);
6891 event->ws.value.syscall_number = (int) sysno;
6892 }
6893 else if (strprefix (p, p1, "syscall_return"))
6894 {
6895 ULONGEST sysno;
6896
6897 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6898 p = unpack_varlen_hex (++p1, &sysno);
6899 event->ws.value.syscall_number = (int) sysno;
6900 }
6901 else if (strprefix (p, p1, "watch")
6902 || strprefix (p, p1, "rwatch")
6903 || strprefix (p, p1, "awatch"))
6904 {
6905 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6906 p = unpack_varlen_hex (++p1, &addr);
6907 event->watch_data_address = (CORE_ADDR) addr;
6908 }
6909 else if (strprefix (p, p1, "swbreak"))
6910 {
6911 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6912
6913 /* Make sure the stub doesn't forget to indicate support
6914 with qSupported. */
6915 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6916 error (_("Unexpected swbreak stop reason"));
6917
6918 /* The value part is documented as "must be empty",
6919 though we ignore it, in case we ever decide to make
6920 use of it in a backward compatible way. */
6921 p = strchrnul (p1 + 1, ';');
6922 }
6923 else if (strprefix (p, p1, "hwbreak"))
6924 {
6925 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6926
6927 /* Make sure the stub doesn't forget to indicate support
6928 with qSupported. */
6929 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6930 error (_("Unexpected hwbreak stop reason"));
6931
6932 /* See above. */
6933 p = strchrnul (p1 + 1, ';');
6934 }
6935 else if (strprefix (p, p1, "library"))
6936 {
6937 event->ws.kind = TARGET_WAITKIND_LOADED;
6938 p = strchrnul (p1 + 1, ';');
6939 }
6940 else if (strprefix (p, p1, "replaylog"))
6941 {
6942 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6943 /* p1 will indicate "begin" or "end", but it makes
6944 no difference for now, so ignore it. */
6945 p = strchrnul (p1 + 1, ';');
6946 }
6947 else if (strprefix (p, p1, "core"))
6948 {
6949 ULONGEST c;
6950
6951 p = unpack_varlen_hex (++p1, &c);
6952 event->core = c;
6953 }
6954 else if (strprefix (p, p1, "fork"))
6955 {
6956 event->ws.value.related_pid = read_ptid (++p1, &p);
6957 event->ws.kind = TARGET_WAITKIND_FORKED;
6958 }
6959 else if (strprefix (p, p1, "vfork"))
6960 {
6961 event->ws.value.related_pid = read_ptid (++p1, &p);
6962 event->ws.kind = TARGET_WAITKIND_VFORKED;
6963 }
6964 else if (strprefix (p, p1, "vforkdone"))
6965 {
6966 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6967 p = strchrnul (p1 + 1, ';');
6968 }
6969 else if (strprefix (p, p1, "exec"))
6970 {
6971 ULONGEST ignored;
6972 char pathname[PATH_MAX];
6973 int pathlen;
6974
6975 /* Determine the length of the execd pathname. */
6976 p = unpack_varlen_hex (++p1, &ignored);
6977 pathlen = (p - p1) / 2;
6978
6979 /* Save the pathname for event reporting and for
6980 the next run command. */
6981 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6982 pathname[pathlen] = '\0';
6983
6984 /* This is freed during event handling. */
6985 event->ws.value.execd_pathname = xstrdup (pathname);
6986 event->ws.kind = TARGET_WAITKIND_EXECD;
6987
6988 /* Skip the registers included in this packet, since
6989 they may be for an architecture different from the
6990 one used by the original program. */
6991 skipregs = 1;
6992 }
6993 else if (strprefix (p, p1, "create"))
6994 {
6995 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6996 p = strchrnul (p1 + 1, ';');
6997 }
6998 else
6999 {
7000 ULONGEST pnum;
7001 char *p_temp;
7002
7003 if (skipregs)
7004 {
7005 p = strchrnul (p1 + 1, ';');
7006 p++;
7007 continue;
7008 }
7009
7010 /* Maybe a real ``P'' register number. */
7011 p_temp = unpack_varlen_hex (p, &pnum);
7012 /* If the first invalid character is the colon, we got a
7013 register number. Otherwise, it's an unknown stop
7014 reason. */
7015 if (p_temp == p1)
7016 {
7017 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
7018 cached_reg_t cached_reg;
7019 struct gdbarch *gdbarch = target_gdbarch ();
7020
7021 if (reg == NULL)
7022 error (_("Remote sent bad register number %s: %s\n\
7023 Packet: '%s'\n"),
7024 hex_string (pnum), p, buf);
7025
7026 cached_reg.num = reg->regnum;
7027 cached_reg.data = (gdb_byte *)
7028 xmalloc (register_size (gdbarch, reg->regnum));
7029
7030 p = p1 + 1;
7031 fieldsize = hex2bin (p, cached_reg.data,
7032 register_size (gdbarch, reg->regnum));
7033 p += 2 * fieldsize;
7034 if (fieldsize < register_size (gdbarch, reg->regnum))
7035 warning (_("Remote reply is too short: %s"), buf);
7036
7037 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7038 }
7039 else
7040 {
7041 /* Not a number. Silently skip unknown optional
7042 info. */
7043 p = strchrnul (p1 + 1, ';');
7044 }
7045 }
7046
7047 if (*p != ';')
7048 error (_("Remote register badly formatted: %s\nhere: %s"),
7049 buf, p);
7050 ++p;
7051 }
7052
7053 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7054 break;
7055
7056 /* fall through */
7057 case 'S': /* Old style status, just signal only. */
7058 {
7059 int sig;
7060
7061 event->ws.kind = TARGET_WAITKIND_STOPPED;
7062 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7063 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7064 event->ws.value.sig = (enum gdb_signal) sig;
7065 else
7066 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7067 }
7068 break;
7069 case 'w': /* Thread exited. */
7070 {
7071 char *p;
7072 ULONGEST value;
7073
7074 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7075 p = unpack_varlen_hex (&buf[1], &value);
7076 event->ws.value.integer = value;
7077 if (*p != ';')
7078 error (_("stop reply packet badly formatted: %s"), buf);
7079 event->ptid = read_ptid (++p, NULL);
7080 break;
7081 }
7082 case 'W': /* Target exited. */
7083 case 'X':
7084 {
7085 char *p;
7086 int pid;
7087 ULONGEST value;
7088
7089 /* GDB used to accept only 2 hex chars here. Stubs should
7090 only send more if they detect GDB supports multi-process
7091 support. */
7092 p = unpack_varlen_hex (&buf[1], &value);
7093
7094 if (buf[0] == 'W')
7095 {
7096 /* The remote process exited. */
7097 event->ws.kind = TARGET_WAITKIND_EXITED;
7098 event->ws.value.integer = value;
7099 }
7100 else
7101 {
7102 /* The remote process exited with a signal. */
7103 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7104 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7105 event->ws.value.sig = (enum gdb_signal) value;
7106 else
7107 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7108 }
7109
7110 /* If no process is specified, assume inferior_ptid. */
7111 pid = ptid_get_pid (inferior_ptid);
7112 if (*p == '\0')
7113 ;
7114 else if (*p == ';')
7115 {
7116 p++;
7117
7118 if (*p == '\0')
7119 ;
7120 else if (startswith (p, "process:"))
7121 {
7122 ULONGEST upid;
7123
7124 p += sizeof ("process:") - 1;
7125 unpack_varlen_hex (p, &upid);
7126 pid = upid;
7127 }
7128 else
7129 error (_("unknown stop reply packet: %s"), buf);
7130 }
7131 else
7132 error (_("unknown stop reply packet: %s"), buf);
7133 event->ptid = pid_to_ptid (pid);
7134 }
7135 break;
7136 case 'N':
7137 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7138 event->ptid = minus_one_ptid;
7139 break;
7140 }
7141
7142 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7143 error (_("No process or thread specified in stop reply: %s"), buf);
7144 }
7145
7146 /* When the stub wants to tell GDB about a new notification reply, it
7147 sends a notification (%Stop, for example). Those can come it at
7148 any time, hence, we have to make sure that any pending
7149 putpkt/getpkt sequence we're making is finished, before querying
7150 the stub for more events with the corresponding ack command
7151 (vStopped, for example). E.g., if we started a vStopped sequence
7152 immediately upon receiving the notification, something like this
7153 could happen:
7154
7155 1.1) --> Hg 1
7156 1.2) <-- OK
7157 1.3) --> g
7158 1.4) <-- %Stop
7159 1.5) --> vStopped
7160 1.6) <-- (registers reply to step #1.3)
7161
7162 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7163 query.
7164
7165 To solve this, whenever we parse a %Stop notification successfully,
7166 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7167 doing whatever we were doing:
7168
7169 2.1) --> Hg 1
7170 2.2) <-- OK
7171 2.3) --> g
7172 2.4) <-- %Stop
7173 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7174 2.5) <-- (registers reply to step #2.3)
7175
7176 Eventualy after step #2.5, we return to the event loop, which
7177 notices there's an event on the
7178 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7179 associated callback --- the function below. At this point, we're
7180 always safe to start a vStopped sequence. :
7181
7182 2.6) --> vStopped
7183 2.7) <-- T05 thread:2
7184 2.8) --> vStopped
7185 2.9) --> OK
7186 */
7187
7188 void
7189 remote_notif_get_pending_events (struct notif_client *nc)
7190 {
7191 struct remote_state *rs = get_remote_state ();
7192
7193 if (rs->notif_state->pending_event[nc->id] != NULL)
7194 {
7195 if (notif_debug)
7196 fprintf_unfiltered (gdb_stdlog,
7197 "notif: process: '%s' ack pending event\n",
7198 nc->name);
7199
7200 /* acknowledge */
7201 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7202 rs->notif_state->pending_event[nc->id] = NULL;
7203
7204 while (1)
7205 {
7206 getpkt (&rs->buf, &rs->buf_size, 0);
7207 if (strcmp (rs->buf, "OK") == 0)
7208 break;
7209 else
7210 remote_notif_ack (nc, rs->buf);
7211 }
7212 }
7213 else
7214 {
7215 if (notif_debug)
7216 fprintf_unfiltered (gdb_stdlog,
7217 "notif: process: '%s' no pending reply\n",
7218 nc->name);
7219 }
7220 }
7221
7222 /* Called when it is decided that STOP_REPLY holds the info of the
7223 event that is to be returned to the core. This function always
7224 destroys STOP_REPLY. */
7225
7226 static ptid_t
7227 process_stop_reply (struct stop_reply *stop_reply,
7228 struct target_waitstatus *status)
7229 {
7230 ptid_t ptid;
7231
7232 *status = stop_reply->ws;
7233 ptid = stop_reply->ptid;
7234
7235 /* If no thread/process was reported by the stub, assume the current
7236 inferior. */
7237 if (ptid_equal (ptid, null_ptid))
7238 ptid = inferior_ptid;
7239
7240 if (status->kind != TARGET_WAITKIND_EXITED
7241 && status->kind != TARGET_WAITKIND_SIGNALLED
7242 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7243 {
7244 struct private_thread_info *remote_thr;
7245
7246 /* Expedited registers. */
7247 if (stop_reply->regcache)
7248 {
7249 struct regcache *regcache
7250 = get_thread_arch_regcache (ptid, target_gdbarch ());
7251 cached_reg_t *reg;
7252 int ix;
7253
7254 for (ix = 0;
7255 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7256 ix++)
7257 {
7258 regcache_raw_supply (regcache, reg->num, reg->data);
7259 xfree (reg->data);
7260 }
7261
7262 VEC_free (cached_reg_t, stop_reply->regcache);
7263 }
7264
7265 remote_notice_new_inferior (ptid, 0);
7266 remote_thr = get_private_info_ptid (ptid);
7267 remote_thr->core = stop_reply->core;
7268 remote_thr->stop_reason = stop_reply->stop_reason;
7269 remote_thr->watch_data_address = stop_reply->watch_data_address;
7270 remote_thr->vcont_resumed = 0;
7271 }
7272
7273 stop_reply_xfree (stop_reply);
7274 return ptid;
7275 }
7276
7277 /* The non-stop mode version of target_wait. */
7278
7279 static ptid_t
7280 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7281 {
7282 struct remote_state *rs = get_remote_state ();
7283 struct stop_reply *stop_reply;
7284 int ret;
7285 int is_notif = 0;
7286
7287 /* If in non-stop mode, get out of getpkt even if a
7288 notification is received. */
7289
7290 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7291 0 /* forever */, &is_notif);
7292 while (1)
7293 {
7294 if (ret != -1 && !is_notif)
7295 switch (rs->buf[0])
7296 {
7297 case 'E': /* Error of some sort. */
7298 /* We're out of sync with the target now. Did it continue
7299 or not? We can't tell which thread it was in non-stop,
7300 so just ignore this. */
7301 warning (_("Remote failure reply: %s"), rs->buf);
7302 break;
7303 case 'O': /* Console output. */
7304 remote_console_output (rs->buf + 1);
7305 break;
7306 default:
7307 warning (_("Invalid remote reply: %s"), rs->buf);
7308 break;
7309 }
7310
7311 /* Acknowledge a pending stop reply that may have arrived in the
7312 mean time. */
7313 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7314 remote_notif_get_pending_events (&notif_client_stop);
7315
7316 /* If indeed we noticed a stop reply, we're done. */
7317 stop_reply = queued_stop_reply (ptid);
7318 if (stop_reply != NULL)
7319 return process_stop_reply (stop_reply, status);
7320
7321 /* Still no event. If we're just polling for an event, then
7322 return to the event loop. */
7323 if (options & TARGET_WNOHANG)
7324 {
7325 status->kind = TARGET_WAITKIND_IGNORE;
7326 return minus_one_ptid;
7327 }
7328
7329 /* Otherwise do a blocking wait. */
7330 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7331 1 /* forever */, &is_notif);
7332 }
7333 }
7334
7335 /* Wait until the remote machine stops, then return, storing status in
7336 STATUS just as `wait' would. */
7337
7338 static ptid_t
7339 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7340 {
7341 struct remote_state *rs = get_remote_state ();
7342 ptid_t event_ptid = null_ptid;
7343 char *buf;
7344 struct stop_reply *stop_reply;
7345
7346 again:
7347
7348 status->kind = TARGET_WAITKIND_IGNORE;
7349 status->value.integer = 0;
7350
7351 stop_reply = queued_stop_reply (ptid);
7352 if (stop_reply != NULL)
7353 return process_stop_reply (stop_reply, status);
7354
7355 if (rs->cached_wait_status)
7356 /* Use the cached wait status, but only once. */
7357 rs->cached_wait_status = 0;
7358 else
7359 {
7360 int ret;
7361 int is_notif;
7362 int forever = ((options & TARGET_WNOHANG) == 0
7363 && wait_forever_enabled_p);
7364
7365 if (!rs->waiting_for_stop_reply)
7366 {
7367 status->kind = TARGET_WAITKIND_NO_RESUMED;
7368 return minus_one_ptid;
7369 }
7370
7371 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7372 _never_ wait for ever -> test on target_is_async_p().
7373 However, before we do that we need to ensure that the caller
7374 knows how to take the target into/out of async mode. */
7375 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7376 forever, &is_notif);
7377
7378 /* GDB gets a notification. Return to core as this event is
7379 not interesting. */
7380 if (ret != -1 && is_notif)
7381 return minus_one_ptid;
7382
7383 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7384 return minus_one_ptid;
7385 }
7386
7387 buf = rs->buf;
7388
7389 /* Assume that the target has acknowledged Ctrl-C unless we receive
7390 an 'F' or 'O' packet. */
7391 if (buf[0] != 'F' && buf[0] != 'O')
7392 rs->ctrlc_pending_p = 0;
7393
7394 switch (buf[0])
7395 {
7396 case 'E': /* Error of some sort. */
7397 /* We're out of sync with the target now. Did it continue or
7398 not? Not is more likely, so report a stop. */
7399 rs->waiting_for_stop_reply = 0;
7400
7401 warning (_("Remote failure reply: %s"), buf);
7402 status->kind = TARGET_WAITKIND_STOPPED;
7403 status->value.sig = GDB_SIGNAL_0;
7404 break;
7405 case 'F': /* File-I/O request. */
7406 /* GDB may access the inferior memory while handling the File-I/O
7407 request, but we don't want GDB accessing memory while waiting
7408 for a stop reply. See the comments in putpkt_binary. Set
7409 waiting_for_stop_reply to 0 temporarily. */
7410 rs->waiting_for_stop_reply = 0;
7411 remote_fileio_request (buf, rs->ctrlc_pending_p);
7412 rs->ctrlc_pending_p = 0;
7413 /* GDB handled the File-I/O request, and the target is running
7414 again. Keep waiting for events. */
7415 rs->waiting_for_stop_reply = 1;
7416 break;
7417 case 'N': case 'T': case 'S': case 'X': case 'W':
7418 {
7419 struct stop_reply *stop_reply;
7420
7421 /* There is a stop reply to handle. */
7422 rs->waiting_for_stop_reply = 0;
7423
7424 stop_reply
7425 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7426 rs->buf);
7427
7428 event_ptid = process_stop_reply (stop_reply, status);
7429 break;
7430 }
7431 case 'O': /* Console output. */
7432 remote_console_output (buf + 1);
7433 break;
7434 case '\0':
7435 if (rs->last_sent_signal != GDB_SIGNAL_0)
7436 {
7437 /* Zero length reply means that we tried 'S' or 'C' and the
7438 remote system doesn't support it. */
7439 target_terminal::ours_for_output ();
7440 printf_filtered
7441 ("Can't send signals to this remote system. %s not sent.\n",
7442 gdb_signal_to_name (rs->last_sent_signal));
7443 rs->last_sent_signal = GDB_SIGNAL_0;
7444 target_terminal::inferior ();
7445
7446 strcpy (buf, rs->last_sent_step ? "s" : "c");
7447 putpkt (buf);
7448 break;
7449 }
7450 /* else fallthrough */
7451 default:
7452 warning (_("Invalid remote reply: %s"), buf);
7453 break;
7454 }
7455
7456 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7457 return minus_one_ptid;
7458 else if (status->kind == TARGET_WAITKIND_IGNORE)
7459 {
7460 /* Nothing interesting happened. If we're doing a non-blocking
7461 poll, we're done. Otherwise, go back to waiting. */
7462 if (options & TARGET_WNOHANG)
7463 return minus_one_ptid;
7464 else
7465 goto again;
7466 }
7467 else if (status->kind != TARGET_WAITKIND_EXITED
7468 && status->kind != TARGET_WAITKIND_SIGNALLED)
7469 {
7470 if (!ptid_equal (event_ptid, null_ptid))
7471 record_currthread (rs, event_ptid);
7472 else
7473 event_ptid = inferior_ptid;
7474 }
7475 else
7476 /* A process exit. Invalidate our notion of current thread. */
7477 record_currthread (rs, minus_one_ptid);
7478
7479 return event_ptid;
7480 }
7481
7482 /* Wait until the remote machine stops, then return, storing status in
7483 STATUS just as `wait' would. */
7484
7485 static ptid_t
7486 remote_wait (struct target_ops *ops,
7487 ptid_t ptid, struct target_waitstatus *status, int options)
7488 {
7489 ptid_t event_ptid;
7490
7491 if (target_is_non_stop_p ())
7492 event_ptid = remote_wait_ns (ptid, status, options);
7493 else
7494 event_ptid = remote_wait_as (ptid, status, options);
7495
7496 if (target_is_async_p ())
7497 {
7498 /* If there are are events left in the queue tell the event loop
7499 to return here. */
7500 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7501 mark_async_event_handler (remote_async_inferior_event_token);
7502 }
7503
7504 return event_ptid;
7505 }
7506
7507 /* Fetch a single register using a 'p' packet. */
7508
7509 static int
7510 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7511 {
7512 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7513 struct remote_state *rs = get_remote_state ();
7514 char *buf, *p;
7515 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7516 int i;
7517
7518 if (packet_support (PACKET_p) == PACKET_DISABLE)
7519 return 0;
7520
7521 if (reg->pnum == -1)
7522 return 0;
7523
7524 p = rs->buf;
7525 *p++ = 'p';
7526 p += hexnumstr (p, reg->pnum);
7527 *p++ = '\0';
7528 putpkt (rs->buf);
7529 getpkt (&rs->buf, &rs->buf_size, 0);
7530
7531 buf = rs->buf;
7532
7533 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7534 {
7535 case PACKET_OK:
7536 break;
7537 case PACKET_UNKNOWN:
7538 return 0;
7539 case PACKET_ERROR:
7540 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7541 gdbarch_register_name (get_regcache_arch (regcache),
7542 reg->regnum),
7543 buf);
7544 }
7545
7546 /* If this register is unfetchable, tell the regcache. */
7547 if (buf[0] == 'x')
7548 {
7549 regcache_raw_supply (regcache, reg->regnum, NULL);
7550 return 1;
7551 }
7552
7553 /* Otherwise, parse and supply the value. */
7554 p = buf;
7555 i = 0;
7556 while (p[0] != 0)
7557 {
7558 if (p[1] == 0)
7559 error (_("fetch_register_using_p: early buf termination"));
7560
7561 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7562 p += 2;
7563 }
7564 regcache_raw_supply (regcache, reg->regnum, regp);
7565 return 1;
7566 }
7567
7568 /* Fetch the registers included in the target's 'g' packet. */
7569
7570 static int
7571 send_g_packet (void)
7572 {
7573 struct remote_state *rs = get_remote_state ();
7574 int buf_len;
7575
7576 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7577 remote_send (&rs->buf, &rs->buf_size);
7578
7579 /* We can get out of synch in various cases. If the first character
7580 in the buffer is not a hex character, assume that has happened
7581 and try to fetch another packet to read. */
7582 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7583 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7584 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7585 && rs->buf[0] != 'x') /* New: unavailable register value. */
7586 {
7587 if (remote_debug)
7588 fprintf_unfiltered (gdb_stdlog,
7589 "Bad register packet; fetching a new packet\n");
7590 getpkt (&rs->buf, &rs->buf_size, 0);
7591 }
7592
7593 buf_len = strlen (rs->buf);
7594
7595 /* Sanity check the received packet. */
7596 if (buf_len % 2 != 0)
7597 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7598
7599 return buf_len / 2;
7600 }
7601
7602 static void
7603 process_g_packet (struct regcache *regcache)
7604 {
7605 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7606 struct remote_state *rs = get_remote_state ();
7607 struct remote_arch_state *rsa = get_remote_arch_state ();
7608 int i, buf_len;
7609 char *p;
7610 char *regs;
7611
7612 buf_len = strlen (rs->buf);
7613
7614 /* Further sanity checks, with knowledge of the architecture. */
7615 if (buf_len > 2 * rsa->sizeof_g_packet)
7616 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7617 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7618
7619 /* Save the size of the packet sent to us by the target. It is used
7620 as a heuristic when determining the max size of packets that the
7621 target can safely receive. */
7622 if (rsa->actual_register_packet_size == 0)
7623 rsa->actual_register_packet_size = buf_len;
7624
7625 /* If this is smaller than we guessed the 'g' packet would be,
7626 update our records. A 'g' reply that doesn't include a register's
7627 value implies either that the register is not available, or that
7628 the 'p' packet must be used. */
7629 if (buf_len < 2 * rsa->sizeof_g_packet)
7630 {
7631 long sizeof_g_packet = buf_len / 2;
7632
7633 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7634 {
7635 long offset = rsa->regs[i].offset;
7636 long reg_size = register_size (gdbarch, i);
7637
7638 if (rsa->regs[i].pnum == -1)
7639 continue;
7640
7641 if (offset >= sizeof_g_packet)
7642 rsa->regs[i].in_g_packet = 0;
7643 else if (offset + reg_size > sizeof_g_packet)
7644 error (_("Truncated register %d in remote 'g' packet"), i);
7645 else
7646 rsa->regs[i].in_g_packet = 1;
7647 }
7648
7649 /* Looks valid enough, we can assume this is the correct length
7650 for a 'g' packet. It's important not to adjust
7651 rsa->sizeof_g_packet if we have truncated registers otherwise
7652 this "if" won't be run the next time the method is called
7653 with a packet of the same size and one of the internal errors
7654 below will trigger instead. */
7655 rsa->sizeof_g_packet = sizeof_g_packet;
7656 }
7657
7658 regs = (char *) alloca (rsa->sizeof_g_packet);
7659
7660 /* Unimplemented registers read as all bits zero. */
7661 memset (regs, 0, rsa->sizeof_g_packet);
7662
7663 /* Reply describes registers byte by byte, each byte encoded as two
7664 hex characters. Suck them all up, then supply them to the
7665 register cacheing/storage mechanism. */
7666
7667 p = rs->buf;
7668 for (i = 0; i < rsa->sizeof_g_packet; i++)
7669 {
7670 if (p[0] == 0 || p[1] == 0)
7671 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7672 internal_error (__FILE__, __LINE__,
7673 _("unexpected end of 'g' packet reply"));
7674
7675 if (p[0] == 'x' && p[1] == 'x')
7676 regs[i] = 0; /* 'x' */
7677 else
7678 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7679 p += 2;
7680 }
7681
7682 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7683 {
7684 struct packet_reg *r = &rsa->regs[i];
7685 long reg_size = register_size (gdbarch, i);
7686
7687 if (r->in_g_packet)
7688 {
7689 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7690 /* This shouldn't happen - we adjusted in_g_packet above. */
7691 internal_error (__FILE__, __LINE__,
7692 _("unexpected end of 'g' packet reply"));
7693 else if (rs->buf[r->offset * 2] == 'x')
7694 {
7695 gdb_assert (r->offset * 2 < strlen (rs->buf));
7696 /* The register isn't available, mark it as such (at
7697 the same time setting the value to zero). */
7698 regcache_raw_supply (regcache, r->regnum, NULL);
7699 }
7700 else
7701 regcache_raw_supply (regcache, r->regnum,
7702 regs + r->offset);
7703 }
7704 }
7705 }
7706
7707 static void
7708 fetch_registers_using_g (struct regcache *regcache)
7709 {
7710 send_g_packet ();
7711 process_g_packet (regcache);
7712 }
7713
7714 /* Make the remote selected traceframe match GDB's selected
7715 traceframe. */
7716
7717 static void
7718 set_remote_traceframe (void)
7719 {
7720 int newnum;
7721 struct remote_state *rs = get_remote_state ();
7722
7723 if (rs->remote_traceframe_number == get_traceframe_number ())
7724 return;
7725
7726 /* Avoid recursion, remote_trace_find calls us again. */
7727 rs->remote_traceframe_number = get_traceframe_number ();
7728
7729 newnum = target_trace_find (tfind_number,
7730 get_traceframe_number (), 0, 0, NULL);
7731
7732 /* Should not happen. If it does, all bets are off. */
7733 if (newnum != get_traceframe_number ())
7734 warning (_("could not set remote traceframe"));
7735 }
7736
7737 static void
7738 remote_fetch_registers (struct target_ops *ops,
7739 struct regcache *regcache, int regnum)
7740 {
7741 struct remote_arch_state *rsa = get_remote_arch_state ();
7742 int i;
7743
7744 set_remote_traceframe ();
7745 set_general_thread (regcache_get_ptid (regcache));
7746
7747 if (regnum >= 0)
7748 {
7749 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7750
7751 gdb_assert (reg != NULL);
7752
7753 /* If this register might be in the 'g' packet, try that first -
7754 we are likely to read more than one register. If this is the
7755 first 'g' packet, we might be overly optimistic about its
7756 contents, so fall back to 'p'. */
7757 if (reg->in_g_packet)
7758 {
7759 fetch_registers_using_g (regcache);
7760 if (reg->in_g_packet)
7761 return;
7762 }
7763
7764 if (fetch_register_using_p (regcache, reg))
7765 return;
7766
7767 /* This register is not available. */
7768 regcache_raw_supply (regcache, reg->regnum, NULL);
7769
7770 return;
7771 }
7772
7773 fetch_registers_using_g (regcache);
7774
7775 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7776 if (!rsa->regs[i].in_g_packet)
7777 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7778 {
7779 /* This register is not available. */
7780 regcache_raw_supply (regcache, i, NULL);
7781 }
7782 }
7783
7784 /* Prepare to store registers. Since we may send them all (using a
7785 'G' request), we have to read out the ones we don't want to change
7786 first. */
7787
7788 static void
7789 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7790 {
7791 struct remote_arch_state *rsa = get_remote_arch_state ();
7792 int i;
7793
7794 /* Make sure the entire registers array is valid. */
7795 switch (packet_support (PACKET_P))
7796 {
7797 case PACKET_DISABLE:
7798 case PACKET_SUPPORT_UNKNOWN:
7799 /* Make sure all the necessary registers are cached. */
7800 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7801 if (rsa->regs[i].in_g_packet)
7802 regcache_raw_update (regcache, rsa->regs[i].regnum);
7803 break;
7804 case PACKET_ENABLE:
7805 break;
7806 }
7807 }
7808
7809 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7810 packet was not recognized. */
7811
7812 static int
7813 store_register_using_P (const struct regcache *regcache,
7814 struct packet_reg *reg)
7815 {
7816 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7817 struct remote_state *rs = get_remote_state ();
7818 /* Try storing a single register. */
7819 char *buf = rs->buf;
7820 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7821 char *p;
7822
7823 if (packet_support (PACKET_P) == PACKET_DISABLE)
7824 return 0;
7825
7826 if (reg->pnum == -1)
7827 return 0;
7828
7829 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7830 p = buf + strlen (buf);
7831 regcache_raw_collect (regcache, reg->regnum, regp);
7832 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7833 putpkt (rs->buf);
7834 getpkt (&rs->buf, &rs->buf_size, 0);
7835
7836 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7837 {
7838 case PACKET_OK:
7839 return 1;
7840 case PACKET_ERROR:
7841 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7842 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7843 case PACKET_UNKNOWN:
7844 return 0;
7845 default:
7846 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7847 }
7848 }
7849
7850 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7851 contents of the register cache buffer. FIXME: ignores errors. */
7852
7853 static void
7854 store_registers_using_G (const struct regcache *regcache)
7855 {
7856 struct remote_state *rs = get_remote_state ();
7857 struct remote_arch_state *rsa = get_remote_arch_state ();
7858 gdb_byte *regs;
7859 char *p;
7860
7861 /* Extract all the registers in the regcache copying them into a
7862 local buffer. */
7863 {
7864 int i;
7865
7866 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7867 memset (regs, 0, rsa->sizeof_g_packet);
7868 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7869 {
7870 struct packet_reg *r = &rsa->regs[i];
7871
7872 if (r->in_g_packet)
7873 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7874 }
7875 }
7876
7877 /* Command describes registers byte by byte,
7878 each byte encoded as two hex characters. */
7879 p = rs->buf;
7880 *p++ = 'G';
7881 bin2hex (regs, p, rsa->sizeof_g_packet);
7882 putpkt (rs->buf);
7883 getpkt (&rs->buf, &rs->buf_size, 0);
7884 if (packet_check_result (rs->buf) == PACKET_ERROR)
7885 error (_("Could not write registers; remote failure reply '%s'"),
7886 rs->buf);
7887 }
7888
7889 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7890 of the register cache buffer. FIXME: ignores errors. */
7891
7892 static void
7893 remote_store_registers (struct target_ops *ops,
7894 struct regcache *regcache, int regnum)
7895 {
7896 struct remote_arch_state *rsa = get_remote_arch_state ();
7897 int i;
7898
7899 set_remote_traceframe ();
7900 set_general_thread (regcache_get_ptid (regcache));
7901
7902 if (regnum >= 0)
7903 {
7904 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7905
7906 gdb_assert (reg != NULL);
7907
7908 /* Always prefer to store registers using the 'P' packet if
7909 possible; we often change only a small number of registers.
7910 Sometimes we change a larger number; we'd need help from a
7911 higher layer to know to use 'G'. */
7912 if (store_register_using_P (regcache, reg))
7913 return;
7914
7915 /* For now, don't complain if we have no way to write the
7916 register. GDB loses track of unavailable registers too
7917 easily. Some day, this may be an error. We don't have
7918 any way to read the register, either... */
7919 if (!reg->in_g_packet)
7920 return;
7921
7922 store_registers_using_G (regcache);
7923 return;
7924 }
7925
7926 store_registers_using_G (regcache);
7927
7928 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7929 if (!rsa->regs[i].in_g_packet)
7930 if (!store_register_using_P (regcache, &rsa->regs[i]))
7931 /* See above for why we do not issue an error here. */
7932 continue;
7933 }
7934 \f
7935
7936 /* Return the number of hex digits in num. */
7937
7938 static int
7939 hexnumlen (ULONGEST num)
7940 {
7941 int i;
7942
7943 for (i = 0; num != 0; i++)
7944 num >>= 4;
7945
7946 return std::max (i, 1);
7947 }
7948
7949 /* Set BUF to the minimum number of hex digits representing NUM. */
7950
7951 static int
7952 hexnumstr (char *buf, ULONGEST num)
7953 {
7954 int len = hexnumlen (num);
7955
7956 return hexnumnstr (buf, num, len);
7957 }
7958
7959
7960 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7961
7962 static int
7963 hexnumnstr (char *buf, ULONGEST num, int width)
7964 {
7965 int i;
7966
7967 buf[width] = '\0';
7968
7969 for (i = width - 1; i >= 0; i--)
7970 {
7971 buf[i] = "0123456789abcdef"[(num & 0xf)];
7972 num >>= 4;
7973 }
7974
7975 return width;
7976 }
7977
7978 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7979
7980 static CORE_ADDR
7981 remote_address_masked (CORE_ADDR addr)
7982 {
7983 unsigned int address_size = remote_address_size;
7984
7985 /* If "remoteaddresssize" was not set, default to target address size. */
7986 if (!address_size)
7987 address_size = gdbarch_addr_bit (target_gdbarch ());
7988
7989 if (address_size > 0
7990 && address_size < (sizeof (ULONGEST) * 8))
7991 {
7992 /* Only create a mask when that mask can safely be constructed
7993 in a ULONGEST variable. */
7994 ULONGEST mask = 1;
7995
7996 mask = (mask << address_size) - 1;
7997 addr &= mask;
7998 }
7999 return addr;
8000 }
8001
8002 /* Determine whether the remote target supports binary downloading.
8003 This is accomplished by sending a no-op memory write of zero length
8004 to the target at the specified address. It does not suffice to send
8005 the whole packet, since many stubs strip the eighth bit and
8006 subsequently compute a wrong checksum, which causes real havoc with
8007 remote_write_bytes.
8008
8009 NOTE: This can still lose if the serial line is not eight-bit
8010 clean. In cases like this, the user should clear "remote
8011 X-packet". */
8012
8013 static void
8014 check_binary_download (CORE_ADDR addr)
8015 {
8016 struct remote_state *rs = get_remote_state ();
8017
8018 switch (packet_support (PACKET_X))
8019 {
8020 case PACKET_DISABLE:
8021 break;
8022 case PACKET_ENABLE:
8023 break;
8024 case PACKET_SUPPORT_UNKNOWN:
8025 {
8026 char *p;
8027
8028 p = rs->buf;
8029 *p++ = 'X';
8030 p += hexnumstr (p, (ULONGEST) addr);
8031 *p++ = ',';
8032 p += hexnumstr (p, (ULONGEST) 0);
8033 *p++ = ':';
8034 *p = '\0';
8035
8036 putpkt_binary (rs->buf, (int) (p - rs->buf));
8037 getpkt (&rs->buf, &rs->buf_size, 0);
8038
8039 if (rs->buf[0] == '\0')
8040 {
8041 if (remote_debug)
8042 fprintf_unfiltered (gdb_stdlog,
8043 "binary downloading NOT "
8044 "supported by target\n");
8045 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8046 }
8047 else
8048 {
8049 if (remote_debug)
8050 fprintf_unfiltered (gdb_stdlog,
8051 "binary downloading supported by target\n");
8052 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8053 }
8054 break;
8055 }
8056 }
8057 }
8058
8059 /* Helper function to resize the payload in order to try to get a good
8060 alignment. We try to write an amount of data such that the next write will
8061 start on an address aligned on REMOTE_ALIGN_WRITES. */
8062
8063 static int
8064 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8065 {
8066 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8067 }
8068
8069 /* Write memory data directly to the remote machine.
8070 This does not inform the data cache; the data cache uses this.
8071 HEADER is the starting part of the packet.
8072 MEMADDR is the address in the remote memory space.
8073 MYADDR is the address of the buffer in our space.
8074 LEN_UNITS is the number of addressable units to write.
8075 UNIT_SIZE is the length in bytes of an addressable unit.
8076 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8077 should send data as binary ('X'), or hex-encoded ('M').
8078
8079 The function creates packet of the form
8080 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8081
8082 where encoding of <DATA> is terminated by PACKET_FORMAT.
8083
8084 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8085 are omitted.
8086
8087 Return the transferred status, error or OK (an
8088 'enum target_xfer_status' value). Save the number of addressable units
8089 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8090
8091 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8092 exchange between gdb and the stub could look like (?? in place of the
8093 checksum):
8094
8095 -> $m1000,4#??
8096 <- aaaabbbbccccdddd
8097
8098 -> $M1000,3:eeeeffffeeee#??
8099 <- OK
8100
8101 -> $m1000,4#??
8102 <- eeeeffffeeeedddd */
8103
8104 static enum target_xfer_status
8105 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8106 const gdb_byte *myaddr, ULONGEST len_units,
8107 int unit_size, ULONGEST *xfered_len_units,
8108 char packet_format, int use_length)
8109 {
8110 struct remote_state *rs = get_remote_state ();
8111 char *p;
8112 char *plen = NULL;
8113 int plenlen = 0;
8114 int todo_units;
8115 int units_written;
8116 int payload_capacity_bytes;
8117 int payload_length_bytes;
8118
8119 if (packet_format != 'X' && packet_format != 'M')
8120 internal_error (__FILE__, __LINE__,
8121 _("remote_write_bytes_aux: bad packet format"));
8122
8123 if (len_units == 0)
8124 return TARGET_XFER_EOF;
8125
8126 payload_capacity_bytes = get_memory_write_packet_size ();
8127
8128 /* The packet buffer will be large enough for the payload;
8129 get_memory_packet_size ensures this. */
8130 rs->buf[0] = '\0';
8131
8132 /* Compute the size of the actual payload by subtracting out the
8133 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8134
8135 payload_capacity_bytes -= strlen ("$,:#NN");
8136 if (!use_length)
8137 /* The comma won't be used. */
8138 payload_capacity_bytes += 1;
8139 payload_capacity_bytes -= strlen (header);
8140 payload_capacity_bytes -= hexnumlen (memaddr);
8141
8142 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8143
8144 strcat (rs->buf, header);
8145 p = rs->buf + strlen (header);
8146
8147 /* Compute a best guess of the number of bytes actually transfered. */
8148 if (packet_format == 'X')
8149 {
8150 /* Best guess at number of bytes that will fit. */
8151 todo_units = std::min (len_units,
8152 (ULONGEST) payload_capacity_bytes / unit_size);
8153 if (use_length)
8154 payload_capacity_bytes -= hexnumlen (todo_units);
8155 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8156 }
8157 else
8158 {
8159 /* Number of bytes that will fit. */
8160 todo_units
8161 = std::min (len_units,
8162 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8163 if (use_length)
8164 payload_capacity_bytes -= hexnumlen (todo_units);
8165 todo_units = std::min (todo_units,
8166 (payload_capacity_bytes / unit_size) / 2);
8167 }
8168
8169 if (todo_units <= 0)
8170 internal_error (__FILE__, __LINE__,
8171 _("minimum packet size too small to write data"));
8172
8173 /* If we already need another packet, then try to align the end
8174 of this packet to a useful boundary. */
8175 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8176 todo_units = align_for_efficient_write (todo_units, memaddr);
8177
8178 /* Append "<memaddr>". */
8179 memaddr = remote_address_masked (memaddr);
8180 p += hexnumstr (p, (ULONGEST) memaddr);
8181
8182 if (use_length)
8183 {
8184 /* Append ",". */
8185 *p++ = ',';
8186
8187 /* Append the length and retain its location and size. It may need to be
8188 adjusted once the packet body has been created. */
8189 plen = p;
8190 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8191 p += plenlen;
8192 }
8193
8194 /* Append ":". */
8195 *p++ = ':';
8196 *p = '\0';
8197
8198 /* Append the packet body. */
8199 if (packet_format == 'X')
8200 {
8201 /* Binary mode. Send target system values byte by byte, in
8202 increasing byte addresses. Only escape certain critical
8203 characters. */
8204 payload_length_bytes =
8205 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8206 &units_written, payload_capacity_bytes);
8207
8208 /* If not all TODO units fit, then we'll need another packet. Make
8209 a second try to keep the end of the packet aligned. Don't do
8210 this if the packet is tiny. */
8211 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8212 {
8213 int new_todo_units;
8214
8215 new_todo_units = align_for_efficient_write (units_written, memaddr);
8216
8217 if (new_todo_units != units_written)
8218 payload_length_bytes =
8219 remote_escape_output (myaddr, new_todo_units, unit_size,
8220 (gdb_byte *) p, &units_written,
8221 payload_capacity_bytes);
8222 }
8223
8224 p += payload_length_bytes;
8225 if (use_length && units_written < todo_units)
8226 {
8227 /* Escape chars have filled up the buffer prematurely,
8228 and we have actually sent fewer units than planned.
8229 Fix-up the length field of the packet. Use the same
8230 number of characters as before. */
8231 plen += hexnumnstr (plen, (ULONGEST) units_written,
8232 plenlen);
8233 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8234 }
8235 }
8236 else
8237 {
8238 /* Normal mode: Send target system values byte by byte, in
8239 increasing byte addresses. Each byte is encoded as a two hex
8240 value. */
8241 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8242 units_written = todo_units;
8243 }
8244
8245 putpkt_binary (rs->buf, (int) (p - rs->buf));
8246 getpkt (&rs->buf, &rs->buf_size, 0);
8247
8248 if (rs->buf[0] == 'E')
8249 return TARGET_XFER_E_IO;
8250
8251 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8252 send fewer units than we'd planned. */
8253 *xfered_len_units = (ULONGEST) units_written;
8254 return TARGET_XFER_OK;
8255 }
8256
8257 /* Write memory data directly to the remote machine.
8258 This does not inform the data cache; the data cache uses this.
8259 MEMADDR is the address in the remote memory space.
8260 MYADDR is the address of the buffer in our space.
8261 LEN is the number of bytes.
8262
8263 Return the transferred status, error or OK (an
8264 'enum target_xfer_status' value). Save the number of bytes
8265 transferred in *XFERED_LEN. Only transfer a single packet. */
8266
8267 static enum target_xfer_status
8268 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8269 int unit_size, ULONGEST *xfered_len)
8270 {
8271 const char *packet_format = NULL;
8272
8273 /* Check whether the target supports binary download. */
8274 check_binary_download (memaddr);
8275
8276 switch (packet_support (PACKET_X))
8277 {
8278 case PACKET_ENABLE:
8279 packet_format = "X";
8280 break;
8281 case PACKET_DISABLE:
8282 packet_format = "M";
8283 break;
8284 case PACKET_SUPPORT_UNKNOWN:
8285 internal_error (__FILE__, __LINE__,
8286 _("remote_write_bytes: bad internal state"));
8287 default:
8288 internal_error (__FILE__, __LINE__, _("bad switch"));
8289 }
8290
8291 return remote_write_bytes_aux (packet_format,
8292 memaddr, myaddr, len, unit_size, xfered_len,
8293 packet_format[0], 1);
8294 }
8295
8296 /* Read memory data directly from the remote machine.
8297 This does not use the data cache; the data cache uses this.
8298 MEMADDR is the address in the remote memory space.
8299 MYADDR is the address of the buffer in our space.
8300 LEN_UNITS is the number of addressable memory units to read..
8301 UNIT_SIZE is the length in bytes of an addressable unit.
8302
8303 Return the transferred status, error or OK (an
8304 'enum target_xfer_status' value). Save the number of bytes
8305 transferred in *XFERED_LEN_UNITS.
8306
8307 See the comment of remote_write_bytes_aux for an example of
8308 memory read/write exchange between gdb and the stub. */
8309
8310 static enum target_xfer_status
8311 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8312 int unit_size, ULONGEST *xfered_len_units)
8313 {
8314 struct remote_state *rs = get_remote_state ();
8315 int buf_size_bytes; /* Max size of packet output buffer. */
8316 char *p;
8317 int todo_units;
8318 int decoded_bytes;
8319
8320 buf_size_bytes = get_memory_read_packet_size ();
8321 /* The packet buffer will be large enough for the payload;
8322 get_memory_packet_size ensures this. */
8323
8324 /* Number of units that will fit. */
8325 todo_units = std::min (len_units,
8326 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8327
8328 /* Construct "m"<memaddr>","<len>". */
8329 memaddr = remote_address_masked (memaddr);
8330 p = rs->buf;
8331 *p++ = 'm';
8332 p += hexnumstr (p, (ULONGEST) memaddr);
8333 *p++ = ',';
8334 p += hexnumstr (p, (ULONGEST) todo_units);
8335 *p = '\0';
8336 putpkt (rs->buf);
8337 getpkt (&rs->buf, &rs->buf_size, 0);
8338 if (rs->buf[0] == 'E'
8339 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8340 && rs->buf[3] == '\0')
8341 return TARGET_XFER_E_IO;
8342 /* Reply describes memory byte by byte, each byte encoded as two hex
8343 characters. */
8344 p = rs->buf;
8345 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8346 /* Return what we have. Let higher layers handle partial reads. */
8347 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8348 return TARGET_XFER_OK;
8349 }
8350
8351 /* Using the set of read-only target sections of remote, read live
8352 read-only memory.
8353
8354 For interface/parameters/return description see target.h,
8355 to_xfer_partial. */
8356
8357 static enum target_xfer_status
8358 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8359 ULONGEST memaddr, ULONGEST len,
8360 int unit_size, ULONGEST *xfered_len)
8361 {
8362 struct target_section *secp;
8363 struct target_section_table *table;
8364
8365 secp = target_section_by_addr (ops, memaddr);
8366 if (secp != NULL
8367 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8368 secp->the_bfd_section)
8369 & SEC_READONLY))
8370 {
8371 struct target_section *p;
8372 ULONGEST memend = memaddr + len;
8373
8374 table = target_get_section_table (ops);
8375
8376 for (p = table->sections; p < table->sections_end; p++)
8377 {
8378 if (memaddr >= p->addr)
8379 {
8380 if (memend <= p->endaddr)
8381 {
8382 /* Entire transfer is within this section. */
8383 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8384 xfered_len);
8385 }
8386 else if (memaddr >= p->endaddr)
8387 {
8388 /* This section ends before the transfer starts. */
8389 continue;
8390 }
8391 else
8392 {
8393 /* This section overlaps the transfer. Just do half. */
8394 len = p->endaddr - memaddr;
8395 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8396 xfered_len);
8397 }
8398 }
8399 }
8400 }
8401
8402 return TARGET_XFER_EOF;
8403 }
8404
8405 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8406 first if the requested memory is unavailable in traceframe.
8407 Otherwise, fall back to remote_read_bytes_1. */
8408
8409 static enum target_xfer_status
8410 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8411 gdb_byte *myaddr, ULONGEST len, int unit_size,
8412 ULONGEST *xfered_len)
8413 {
8414 if (len == 0)
8415 return TARGET_XFER_EOF;
8416
8417 if (get_traceframe_number () != -1)
8418 {
8419 VEC(mem_range_s) *available;
8420
8421 /* If we fail to get the set of available memory, then the
8422 target does not support querying traceframe info, and so we
8423 attempt reading from the traceframe anyway (assuming the
8424 target implements the old QTro packet then). */
8425 if (traceframe_available_memory (&available, memaddr, len))
8426 {
8427 struct cleanup *old_chain;
8428
8429 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8430
8431 if (VEC_empty (mem_range_s, available)
8432 || VEC_index (mem_range_s, available, 0)->start != memaddr)
8433 {
8434 enum target_xfer_status res;
8435
8436 /* Don't read into the traceframe's available
8437 memory. */
8438 if (!VEC_empty (mem_range_s, available))
8439 {
8440 LONGEST oldlen = len;
8441
8442 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8443 gdb_assert (len <= oldlen);
8444 }
8445
8446 do_cleanups (old_chain);
8447
8448 /* This goes through the topmost target again. */
8449 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8450 len, unit_size, xfered_len);
8451 if (res == TARGET_XFER_OK)
8452 return TARGET_XFER_OK;
8453 else
8454 {
8455 /* No use trying further, we know some memory starting
8456 at MEMADDR isn't available. */
8457 *xfered_len = len;
8458 return TARGET_XFER_UNAVAILABLE;
8459 }
8460 }
8461
8462 /* Don't try to read more than how much is available, in
8463 case the target implements the deprecated QTro packet to
8464 cater for older GDBs (the target's knowledge of read-only
8465 sections may be outdated by now). */
8466 len = VEC_index (mem_range_s, available, 0)->length;
8467
8468 do_cleanups (old_chain);
8469 }
8470 }
8471
8472 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8473 }
8474
8475 \f
8476
8477 /* Sends a packet with content determined by the printf format string
8478 FORMAT and the remaining arguments, then gets the reply. Returns
8479 whether the packet was a success, a failure, or unknown. */
8480
8481 static enum packet_result remote_send_printf (const char *format, ...)
8482 ATTRIBUTE_PRINTF (1, 2);
8483
8484 static enum packet_result
8485 remote_send_printf (const char *format, ...)
8486 {
8487 struct remote_state *rs = get_remote_state ();
8488 int max_size = get_remote_packet_size ();
8489 va_list ap;
8490
8491 va_start (ap, format);
8492
8493 rs->buf[0] = '\0';
8494 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8495 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8496
8497 if (putpkt (rs->buf) < 0)
8498 error (_("Communication problem with target."));
8499
8500 rs->buf[0] = '\0';
8501 getpkt (&rs->buf, &rs->buf_size, 0);
8502
8503 return packet_check_result (rs->buf);
8504 }
8505
8506 /* Flash writing can take quite some time. We'll set
8507 effectively infinite timeout for flash operations.
8508 In future, we'll need to decide on a better approach. */
8509 static const int remote_flash_timeout = 1000;
8510
8511 static void
8512 remote_flash_erase (struct target_ops *ops,
8513 ULONGEST address, LONGEST length)
8514 {
8515 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8516 enum packet_result ret;
8517 scoped_restore restore_timeout
8518 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8519
8520 ret = remote_send_printf ("vFlashErase:%s,%s",
8521 phex (address, addr_size),
8522 phex (length, 4));
8523 switch (ret)
8524 {
8525 case PACKET_UNKNOWN:
8526 error (_("Remote target does not support flash erase"));
8527 case PACKET_ERROR:
8528 error (_("Error erasing flash with vFlashErase packet"));
8529 default:
8530 break;
8531 }
8532 }
8533
8534 static enum target_xfer_status
8535 remote_flash_write (struct target_ops *ops, ULONGEST address,
8536 ULONGEST length, ULONGEST *xfered_len,
8537 const gdb_byte *data)
8538 {
8539 scoped_restore restore_timeout
8540 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8541 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8542 xfered_len,'X', 0);
8543 }
8544
8545 static void
8546 remote_flash_done (struct target_ops *ops)
8547 {
8548 int ret;
8549
8550 scoped_restore restore_timeout
8551 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8552
8553 ret = remote_send_printf ("vFlashDone");
8554
8555 switch (ret)
8556 {
8557 case PACKET_UNKNOWN:
8558 error (_("Remote target does not support vFlashDone"));
8559 case PACKET_ERROR:
8560 error (_("Error finishing flash operation"));
8561 default:
8562 break;
8563 }
8564 }
8565
8566 static void
8567 remote_files_info (struct target_ops *ignore)
8568 {
8569 puts_filtered ("Debugging a target over a serial line.\n");
8570 }
8571 \f
8572 /* Stuff for dealing with the packets which are part of this protocol.
8573 See comment at top of file for details. */
8574
8575 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8576 error to higher layers. Called when a serial error is detected.
8577 The exception message is STRING, followed by a colon and a blank,
8578 the system error message for errno at function entry and final dot
8579 for output compatibility with throw_perror_with_name. */
8580
8581 static void
8582 unpush_and_perror (const char *string)
8583 {
8584 int saved_errno = errno;
8585
8586 remote_unpush_target ();
8587 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8588 safe_strerror (saved_errno));
8589 }
8590
8591 /* Read a single character from the remote end. The current quit
8592 handler is overridden to avoid quitting in the middle of packet
8593 sequence, as that would break communication with the remote server.
8594 See remote_serial_quit_handler for more detail. */
8595
8596 static int
8597 readchar (int timeout)
8598 {
8599 int ch;
8600 struct remote_state *rs = get_remote_state ();
8601
8602 {
8603 scoped_restore restore_quit
8604 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8605
8606 rs->got_ctrlc_during_io = 0;
8607
8608 ch = serial_readchar (rs->remote_desc, timeout);
8609
8610 if (rs->got_ctrlc_during_io)
8611 set_quit_flag ();
8612 }
8613
8614 if (ch >= 0)
8615 return ch;
8616
8617 switch ((enum serial_rc) ch)
8618 {
8619 case SERIAL_EOF:
8620 remote_unpush_target ();
8621 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8622 /* no return */
8623 case SERIAL_ERROR:
8624 unpush_and_perror (_("Remote communication error. "
8625 "Target disconnected."));
8626 /* no return */
8627 case SERIAL_TIMEOUT:
8628 break;
8629 }
8630 return ch;
8631 }
8632
8633 /* Wrapper for serial_write that closes the target and throws if
8634 writing fails. The current quit handler is overridden to avoid
8635 quitting in the middle of packet sequence, as that would break
8636 communication with the remote server. See
8637 remote_serial_quit_handler for more detail. */
8638
8639 static void
8640 remote_serial_write (const char *str, int len)
8641 {
8642 struct remote_state *rs = get_remote_state ();
8643
8644 scoped_restore restore_quit
8645 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8646
8647 rs->got_ctrlc_during_io = 0;
8648
8649 if (serial_write (rs->remote_desc, str, len))
8650 {
8651 unpush_and_perror (_("Remote communication error. "
8652 "Target disconnected."));
8653 }
8654
8655 if (rs->got_ctrlc_during_io)
8656 set_quit_flag ();
8657 }
8658
8659 /* Send the command in *BUF to the remote machine, and read the reply
8660 into *BUF. Report an error if we get an error reply. Resize
8661 *BUF using xrealloc if necessary to hold the result, and update
8662 *SIZEOF_BUF. */
8663
8664 static void
8665 remote_send (char **buf,
8666 long *sizeof_buf)
8667 {
8668 putpkt (*buf);
8669 getpkt (buf, sizeof_buf, 0);
8670
8671 if ((*buf)[0] == 'E')
8672 error (_("Remote failure reply: %s"), *buf);
8673 }
8674
8675 /* Return a string representing an escaped version of BUF, of len N.
8676 E.g. \n is converted to \\n, \t to \\t, etc. */
8677
8678 static std::string
8679 escape_buffer (const char *buf, int n)
8680 {
8681 string_file stb;
8682
8683 stb.putstrn (buf, n, '\\');
8684 return std::move (stb.string ());
8685 }
8686
8687 /* Display a null-terminated packet on stdout, for debugging, using C
8688 string notation. */
8689
8690 static void
8691 print_packet (const char *buf)
8692 {
8693 puts_filtered ("\"");
8694 fputstr_filtered (buf, '"', gdb_stdout);
8695 puts_filtered ("\"");
8696 }
8697
8698 int
8699 putpkt (const char *buf)
8700 {
8701 return putpkt_binary (buf, strlen (buf));
8702 }
8703
8704 /* Send a packet to the remote machine, with error checking. The data
8705 of the packet is in BUF. The string in BUF can be at most
8706 get_remote_packet_size () - 5 to account for the $, # and checksum,
8707 and for a possible /0 if we are debugging (remote_debug) and want
8708 to print the sent packet as a string. */
8709
8710 static int
8711 putpkt_binary (const char *buf, int cnt)
8712 {
8713 struct remote_state *rs = get_remote_state ();
8714 int i;
8715 unsigned char csum = 0;
8716 char *buf2 = (char *) xmalloc (cnt + 6);
8717 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8718
8719 int ch;
8720 int tcount = 0;
8721 char *p;
8722
8723 /* Catch cases like trying to read memory or listing threads while
8724 we're waiting for a stop reply. The remote server wouldn't be
8725 ready to handle this request, so we'd hang and timeout. We don't
8726 have to worry about this in synchronous mode, because in that
8727 case it's not possible to issue a command while the target is
8728 running. This is not a problem in non-stop mode, because in that
8729 case, the stub is always ready to process serial input. */
8730 if (!target_is_non_stop_p ()
8731 && target_is_async_p ()
8732 && rs->waiting_for_stop_reply)
8733 {
8734 error (_("Cannot execute this command while the target is running.\n"
8735 "Use the \"interrupt\" command to stop the target\n"
8736 "and then try again."));
8737 }
8738
8739 /* We're sending out a new packet. Make sure we don't look at a
8740 stale cached response. */
8741 rs->cached_wait_status = 0;
8742
8743 /* Copy the packet into buffer BUF2, encapsulating it
8744 and giving it a checksum. */
8745
8746 p = buf2;
8747 *p++ = '$';
8748
8749 for (i = 0; i < cnt; i++)
8750 {
8751 csum += buf[i];
8752 *p++ = buf[i];
8753 }
8754 *p++ = '#';
8755 *p++ = tohex ((csum >> 4) & 0xf);
8756 *p++ = tohex (csum & 0xf);
8757
8758 /* Send it over and over until we get a positive ack. */
8759
8760 while (1)
8761 {
8762 int started_error_output = 0;
8763
8764 if (remote_debug)
8765 {
8766 *p = '\0';
8767
8768 int len = (int) (p - buf2);
8769
8770 std::string str
8771 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8772
8773 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8774
8775 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
8776 {
8777 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
8778 str.length () - REMOTE_DEBUG_MAX_CHAR);
8779 }
8780
8781 fprintf_unfiltered (gdb_stdlog, "...");
8782
8783 gdb_flush (gdb_stdlog);
8784 }
8785 remote_serial_write (buf2, p - buf2);
8786
8787 /* If this is a no acks version of the remote protocol, send the
8788 packet and move on. */
8789 if (rs->noack_mode)
8790 break;
8791
8792 /* Read until either a timeout occurs (-2) or '+' is read.
8793 Handle any notification that arrives in the mean time. */
8794 while (1)
8795 {
8796 ch = readchar (remote_timeout);
8797
8798 if (remote_debug)
8799 {
8800 switch (ch)
8801 {
8802 case '+':
8803 case '-':
8804 case SERIAL_TIMEOUT:
8805 case '$':
8806 case '%':
8807 if (started_error_output)
8808 {
8809 putchar_unfiltered ('\n');
8810 started_error_output = 0;
8811 }
8812 }
8813 }
8814
8815 switch (ch)
8816 {
8817 case '+':
8818 if (remote_debug)
8819 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8820 do_cleanups (old_chain);
8821 return 1;
8822 case '-':
8823 if (remote_debug)
8824 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8825 /* FALLTHROUGH */
8826 case SERIAL_TIMEOUT:
8827 tcount++;
8828 if (tcount > 3)
8829 {
8830 do_cleanups (old_chain);
8831 return 0;
8832 }
8833 break; /* Retransmit buffer. */
8834 case '$':
8835 {
8836 if (remote_debug)
8837 fprintf_unfiltered (gdb_stdlog,
8838 "Packet instead of Ack, ignoring it\n");
8839 /* It's probably an old response sent because an ACK
8840 was lost. Gobble up the packet and ack it so it
8841 doesn't get retransmitted when we resend this
8842 packet. */
8843 skip_frame ();
8844 remote_serial_write ("+", 1);
8845 continue; /* Now, go look for +. */
8846 }
8847
8848 case '%':
8849 {
8850 int val;
8851
8852 /* If we got a notification, handle it, and go back to looking
8853 for an ack. */
8854 /* We've found the start of a notification. Now
8855 collect the data. */
8856 val = read_frame (&rs->buf, &rs->buf_size);
8857 if (val >= 0)
8858 {
8859 if (remote_debug)
8860 {
8861 std::string str = escape_buffer (rs->buf, val);
8862
8863 fprintf_unfiltered (gdb_stdlog,
8864 " Notification received: %s\n",
8865 str.c_str ());
8866 }
8867 handle_notification (rs->notif_state, rs->buf);
8868 /* We're in sync now, rewait for the ack. */
8869 tcount = 0;
8870 }
8871 else
8872 {
8873 if (remote_debug)
8874 {
8875 if (!started_error_output)
8876 {
8877 started_error_output = 1;
8878 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8879 }
8880 fputc_unfiltered (ch & 0177, gdb_stdlog);
8881 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8882 }
8883 }
8884 continue;
8885 }
8886 /* fall-through */
8887 default:
8888 if (remote_debug)
8889 {
8890 if (!started_error_output)
8891 {
8892 started_error_output = 1;
8893 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8894 }
8895 fputc_unfiltered (ch & 0177, gdb_stdlog);
8896 }
8897 continue;
8898 }
8899 break; /* Here to retransmit. */
8900 }
8901
8902 #if 0
8903 /* This is wrong. If doing a long backtrace, the user should be
8904 able to get out next time we call QUIT, without anything as
8905 violent as interrupt_query. If we want to provide a way out of
8906 here without getting to the next QUIT, it should be based on
8907 hitting ^C twice as in remote_wait. */
8908 if (quit_flag)
8909 {
8910 quit_flag = 0;
8911 interrupt_query ();
8912 }
8913 #endif
8914 }
8915
8916 do_cleanups (old_chain);
8917 return 0;
8918 }
8919
8920 /* Come here after finding the start of a frame when we expected an
8921 ack. Do our best to discard the rest of this packet. */
8922
8923 static void
8924 skip_frame (void)
8925 {
8926 int c;
8927
8928 while (1)
8929 {
8930 c = readchar (remote_timeout);
8931 switch (c)
8932 {
8933 case SERIAL_TIMEOUT:
8934 /* Nothing we can do. */
8935 return;
8936 case '#':
8937 /* Discard the two bytes of checksum and stop. */
8938 c = readchar (remote_timeout);
8939 if (c >= 0)
8940 c = readchar (remote_timeout);
8941
8942 return;
8943 case '*': /* Run length encoding. */
8944 /* Discard the repeat count. */
8945 c = readchar (remote_timeout);
8946 if (c < 0)
8947 return;
8948 break;
8949 default:
8950 /* A regular character. */
8951 break;
8952 }
8953 }
8954 }
8955
8956 /* Come here after finding the start of the frame. Collect the rest
8957 into *BUF, verifying the checksum, length, and handling run-length
8958 compression. NUL terminate the buffer. If there is not enough room,
8959 expand *BUF using xrealloc.
8960
8961 Returns -1 on error, number of characters in buffer (ignoring the
8962 trailing NULL) on success. (could be extended to return one of the
8963 SERIAL status indications). */
8964
8965 static long
8966 read_frame (char **buf_p,
8967 long *sizeof_buf)
8968 {
8969 unsigned char csum;
8970 long bc;
8971 int c;
8972 char *buf = *buf_p;
8973 struct remote_state *rs = get_remote_state ();
8974
8975 csum = 0;
8976 bc = 0;
8977
8978 while (1)
8979 {
8980 c = readchar (remote_timeout);
8981 switch (c)
8982 {
8983 case SERIAL_TIMEOUT:
8984 if (remote_debug)
8985 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8986 return -1;
8987 case '$':
8988 if (remote_debug)
8989 fputs_filtered ("Saw new packet start in middle of old one\n",
8990 gdb_stdlog);
8991 return -1; /* Start a new packet, count retries. */
8992 case '#':
8993 {
8994 unsigned char pktcsum;
8995 int check_0 = 0;
8996 int check_1 = 0;
8997
8998 buf[bc] = '\0';
8999
9000 check_0 = readchar (remote_timeout);
9001 if (check_0 >= 0)
9002 check_1 = readchar (remote_timeout);
9003
9004 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9005 {
9006 if (remote_debug)
9007 fputs_filtered ("Timeout in checksum, retrying\n",
9008 gdb_stdlog);
9009 return -1;
9010 }
9011 else if (check_0 < 0 || check_1 < 0)
9012 {
9013 if (remote_debug)
9014 fputs_filtered ("Communication error in checksum\n",
9015 gdb_stdlog);
9016 return -1;
9017 }
9018
9019 /* Don't recompute the checksum; with no ack packets we
9020 don't have any way to indicate a packet retransmission
9021 is necessary. */
9022 if (rs->noack_mode)
9023 return bc;
9024
9025 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9026 if (csum == pktcsum)
9027 return bc;
9028
9029 if (remote_debug)
9030 {
9031 std::string str = escape_buffer (buf, bc);
9032
9033 fprintf_unfiltered (gdb_stdlog,
9034 "Bad checksum, sentsum=0x%x, "
9035 "csum=0x%x, buf=%s\n",
9036 pktcsum, csum, str.c_str ());
9037 }
9038 /* Number of characters in buffer ignoring trailing
9039 NULL. */
9040 return -1;
9041 }
9042 case '*': /* Run length encoding. */
9043 {
9044 int repeat;
9045
9046 csum += c;
9047 c = readchar (remote_timeout);
9048 csum += c;
9049 repeat = c - ' ' + 3; /* Compute repeat count. */
9050
9051 /* The character before ``*'' is repeated. */
9052
9053 if (repeat > 0 && repeat <= 255 && bc > 0)
9054 {
9055 if (bc + repeat - 1 >= *sizeof_buf - 1)
9056 {
9057 /* Make some more room in the buffer. */
9058 *sizeof_buf += repeat;
9059 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9060 buf = *buf_p;
9061 }
9062
9063 memset (&buf[bc], buf[bc - 1], repeat);
9064 bc += repeat;
9065 continue;
9066 }
9067
9068 buf[bc] = '\0';
9069 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9070 return -1;
9071 }
9072 default:
9073 if (bc >= *sizeof_buf - 1)
9074 {
9075 /* Make some more room in the buffer. */
9076 *sizeof_buf *= 2;
9077 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9078 buf = *buf_p;
9079 }
9080
9081 buf[bc++] = c;
9082 csum += c;
9083 continue;
9084 }
9085 }
9086 }
9087
9088 /* Read a packet from the remote machine, with error checking, and
9089 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9090 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9091 rather than timing out; this is used (in synchronous mode) to wait
9092 for a target that is is executing user code to stop. */
9093 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9094 don't have to change all the calls to getpkt to deal with the
9095 return value, because at the moment I don't know what the right
9096 thing to do it for those. */
9097 void
9098 getpkt (char **buf,
9099 long *sizeof_buf,
9100 int forever)
9101 {
9102 getpkt_sane (buf, sizeof_buf, forever);
9103 }
9104
9105
9106 /* Read a packet from the remote machine, with error checking, and
9107 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9108 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9109 rather than timing out; this is used (in synchronous mode) to wait
9110 for a target that is is executing user code to stop. If FOREVER ==
9111 0, this function is allowed to time out gracefully and return an
9112 indication of this to the caller. Otherwise return the number of
9113 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9114 enough reason to return to the caller. *IS_NOTIF is an output
9115 boolean that indicates whether *BUF holds a notification or not
9116 (a regular packet). */
9117
9118 static int
9119 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9120 int expecting_notif, int *is_notif)
9121 {
9122 struct remote_state *rs = get_remote_state ();
9123 int c;
9124 int tries;
9125 int timeout;
9126 int val = -1;
9127
9128 /* We're reading a new response. Make sure we don't look at a
9129 previously cached response. */
9130 rs->cached_wait_status = 0;
9131
9132 strcpy (*buf, "timeout");
9133
9134 if (forever)
9135 timeout = watchdog > 0 ? watchdog : -1;
9136 else if (expecting_notif)
9137 timeout = 0; /* There should already be a char in the buffer. If
9138 not, bail out. */
9139 else
9140 timeout = remote_timeout;
9141
9142 #define MAX_TRIES 3
9143
9144 /* Process any number of notifications, and then return when
9145 we get a packet. */
9146 for (;;)
9147 {
9148 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9149 times. */
9150 for (tries = 1; tries <= MAX_TRIES; tries++)
9151 {
9152 /* This can loop forever if the remote side sends us
9153 characters continuously, but if it pauses, we'll get
9154 SERIAL_TIMEOUT from readchar because of timeout. Then
9155 we'll count that as a retry.
9156
9157 Note that even when forever is set, we will only wait
9158 forever prior to the start of a packet. After that, we
9159 expect characters to arrive at a brisk pace. They should
9160 show up within remote_timeout intervals. */
9161 do
9162 c = readchar (timeout);
9163 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9164
9165 if (c == SERIAL_TIMEOUT)
9166 {
9167 if (expecting_notif)
9168 return -1; /* Don't complain, it's normal to not get
9169 anything in this case. */
9170
9171 if (forever) /* Watchdog went off? Kill the target. */
9172 {
9173 remote_unpush_target ();
9174 throw_error (TARGET_CLOSE_ERROR,
9175 _("Watchdog timeout has expired. "
9176 "Target detached."));
9177 }
9178 if (remote_debug)
9179 fputs_filtered ("Timed out.\n", gdb_stdlog);
9180 }
9181 else
9182 {
9183 /* We've found the start of a packet or notification.
9184 Now collect the data. */
9185 val = read_frame (buf, sizeof_buf);
9186 if (val >= 0)
9187 break;
9188 }
9189
9190 remote_serial_write ("-", 1);
9191 }
9192
9193 if (tries > MAX_TRIES)
9194 {
9195 /* We have tried hard enough, and just can't receive the
9196 packet/notification. Give up. */
9197 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9198
9199 /* Skip the ack char if we're in no-ack mode. */
9200 if (!rs->noack_mode)
9201 remote_serial_write ("+", 1);
9202 return -1;
9203 }
9204
9205 /* If we got an ordinary packet, return that to our caller. */
9206 if (c == '$')
9207 {
9208 if (remote_debug)
9209 {
9210 std::string str
9211 = escape_buffer (*buf,
9212 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9213
9214 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9215 str.c_str ());
9216
9217 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
9218 {
9219 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
9220 str.length () - REMOTE_DEBUG_MAX_CHAR);
9221 }
9222
9223 fprintf_unfiltered (gdb_stdlog, "\n");
9224 }
9225
9226 /* Skip the ack char if we're in no-ack mode. */
9227 if (!rs->noack_mode)
9228 remote_serial_write ("+", 1);
9229 if (is_notif != NULL)
9230 *is_notif = 0;
9231 return val;
9232 }
9233
9234 /* If we got a notification, handle it, and go back to looking
9235 for a packet. */
9236 else
9237 {
9238 gdb_assert (c == '%');
9239
9240 if (remote_debug)
9241 {
9242 std::string str = escape_buffer (*buf, val);
9243
9244 fprintf_unfiltered (gdb_stdlog,
9245 " Notification received: %s\n",
9246 str.c_str ());
9247 }
9248 if (is_notif != NULL)
9249 *is_notif = 1;
9250
9251 handle_notification (rs->notif_state, *buf);
9252
9253 /* Notifications require no acknowledgement. */
9254
9255 if (expecting_notif)
9256 return val;
9257 }
9258 }
9259 }
9260
9261 static int
9262 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9263 {
9264 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9265 }
9266
9267 static int
9268 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9269 int *is_notif)
9270 {
9271 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9272 is_notif);
9273 }
9274
9275 /* Check whether EVENT is a fork event for the process specified
9276 by the pid passed in DATA, and if it is, kill the fork child. */
9277
9278 static int
9279 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9280 QUEUE_ITER (stop_reply_p) *iter,
9281 stop_reply_p event,
9282 void *data)
9283 {
9284 struct queue_iter_param *param = (struct queue_iter_param *) data;
9285 int parent_pid = *(int *) param->input;
9286
9287 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9288 {
9289 struct remote_state *rs = get_remote_state ();
9290 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9291 int res;
9292
9293 res = remote_vkill (child_pid, rs);
9294 if (res != 0)
9295 error (_("Can't kill fork child process %d"), child_pid);
9296 }
9297
9298 return 1;
9299 }
9300
9301 /* Kill any new fork children of process PID that haven't been
9302 processed by follow_fork. */
9303
9304 static void
9305 kill_new_fork_children (int pid, struct remote_state *rs)
9306 {
9307 struct thread_info *thread;
9308 struct notif_client *notif = &notif_client_stop;
9309 struct queue_iter_param param;
9310
9311 /* Kill the fork child threads of any threads in process PID
9312 that are stopped at a fork event. */
9313 ALL_NON_EXITED_THREADS (thread)
9314 {
9315 struct target_waitstatus *ws = &thread->pending_follow;
9316
9317 if (is_pending_fork_parent (ws, pid, thread->ptid))
9318 {
9319 struct remote_state *rs = get_remote_state ();
9320 int child_pid = ptid_get_pid (ws->value.related_pid);
9321 int res;
9322
9323 res = remote_vkill (child_pid, rs);
9324 if (res != 0)
9325 error (_("Can't kill fork child process %d"), child_pid);
9326 }
9327 }
9328
9329 /* Check for any pending fork events (not reported or processed yet)
9330 in process PID and kill those fork child threads as well. */
9331 remote_notif_get_pending_events (notif);
9332 param.input = &pid;
9333 param.output = NULL;
9334 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9335 kill_child_of_pending_fork, &param);
9336 }
9337
9338 \f
9339 /* Target hook to kill the current inferior. */
9340
9341 static void
9342 remote_kill (struct target_ops *ops)
9343 {
9344 int res = -1;
9345 int pid = ptid_get_pid (inferior_ptid);
9346 struct remote_state *rs = get_remote_state ();
9347
9348 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9349 {
9350 /* If we're stopped while forking and we haven't followed yet,
9351 kill the child task. We need to do this before killing the
9352 parent task because if this is a vfork then the parent will
9353 be sleeping. */
9354 kill_new_fork_children (pid, rs);
9355
9356 res = remote_vkill (pid, rs);
9357 if (res == 0)
9358 {
9359 target_mourn_inferior (inferior_ptid);
9360 return;
9361 }
9362 }
9363
9364 /* If we are in 'target remote' mode and we are killing the only
9365 inferior, then we will tell gdbserver to exit and unpush the
9366 target. */
9367 if (res == -1 && !remote_multi_process_p (rs)
9368 && number_of_live_inferiors () == 1)
9369 {
9370 remote_kill_k ();
9371
9372 /* We've killed the remote end, we get to mourn it. If we are
9373 not in extended mode, mourning the inferior also unpushes
9374 remote_ops from the target stack, which closes the remote
9375 connection. */
9376 target_mourn_inferior (inferior_ptid);
9377
9378 return;
9379 }
9380
9381 error (_("Can't kill process"));
9382 }
9383
9384 /* Send a kill request to the target using the 'vKill' packet. */
9385
9386 static int
9387 remote_vkill (int pid, struct remote_state *rs)
9388 {
9389 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9390 return -1;
9391
9392 /* Tell the remote target to detach. */
9393 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9394 putpkt (rs->buf);
9395 getpkt (&rs->buf, &rs->buf_size, 0);
9396
9397 switch (packet_ok (rs->buf,
9398 &remote_protocol_packets[PACKET_vKill]))
9399 {
9400 case PACKET_OK:
9401 return 0;
9402 case PACKET_ERROR:
9403 return 1;
9404 case PACKET_UNKNOWN:
9405 return -1;
9406 default:
9407 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9408 }
9409 }
9410
9411 /* Send a kill request to the target using the 'k' packet. */
9412
9413 static void
9414 remote_kill_k (void)
9415 {
9416 /* Catch errors so the user can quit from gdb even when we
9417 aren't on speaking terms with the remote system. */
9418 TRY
9419 {
9420 putpkt ("k");
9421 }
9422 CATCH (ex, RETURN_MASK_ERROR)
9423 {
9424 if (ex.error == TARGET_CLOSE_ERROR)
9425 {
9426 /* If we got an (EOF) error that caused the target
9427 to go away, then we're done, that's what we wanted.
9428 "k" is susceptible to cause a premature EOF, given
9429 that the remote server isn't actually required to
9430 reply to "k", and it can happen that it doesn't
9431 even get to reply ACK to the "k". */
9432 return;
9433 }
9434
9435 /* Otherwise, something went wrong. We didn't actually kill
9436 the target. Just propagate the exception, and let the
9437 user or higher layers decide what to do. */
9438 throw_exception (ex);
9439 }
9440 END_CATCH
9441 }
9442
9443 static void
9444 remote_mourn (struct target_ops *target)
9445 {
9446 struct remote_state *rs = get_remote_state ();
9447
9448 /* In 'target remote' mode with one inferior, we close the connection. */
9449 if (!rs->extended && number_of_live_inferiors () <= 1)
9450 {
9451 unpush_target (target);
9452
9453 /* remote_close takes care of doing most of the clean up. */
9454 generic_mourn_inferior ();
9455 return;
9456 }
9457
9458 /* In case we got here due to an error, but we're going to stay
9459 connected. */
9460 rs->waiting_for_stop_reply = 0;
9461
9462 /* If the current general thread belonged to the process we just
9463 detached from or has exited, the remote side current general
9464 thread becomes undefined. Considering a case like this:
9465
9466 - We just got here due to a detach.
9467 - The process that we're detaching from happens to immediately
9468 report a global breakpoint being hit in non-stop mode, in the
9469 same thread we had selected before.
9470 - GDB attaches to this process again.
9471 - This event happens to be the next event we handle.
9472
9473 GDB would consider that the current general thread didn't need to
9474 be set on the stub side (with Hg), since for all it knew,
9475 GENERAL_THREAD hadn't changed.
9476
9477 Notice that although in all-stop mode, the remote server always
9478 sets the current thread to the thread reporting the stop event,
9479 that doesn't happen in non-stop mode; in non-stop, the stub *must
9480 not* change the current thread when reporting a breakpoint hit,
9481 due to the decoupling of event reporting and event handling.
9482
9483 To keep things simple, we always invalidate our notion of the
9484 current thread. */
9485 record_currthread (rs, minus_one_ptid);
9486
9487 /* Call common code to mark the inferior as not running. */
9488 generic_mourn_inferior ();
9489
9490 if (!have_inferiors ())
9491 {
9492 if (!remote_multi_process_p (rs))
9493 {
9494 /* Check whether the target is running now - some remote stubs
9495 automatically restart after kill. */
9496 putpkt ("?");
9497 getpkt (&rs->buf, &rs->buf_size, 0);
9498
9499 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9500 {
9501 /* Assume that the target has been restarted. Set
9502 inferior_ptid so that bits of core GDB realizes
9503 there's something here, e.g., so that the user can
9504 say "kill" again. */
9505 inferior_ptid = magic_null_ptid;
9506 }
9507 }
9508 }
9509 }
9510
9511 static int
9512 extended_remote_supports_disable_randomization (struct target_ops *self)
9513 {
9514 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9515 }
9516
9517 static void
9518 extended_remote_disable_randomization (int val)
9519 {
9520 struct remote_state *rs = get_remote_state ();
9521 char *reply;
9522
9523 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9524 val);
9525 putpkt (rs->buf);
9526 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9527 if (*reply == '\0')
9528 error (_("Target does not support QDisableRandomization."));
9529 if (strcmp (reply, "OK") != 0)
9530 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9531 }
9532
9533 static int
9534 extended_remote_run (const std::string &args)
9535 {
9536 struct remote_state *rs = get_remote_state ();
9537 int len;
9538 const char *remote_exec_file = get_remote_exec_file ();
9539
9540 /* If the user has disabled vRun support, or we have detected that
9541 support is not available, do not try it. */
9542 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9543 return -1;
9544
9545 strcpy (rs->buf, "vRun;");
9546 len = strlen (rs->buf);
9547
9548 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9549 error (_("Remote file name too long for run packet"));
9550 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9551 strlen (remote_exec_file));
9552
9553 if (!args.empty ())
9554 {
9555 int i;
9556
9557 gdb_argv argv (args.c_str ());
9558 for (i = 0; argv[i] != NULL; i++)
9559 {
9560 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9561 error (_("Argument list too long for run packet"));
9562 rs->buf[len++] = ';';
9563 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9564 strlen (argv[i]));
9565 }
9566 }
9567
9568 rs->buf[len++] = '\0';
9569
9570 putpkt (rs->buf);
9571 getpkt (&rs->buf, &rs->buf_size, 0);
9572
9573 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9574 {
9575 case PACKET_OK:
9576 /* We have a wait response. All is well. */
9577 return 0;
9578 case PACKET_UNKNOWN:
9579 return -1;
9580 case PACKET_ERROR:
9581 if (remote_exec_file[0] == '\0')
9582 error (_("Running the default executable on the remote target failed; "
9583 "try \"set remote exec-file\"?"));
9584 else
9585 error (_("Running \"%s\" on the remote target failed"),
9586 remote_exec_file);
9587 default:
9588 gdb_assert_not_reached (_("bad switch"));
9589 }
9590 }
9591
9592 /* Helper function to send set/unset environment packets. ACTION is
9593 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9594 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9595 sent. */
9596
9597 static void
9598 send_environment_packet (struct remote_state *rs,
9599 const char *action,
9600 const char *packet,
9601 const char *value)
9602 {
9603 /* Convert the environment variable to an hex string, which
9604 is the best format to be transmitted over the wire. */
9605 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9606 strlen (value));
9607
9608 xsnprintf (rs->buf, get_remote_packet_size (),
9609 "%s:%s", packet, encoded_value.c_str ());
9610
9611 putpkt (rs->buf);
9612 getpkt (&rs->buf, &rs->buf_size, 0);
9613 if (strcmp (rs->buf, "OK") != 0)
9614 warning (_("Unable to %s environment variable '%s' on remote."),
9615 action, value);
9616 }
9617
9618 /* Helper function to handle the QEnvironment* packets. */
9619
9620 static void
9621 extended_remote_environment_support (struct remote_state *rs)
9622 {
9623 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9624 {
9625 putpkt ("QEnvironmentReset");
9626 getpkt (&rs->buf, &rs->buf_size, 0);
9627 if (strcmp (rs->buf, "OK") != 0)
9628 warning (_("Unable to reset environment on remote."));
9629 }
9630
9631 gdb_environ *e = &current_inferior ()->environment;
9632
9633 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9634 for (const std::string &el : e->user_set_env ())
9635 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9636 el.c_str ());
9637
9638 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9639 for (const std::string &el : e->user_unset_env ())
9640 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9641 }
9642
9643 /* In the extended protocol we want to be able to do things like
9644 "run" and have them basically work as expected. So we need
9645 a special create_inferior function. We support changing the
9646 executable file and the command line arguments, but not the
9647 environment. */
9648
9649 static void
9650 extended_remote_create_inferior (struct target_ops *ops,
9651 const char *exec_file,
9652 const std::string &args,
9653 char **env, int from_tty)
9654 {
9655 int run_worked;
9656 char *stop_reply;
9657 struct remote_state *rs = get_remote_state ();
9658 const char *remote_exec_file = get_remote_exec_file ();
9659
9660 /* If running asynchronously, register the target file descriptor
9661 with the event loop. */
9662 if (target_can_async_p ())
9663 target_async (1);
9664
9665 /* Disable address space randomization if requested (and supported). */
9666 if (extended_remote_supports_disable_randomization (ops))
9667 extended_remote_disable_randomization (disable_randomization);
9668
9669 /* If startup-with-shell is on, we inform gdbserver to start the
9670 remote inferior using a shell. */
9671 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9672 {
9673 xsnprintf (rs->buf, get_remote_packet_size (),
9674 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9675 putpkt (rs->buf);
9676 getpkt (&rs->buf, &rs->buf_size, 0);
9677 if (strcmp (rs->buf, "OK") != 0)
9678 error (_("\
9679 Remote replied unexpectedly while setting startup-with-shell: %s"),
9680 rs->buf);
9681 }
9682
9683 extended_remote_environment_support (rs);
9684
9685 /* Now restart the remote server. */
9686 run_worked = extended_remote_run (args) != -1;
9687 if (!run_worked)
9688 {
9689 /* vRun was not supported. Fail if we need it to do what the
9690 user requested. */
9691 if (remote_exec_file[0])
9692 error (_("Remote target does not support \"set remote exec-file\""));
9693 if (!args.empty ())
9694 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9695
9696 /* Fall back to "R". */
9697 extended_remote_restart ();
9698 }
9699
9700 if (!have_inferiors ())
9701 {
9702 /* Clean up from the last time we ran, before we mark the target
9703 running again. This will mark breakpoints uninserted, and
9704 get_offsets may insert breakpoints. */
9705 init_thread_list ();
9706 init_wait_for_inferior ();
9707 }
9708
9709 /* vRun's success return is a stop reply. */
9710 stop_reply = run_worked ? rs->buf : NULL;
9711 add_current_inferior_and_thread (stop_reply);
9712
9713 /* Get updated offsets, if the stub uses qOffsets. */
9714 get_offsets ();
9715 }
9716 \f
9717
9718 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9719 the list of conditions (in agent expression bytecode format), if any, the
9720 target needs to evaluate. The output is placed into the packet buffer
9721 started from BUF and ended at BUF_END. */
9722
9723 static int
9724 remote_add_target_side_condition (struct gdbarch *gdbarch,
9725 struct bp_target_info *bp_tgt, char *buf,
9726 char *buf_end)
9727 {
9728 if (bp_tgt->conditions.empty ())
9729 return 0;
9730
9731 buf += strlen (buf);
9732 xsnprintf (buf, buf_end - buf, "%s", ";");
9733 buf++;
9734
9735 /* Send conditions to the target. */
9736 for (agent_expr *aexpr : bp_tgt->conditions)
9737 {
9738 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9739 buf += strlen (buf);
9740 for (int i = 0; i < aexpr->len; ++i)
9741 buf = pack_hex_byte (buf, aexpr->buf[i]);
9742 *buf = '\0';
9743 }
9744 return 0;
9745 }
9746
9747 static void
9748 remote_add_target_side_commands (struct gdbarch *gdbarch,
9749 struct bp_target_info *bp_tgt, char *buf)
9750 {
9751 if (bp_tgt->tcommands.empty ())
9752 return;
9753
9754 buf += strlen (buf);
9755
9756 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9757 buf += strlen (buf);
9758
9759 /* Concatenate all the agent expressions that are commands into the
9760 cmds parameter. */
9761 for (agent_expr *aexpr : bp_tgt->tcommands)
9762 {
9763 sprintf (buf, "X%x,", aexpr->len);
9764 buf += strlen (buf);
9765 for (int i = 0; i < aexpr->len; ++i)
9766 buf = pack_hex_byte (buf, aexpr->buf[i]);
9767 *buf = '\0';
9768 }
9769 }
9770
9771 /* Insert a breakpoint. On targets that have software breakpoint
9772 support, we ask the remote target to do the work; on targets
9773 which don't, we insert a traditional memory breakpoint. */
9774
9775 static int
9776 remote_insert_breakpoint (struct target_ops *ops,
9777 struct gdbarch *gdbarch,
9778 struct bp_target_info *bp_tgt)
9779 {
9780 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9781 If it succeeds, then set the support to PACKET_ENABLE. If it
9782 fails, and the user has explicitly requested the Z support then
9783 report an error, otherwise, mark it disabled and go on. */
9784
9785 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9786 {
9787 CORE_ADDR addr = bp_tgt->reqstd_address;
9788 struct remote_state *rs;
9789 char *p, *endbuf;
9790 int bpsize;
9791
9792 /* Make sure the remote is pointing at the right process, if
9793 necessary. */
9794 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9795 set_general_process ();
9796
9797 rs = get_remote_state ();
9798 p = rs->buf;
9799 endbuf = rs->buf + get_remote_packet_size ();
9800
9801 *(p++) = 'Z';
9802 *(p++) = '0';
9803 *(p++) = ',';
9804 addr = (ULONGEST) remote_address_masked (addr);
9805 p += hexnumstr (p, addr);
9806 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9807
9808 if (remote_supports_cond_breakpoints (ops))
9809 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9810
9811 if (remote_can_run_breakpoint_commands (ops))
9812 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9813
9814 putpkt (rs->buf);
9815 getpkt (&rs->buf, &rs->buf_size, 0);
9816
9817 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9818 {
9819 case PACKET_ERROR:
9820 return -1;
9821 case PACKET_OK:
9822 return 0;
9823 case PACKET_UNKNOWN:
9824 break;
9825 }
9826 }
9827
9828 /* If this breakpoint has target-side commands but this stub doesn't
9829 support Z0 packets, throw error. */
9830 if (!bp_tgt->tcommands.empty ())
9831 throw_error (NOT_SUPPORTED_ERROR, _("\
9832 Target doesn't support breakpoints that have target side commands."));
9833
9834 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9835 }
9836
9837 static int
9838 remote_remove_breakpoint (struct target_ops *ops,
9839 struct gdbarch *gdbarch,
9840 struct bp_target_info *bp_tgt,
9841 enum remove_bp_reason reason)
9842 {
9843 CORE_ADDR addr = bp_tgt->placed_address;
9844 struct remote_state *rs = get_remote_state ();
9845
9846 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9847 {
9848 char *p = rs->buf;
9849 char *endbuf = rs->buf + get_remote_packet_size ();
9850
9851 /* Make sure the remote is pointing at the right process, if
9852 necessary. */
9853 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9854 set_general_process ();
9855
9856 *(p++) = 'z';
9857 *(p++) = '0';
9858 *(p++) = ',';
9859
9860 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9861 p += hexnumstr (p, addr);
9862 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9863
9864 putpkt (rs->buf);
9865 getpkt (&rs->buf, &rs->buf_size, 0);
9866
9867 return (rs->buf[0] == 'E');
9868 }
9869
9870 return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
9871 }
9872
9873 static enum Z_packet_type
9874 watchpoint_to_Z_packet (int type)
9875 {
9876 switch (type)
9877 {
9878 case hw_write:
9879 return Z_PACKET_WRITE_WP;
9880 break;
9881 case hw_read:
9882 return Z_PACKET_READ_WP;
9883 break;
9884 case hw_access:
9885 return Z_PACKET_ACCESS_WP;
9886 break;
9887 default:
9888 internal_error (__FILE__, __LINE__,
9889 _("hw_bp_to_z: bad watchpoint type %d"), type);
9890 }
9891 }
9892
9893 static int
9894 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9895 enum target_hw_bp_type type, struct expression *cond)
9896 {
9897 struct remote_state *rs = get_remote_state ();
9898 char *endbuf = rs->buf + get_remote_packet_size ();
9899 char *p;
9900 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9901
9902 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9903 return 1;
9904
9905 /* Make sure the remote is pointing at the right process, if
9906 necessary. */
9907 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9908 set_general_process ();
9909
9910 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9911 p = strchr (rs->buf, '\0');
9912 addr = remote_address_masked (addr);
9913 p += hexnumstr (p, (ULONGEST) addr);
9914 xsnprintf (p, endbuf - p, ",%x", len);
9915
9916 putpkt (rs->buf);
9917 getpkt (&rs->buf, &rs->buf_size, 0);
9918
9919 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9920 {
9921 case PACKET_ERROR:
9922 return -1;
9923 case PACKET_UNKNOWN:
9924 return 1;
9925 case PACKET_OK:
9926 return 0;
9927 }
9928 internal_error (__FILE__, __LINE__,
9929 _("remote_insert_watchpoint: reached end of function"));
9930 }
9931
9932 static int
9933 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9934 CORE_ADDR start, int length)
9935 {
9936 CORE_ADDR diff = remote_address_masked (addr - start);
9937
9938 return diff < length;
9939 }
9940
9941
9942 static int
9943 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9944 enum target_hw_bp_type type, struct expression *cond)
9945 {
9946 struct remote_state *rs = get_remote_state ();
9947 char *endbuf = rs->buf + get_remote_packet_size ();
9948 char *p;
9949 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9950
9951 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9952 return -1;
9953
9954 /* Make sure the remote is pointing at the right process, if
9955 necessary. */
9956 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9957 set_general_process ();
9958
9959 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9960 p = strchr (rs->buf, '\0');
9961 addr = remote_address_masked (addr);
9962 p += hexnumstr (p, (ULONGEST) addr);
9963 xsnprintf (p, endbuf - p, ",%x", len);
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 case PACKET_UNKNOWN:
9971 return -1;
9972 case PACKET_OK:
9973 return 0;
9974 }
9975 internal_error (__FILE__, __LINE__,
9976 _("remote_remove_watchpoint: reached end of function"));
9977 }
9978
9979
9980 int remote_hw_watchpoint_limit = -1;
9981 int remote_hw_watchpoint_length_limit = -1;
9982 int remote_hw_breakpoint_limit = -1;
9983
9984 static int
9985 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9986 CORE_ADDR addr, int len)
9987 {
9988 if (remote_hw_watchpoint_length_limit == 0)
9989 return 0;
9990 else if (remote_hw_watchpoint_length_limit < 0)
9991 return 1;
9992 else if (len <= remote_hw_watchpoint_length_limit)
9993 return 1;
9994 else
9995 return 0;
9996 }
9997
9998 static int
9999 remote_check_watch_resources (struct target_ops *self,
10000 enum bptype type, int cnt, int ot)
10001 {
10002 if (type == bp_hardware_breakpoint)
10003 {
10004 if (remote_hw_breakpoint_limit == 0)
10005 return 0;
10006 else if (remote_hw_breakpoint_limit < 0)
10007 return 1;
10008 else if (cnt <= remote_hw_breakpoint_limit)
10009 return 1;
10010 }
10011 else
10012 {
10013 if (remote_hw_watchpoint_limit == 0)
10014 return 0;
10015 else if (remote_hw_watchpoint_limit < 0)
10016 return 1;
10017 else if (ot)
10018 return -1;
10019 else if (cnt <= remote_hw_watchpoint_limit)
10020 return 1;
10021 }
10022 return -1;
10023 }
10024
10025 /* The to_stopped_by_sw_breakpoint method of target remote. */
10026
10027 static int
10028 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
10029 {
10030 struct thread_info *thread = inferior_thread ();
10031
10032 return (thread->priv != NULL
10033 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
10034 }
10035
10036 /* The to_supports_stopped_by_sw_breakpoint method of target
10037 remote. */
10038
10039 static int
10040 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
10041 {
10042 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10043 }
10044
10045 /* The to_stopped_by_hw_breakpoint method of target remote. */
10046
10047 static int
10048 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
10049 {
10050 struct thread_info *thread = inferior_thread ();
10051
10052 return (thread->priv != NULL
10053 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
10054 }
10055
10056 /* The to_supports_stopped_by_hw_breakpoint method of target
10057 remote. */
10058
10059 static int
10060 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
10061 {
10062 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10063 }
10064
10065 static int
10066 remote_stopped_by_watchpoint (struct target_ops *ops)
10067 {
10068 struct thread_info *thread = inferior_thread ();
10069
10070 return (thread->priv != NULL
10071 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
10072 }
10073
10074 static int
10075 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
10076 {
10077 struct thread_info *thread = inferior_thread ();
10078
10079 if (thread->priv != NULL
10080 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
10081 {
10082 *addr_p = thread->priv->watch_data_address;
10083 return 1;
10084 }
10085
10086 return 0;
10087 }
10088
10089
10090 static int
10091 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10092 struct bp_target_info *bp_tgt)
10093 {
10094 CORE_ADDR addr = bp_tgt->reqstd_address;
10095 struct remote_state *rs;
10096 char *p, *endbuf;
10097 char *message;
10098
10099 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10100 return -1;
10101
10102 /* Make sure the remote is pointing at the right process, if
10103 necessary. */
10104 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10105 set_general_process ();
10106
10107 rs = get_remote_state ();
10108 p = rs->buf;
10109 endbuf = rs->buf + get_remote_packet_size ();
10110
10111 *(p++) = 'Z';
10112 *(p++) = '1';
10113 *(p++) = ',';
10114
10115 addr = remote_address_masked (addr);
10116 p += hexnumstr (p, (ULONGEST) addr);
10117 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10118
10119 if (remote_supports_cond_breakpoints (self))
10120 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10121
10122 if (remote_can_run_breakpoint_commands (self))
10123 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10124
10125 putpkt (rs->buf);
10126 getpkt (&rs->buf, &rs->buf_size, 0);
10127
10128 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10129 {
10130 case PACKET_ERROR:
10131 if (rs->buf[1] == '.')
10132 {
10133 message = strchr (rs->buf + 2, '.');
10134 if (message)
10135 error (_("Remote failure reply: %s"), message + 1);
10136 }
10137 return -1;
10138 case PACKET_UNKNOWN:
10139 return -1;
10140 case PACKET_OK:
10141 return 0;
10142 }
10143 internal_error (__FILE__, __LINE__,
10144 _("remote_insert_hw_breakpoint: reached end of function"));
10145 }
10146
10147
10148 static int
10149 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10150 struct bp_target_info *bp_tgt)
10151 {
10152 CORE_ADDR addr;
10153 struct remote_state *rs = get_remote_state ();
10154 char *p = rs->buf;
10155 char *endbuf = rs->buf + get_remote_packet_size ();
10156
10157 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10158 return -1;
10159
10160 /* Make sure the remote is pointing at the right process, if
10161 necessary. */
10162 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10163 set_general_process ();
10164
10165 *(p++) = 'z';
10166 *(p++) = '1';
10167 *(p++) = ',';
10168
10169 addr = remote_address_masked (bp_tgt->placed_address);
10170 p += hexnumstr (p, (ULONGEST) addr);
10171 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
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 case PACKET_UNKNOWN:
10180 return -1;
10181 case PACKET_OK:
10182 return 0;
10183 }
10184 internal_error (__FILE__, __LINE__,
10185 _("remote_remove_hw_breakpoint: reached end of function"));
10186 }
10187
10188 /* Verify memory using the "qCRC:" request. */
10189
10190 static int
10191 remote_verify_memory (struct target_ops *ops,
10192 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10193 {
10194 struct remote_state *rs = get_remote_state ();
10195 unsigned long host_crc, target_crc;
10196 char *tmp;
10197
10198 /* It doesn't make sense to use qCRC if the remote target is
10199 connected but not running. */
10200 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10201 {
10202 enum packet_result result;
10203
10204 /* Make sure the remote is pointing at the right process. */
10205 set_general_process ();
10206
10207 /* FIXME: assumes lma can fit into long. */
10208 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10209 (long) lma, (long) size);
10210 putpkt (rs->buf);
10211
10212 /* Be clever; compute the host_crc before waiting for target
10213 reply. */
10214 host_crc = xcrc32 (data, size, 0xffffffff);
10215
10216 getpkt (&rs->buf, &rs->buf_size, 0);
10217
10218 result = packet_ok (rs->buf,
10219 &remote_protocol_packets[PACKET_qCRC]);
10220 if (result == PACKET_ERROR)
10221 return -1;
10222 else if (result == PACKET_OK)
10223 {
10224 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10225 target_crc = target_crc * 16 + fromhex (*tmp);
10226
10227 return (host_crc == target_crc);
10228 }
10229 }
10230
10231 return simple_verify_memory (ops, data, lma, size);
10232 }
10233
10234 /* compare-sections command
10235
10236 With no arguments, compares each loadable section in the exec bfd
10237 with the same memory range on the target, and reports mismatches.
10238 Useful for verifying the image on the target against the exec file. */
10239
10240 static void
10241 compare_sections_command (const char *args, int from_tty)
10242 {
10243 asection *s;
10244 struct cleanup *old_chain;
10245 gdb_byte *sectdata;
10246 const char *sectname;
10247 bfd_size_type size;
10248 bfd_vma lma;
10249 int matched = 0;
10250 int mismatched = 0;
10251 int res;
10252 int read_only = 0;
10253
10254 if (!exec_bfd)
10255 error (_("command cannot be used without an exec file"));
10256
10257 /* Make sure the remote is pointing at the right process. */
10258 set_general_process ();
10259
10260 if (args != NULL && strcmp (args, "-r") == 0)
10261 {
10262 read_only = 1;
10263 args = NULL;
10264 }
10265
10266 for (s = exec_bfd->sections; s; s = s->next)
10267 {
10268 if (!(s->flags & SEC_LOAD))
10269 continue; /* Skip non-loadable section. */
10270
10271 if (read_only && (s->flags & SEC_READONLY) == 0)
10272 continue; /* Skip writeable sections */
10273
10274 size = bfd_get_section_size (s);
10275 if (size == 0)
10276 continue; /* Skip zero-length section. */
10277
10278 sectname = bfd_get_section_name (exec_bfd, s);
10279 if (args && strcmp (args, sectname) != 0)
10280 continue; /* Not the section selected by user. */
10281
10282 matched = 1; /* Do this section. */
10283 lma = s->lma;
10284
10285 sectdata = (gdb_byte *) xmalloc (size);
10286 old_chain = make_cleanup (xfree, sectdata);
10287 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
10288
10289 res = target_verify_memory (sectdata, lma, size);
10290
10291 if (res == -1)
10292 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10293 paddress (target_gdbarch (), lma),
10294 paddress (target_gdbarch (), lma + size));
10295
10296 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10297 paddress (target_gdbarch (), lma),
10298 paddress (target_gdbarch (), lma + size));
10299 if (res)
10300 printf_filtered ("matched.\n");
10301 else
10302 {
10303 printf_filtered ("MIS-MATCHED!\n");
10304 mismatched++;
10305 }
10306
10307 do_cleanups (old_chain);
10308 }
10309 if (mismatched > 0)
10310 warning (_("One or more sections of the target image does not match\n\
10311 the loaded file\n"));
10312 if (args && !matched)
10313 printf_filtered (_("No loaded section named '%s'.\n"), args);
10314 }
10315
10316 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10317 into remote target. The number of bytes written to the remote
10318 target is returned, or -1 for error. */
10319
10320 static enum target_xfer_status
10321 remote_write_qxfer (struct target_ops *ops, const char *object_name,
10322 const char *annex, const gdb_byte *writebuf,
10323 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10324 struct packet_config *packet)
10325 {
10326 int i, buf_len;
10327 ULONGEST n;
10328 struct remote_state *rs = get_remote_state ();
10329 int max_size = get_memory_write_packet_size ();
10330
10331 if (packet->support == PACKET_DISABLE)
10332 return TARGET_XFER_E_IO;
10333
10334 /* Insert header. */
10335 i = snprintf (rs->buf, max_size,
10336 "qXfer:%s:write:%s:%s:",
10337 object_name, annex ? annex : "",
10338 phex_nz (offset, sizeof offset));
10339 max_size -= (i + 1);
10340
10341 /* Escape as much data as fits into rs->buf. */
10342 buf_len = remote_escape_output
10343 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10344
10345 if (putpkt_binary (rs->buf, i + buf_len) < 0
10346 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10347 || packet_ok (rs->buf, packet) != PACKET_OK)
10348 return TARGET_XFER_E_IO;
10349
10350 unpack_varlen_hex (rs->buf, &n);
10351
10352 *xfered_len = n;
10353 return TARGET_XFER_OK;
10354 }
10355
10356 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10357 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10358 number of bytes read is returned, or 0 for EOF, or -1 for error.
10359 The number of bytes read may be less than LEN without indicating an
10360 EOF. PACKET is checked and updated to indicate whether the remote
10361 target supports this object. */
10362
10363 static enum target_xfer_status
10364 remote_read_qxfer (struct target_ops *ops, const char *object_name,
10365 const char *annex,
10366 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10367 ULONGEST *xfered_len,
10368 struct packet_config *packet)
10369 {
10370 struct remote_state *rs = get_remote_state ();
10371 LONGEST i, n, packet_len;
10372
10373 if (packet->support == PACKET_DISABLE)
10374 return TARGET_XFER_E_IO;
10375
10376 /* Check whether we've cached an end-of-object packet that matches
10377 this request. */
10378 if (rs->finished_object)
10379 {
10380 if (strcmp (object_name, rs->finished_object) == 0
10381 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10382 && offset == rs->finished_offset)
10383 return TARGET_XFER_EOF;
10384
10385
10386 /* Otherwise, we're now reading something different. Discard
10387 the cache. */
10388 xfree (rs->finished_object);
10389 xfree (rs->finished_annex);
10390 rs->finished_object = NULL;
10391 rs->finished_annex = NULL;
10392 }
10393
10394 /* Request only enough to fit in a single packet. The actual data
10395 may not, since we don't know how much of it will need to be escaped;
10396 the target is free to respond with slightly less data. We subtract
10397 five to account for the response type and the protocol frame. */
10398 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10399 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10400 object_name, annex ? annex : "",
10401 phex_nz (offset, sizeof offset),
10402 phex_nz (n, sizeof n));
10403 i = putpkt (rs->buf);
10404 if (i < 0)
10405 return TARGET_XFER_E_IO;
10406
10407 rs->buf[0] = '\0';
10408 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10409 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10410 return TARGET_XFER_E_IO;
10411
10412 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10413 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10414
10415 /* 'm' means there is (or at least might be) more data after this
10416 batch. That does not make sense unless there's at least one byte
10417 of data in this reply. */
10418 if (rs->buf[0] == 'm' && packet_len == 1)
10419 error (_("Remote qXfer reply contained no data."));
10420
10421 /* Got some data. */
10422 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10423 packet_len - 1, readbuf, n);
10424
10425 /* 'l' is an EOF marker, possibly including a final block of data,
10426 or possibly empty. If we have the final block of a non-empty
10427 object, record this fact to bypass a subsequent partial read. */
10428 if (rs->buf[0] == 'l' && offset + i > 0)
10429 {
10430 rs->finished_object = xstrdup (object_name);
10431 rs->finished_annex = xstrdup (annex ? annex : "");
10432 rs->finished_offset = offset + i;
10433 }
10434
10435 if (i == 0)
10436 return TARGET_XFER_EOF;
10437 else
10438 {
10439 *xfered_len = i;
10440 return TARGET_XFER_OK;
10441 }
10442 }
10443
10444 static enum target_xfer_status
10445 remote_xfer_partial (struct target_ops *ops, enum target_object object,
10446 const char *annex, gdb_byte *readbuf,
10447 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10448 ULONGEST *xfered_len)
10449 {
10450 struct remote_state *rs;
10451 int i;
10452 char *p2;
10453 char query_type;
10454 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10455
10456 set_remote_traceframe ();
10457 set_general_thread (inferior_ptid);
10458
10459 rs = get_remote_state ();
10460
10461 /* Handle memory using the standard memory routines. */
10462 if (object == TARGET_OBJECT_MEMORY)
10463 {
10464 /* If the remote target is connected but not running, we should
10465 pass this request down to a lower stratum (e.g. the executable
10466 file). */
10467 if (!target_has_execution)
10468 return TARGET_XFER_EOF;
10469
10470 if (writebuf != NULL)
10471 return remote_write_bytes (offset, writebuf, len, unit_size,
10472 xfered_len);
10473 else
10474 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10475 xfered_len);
10476 }
10477
10478 /* Handle SPU memory using qxfer packets. */
10479 if (object == TARGET_OBJECT_SPU)
10480 {
10481 if (readbuf)
10482 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
10483 xfered_len, &remote_protocol_packets
10484 [PACKET_qXfer_spu_read]);
10485 else
10486 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
10487 xfered_len, &remote_protocol_packets
10488 [PACKET_qXfer_spu_write]);
10489 }
10490
10491 /* Handle extra signal info using qxfer packets. */
10492 if (object == TARGET_OBJECT_SIGNAL_INFO)
10493 {
10494 if (readbuf)
10495 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10496 xfered_len, &remote_protocol_packets
10497 [PACKET_qXfer_siginfo_read]);
10498 else
10499 return remote_write_qxfer (ops, "siginfo", annex,
10500 writebuf, offset, len, xfered_len,
10501 &remote_protocol_packets
10502 [PACKET_qXfer_siginfo_write]);
10503 }
10504
10505 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10506 {
10507 if (readbuf)
10508 return remote_read_qxfer (ops, "statictrace", annex,
10509 readbuf, offset, len, xfered_len,
10510 &remote_protocol_packets
10511 [PACKET_qXfer_statictrace_read]);
10512 else
10513 return TARGET_XFER_E_IO;
10514 }
10515
10516 /* Only handle flash writes. */
10517 if (writebuf != NULL)
10518 {
10519 switch (object)
10520 {
10521 case TARGET_OBJECT_FLASH:
10522 return remote_flash_write (ops, offset, len, xfered_len,
10523 writebuf);
10524
10525 default:
10526 return TARGET_XFER_E_IO;
10527 }
10528 }
10529
10530 /* Map pre-existing objects onto letters. DO NOT do this for new
10531 objects!!! Instead specify new query packets. */
10532 switch (object)
10533 {
10534 case TARGET_OBJECT_AVR:
10535 query_type = 'R';
10536 break;
10537
10538 case TARGET_OBJECT_AUXV:
10539 gdb_assert (annex == NULL);
10540 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10541 xfered_len,
10542 &remote_protocol_packets[PACKET_qXfer_auxv]);
10543
10544 case TARGET_OBJECT_AVAILABLE_FEATURES:
10545 return remote_read_qxfer
10546 (ops, "features", annex, readbuf, offset, len, xfered_len,
10547 &remote_protocol_packets[PACKET_qXfer_features]);
10548
10549 case TARGET_OBJECT_LIBRARIES:
10550 return remote_read_qxfer
10551 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10552 &remote_protocol_packets[PACKET_qXfer_libraries]);
10553
10554 case TARGET_OBJECT_LIBRARIES_SVR4:
10555 return remote_read_qxfer
10556 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10557 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10558
10559 case TARGET_OBJECT_MEMORY_MAP:
10560 gdb_assert (annex == NULL);
10561 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10562 xfered_len,
10563 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10564
10565 case TARGET_OBJECT_OSDATA:
10566 /* Should only get here if we're connected. */
10567 gdb_assert (rs->remote_desc);
10568 return remote_read_qxfer
10569 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10570 &remote_protocol_packets[PACKET_qXfer_osdata]);
10571
10572 case TARGET_OBJECT_THREADS:
10573 gdb_assert (annex == NULL);
10574 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10575 xfered_len,
10576 &remote_protocol_packets[PACKET_qXfer_threads]);
10577
10578 case TARGET_OBJECT_TRACEFRAME_INFO:
10579 gdb_assert (annex == NULL);
10580 return remote_read_qxfer
10581 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10582 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10583
10584 case TARGET_OBJECT_FDPIC:
10585 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10586 xfered_len,
10587 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10588
10589 case TARGET_OBJECT_OPENVMS_UIB:
10590 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10591 xfered_len,
10592 &remote_protocol_packets[PACKET_qXfer_uib]);
10593
10594 case TARGET_OBJECT_BTRACE:
10595 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10596 xfered_len,
10597 &remote_protocol_packets[PACKET_qXfer_btrace]);
10598
10599 case TARGET_OBJECT_BTRACE_CONF:
10600 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10601 len, xfered_len,
10602 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10603
10604 case TARGET_OBJECT_EXEC_FILE:
10605 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10606 len, xfered_len,
10607 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10608
10609 default:
10610 return TARGET_XFER_E_IO;
10611 }
10612
10613 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10614 large enough let the caller deal with it. */
10615 if (len < get_remote_packet_size ())
10616 return TARGET_XFER_E_IO;
10617 len = get_remote_packet_size ();
10618
10619 /* Except for querying the minimum buffer size, target must be open. */
10620 if (!rs->remote_desc)
10621 error (_("remote query is only available after target open"));
10622
10623 gdb_assert (annex != NULL);
10624 gdb_assert (readbuf != NULL);
10625
10626 p2 = rs->buf;
10627 *p2++ = 'q';
10628 *p2++ = query_type;
10629
10630 /* We used one buffer char for the remote protocol q command and
10631 another for the query type. As the remote protocol encapsulation
10632 uses 4 chars plus one extra in case we are debugging
10633 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10634 string. */
10635 i = 0;
10636 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10637 {
10638 /* Bad caller may have sent forbidden characters. */
10639 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10640 *p2++ = annex[i];
10641 i++;
10642 }
10643 *p2 = '\0';
10644 gdb_assert (annex[i] == '\0');
10645
10646 i = putpkt (rs->buf);
10647 if (i < 0)
10648 return TARGET_XFER_E_IO;
10649
10650 getpkt (&rs->buf, &rs->buf_size, 0);
10651 strcpy ((char *) readbuf, rs->buf);
10652
10653 *xfered_len = strlen ((char *) readbuf);
10654 return TARGET_XFER_OK;
10655 }
10656
10657 /* Implementation of to_get_memory_xfer_limit. */
10658
10659 static ULONGEST
10660 remote_get_memory_xfer_limit (struct target_ops *ops)
10661 {
10662 return get_memory_write_packet_size ();
10663 }
10664
10665 static int
10666 remote_search_memory (struct target_ops* ops,
10667 CORE_ADDR start_addr, ULONGEST search_space_len,
10668 const gdb_byte *pattern, ULONGEST pattern_len,
10669 CORE_ADDR *found_addrp)
10670 {
10671 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10672 struct remote_state *rs = get_remote_state ();
10673 int max_size = get_memory_write_packet_size ();
10674 struct packet_config *packet =
10675 &remote_protocol_packets[PACKET_qSearch_memory];
10676 /* Number of packet bytes used to encode the pattern;
10677 this could be more than PATTERN_LEN due to escape characters. */
10678 int escaped_pattern_len;
10679 /* Amount of pattern that was encodable in the packet. */
10680 int used_pattern_len;
10681 int i;
10682 int found;
10683 ULONGEST found_addr;
10684
10685 /* Don't go to the target if we don't have to.
10686 This is done before checking packet->support to avoid the possibility that
10687 a success for this edge case means the facility works in general. */
10688 if (pattern_len > search_space_len)
10689 return 0;
10690 if (pattern_len == 0)
10691 {
10692 *found_addrp = start_addr;
10693 return 1;
10694 }
10695
10696 /* If we already know the packet isn't supported, fall back to the simple
10697 way of searching memory. */
10698
10699 if (packet_config_support (packet) == PACKET_DISABLE)
10700 {
10701 /* Target doesn't provided special support, fall back and use the
10702 standard support (copy memory and do the search here). */
10703 return simple_search_memory (ops, start_addr, search_space_len,
10704 pattern, pattern_len, found_addrp);
10705 }
10706
10707 /* Make sure the remote is pointing at the right process. */
10708 set_general_process ();
10709
10710 /* Insert header. */
10711 i = snprintf (rs->buf, max_size,
10712 "qSearch:memory:%s;%s;",
10713 phex_nz (start_addr, addr_size),
10714 phex_nz (search_space_len, sizeof (search_space_len)));
10715 max_size -= (i + 1);
10716
10717 /* Escape as much data as fits into rs->buf. */
10718 escaped_pattern_len =
10719 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10720 &used_pattern_len, max_size);
10721
10722 /* Bail if the pattern is too large. */
10723 if (used_pattern_len != pattern_len)
10724 error (_("Pattern is too large to transmit to remote target."));
10725
10726 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10727 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10728 || packet_ok (rs->buf, packet) != PACKET_OK)
10729 {
10730 /* The request may not have worked because the command is not
10731 supported. If so, fall back to the simple way. */
10732 if (packet->support == PACKET_DISABLE)
10733 {
10734 return simple_search_memory (ops, start_addr, search_space_len,
10735 pattern, pattern_len, found_addrp);
10736 }
10737 return -1;
10738 }
10739
10740 if (rs->buf[0] == '0')
10741 found = 0;
10742 else if (rs->buf[0] == '1')
10743 {
10744 found = 1;
10745 if (rs->buf[1] != ',')
10746 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10747 unpack_varlen_hex (rs->buf + 2, &found_addr);
10748 *found_addrp = found_addr;
10749 }
10750 else
10751 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10752
10753 return found;
10754 }
10755
10756 static void
10757 remote_rcmd (struct target_ops *self, const char *command,
10758 struct ui_file *outbuf)
10759 {
10760 struct remote_state *rs = get_remote_state ();
10761 char *p = rs->buf;
10762
10763 if (!rs->remote_desc)
10764 error (_("remote rcmd is only available after target open"));
10765
10766 /* Send a NULL command across as an empty command. */
10767 if (command == NULL)
10768 command = "";
10769
10770 /* The query prefix. */
10771 strcpy (rs->buf, "qRcmd,");
10772 p = strchr (rs->buf, '\0');
10773
10774 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10775 > get_remote_packet_size ())
10776 error (_("\"monitor\" command ``%s'' is too long."), command);
10777
10778 /* Encode the actual command. */
10779 bin2hex ((const gdb_byte *) command, p, strlen (command));
10780
10781 if (putpkt (rs->buf) < 0)
10782 error (_("Communication problem with target."));
10783
10784 /* get/display the response */
10785 while (1)
10786 {
10787 char *buf;
10788
10789 /* XXX - see also remote_get_noisy_reply(). */
10790 QUIT; /* Allow user to bail out with ^C. */
10791 rs->buf[0] = '\0';
10792 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10793 {
10794 /* Timeout. Continue to (try to) read responses.
10795 This is better than stopping with an error, assuming the stub
10796 is still executing the (long) monitor command.
10797 If needed, the user can interrupt gdb using C-c, obtaining
10798 an effect similar to stop on timeout. */
10799 continue;
10800 }
10801 buf = rs->buf;
10802 if (buf[0] == '\0')
10803 error (_("Target does not support this command."));
10804 if (buf[0] == 'O' && buf[1] != 'K')
10805 {
10806 remote_console_output (buf + 1); /* 'O' message from stub. */
10807 continue;
10808 }
10809 if (strcmp (buf, "OK") == 0)
10810 break;
10811 if (strlen (buf) == 3 && buf[0] == 'E'
10812 && isdigit (buf[1]) && isdigit (buf[2]))
10813 {
10814 error (_("Protocol error with Rcmd"));
10815 }
10816 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10817 {
10818 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10819
10820 fputc_unfiltered (c, outbuf);
10821 }
10822 break;
10823 }
10824 }
10825
10826 static VEC(mem_region_s) *
10827 remote_memory_map (struct target_ops *ops)
10828 {
10829 VEC(mem_region_s) *result = NULL;
10830 char *text = target_read_stralloc (&current_target,
10831 TARGET_OBJECT_MEMORY_MAP, NULL);
10832
10833 if (text)
10834 {
10835 struct cleanup *back_to = make_cleanup (xfree, text);
10836
10837 result = parse_memory_map (text);
10838 do_cleanups (back_to);
10839 }
10840
10841 return result;
10842 }
10843
10844 static void
10845 packet_command (const char *args, int from_tty)
10846 {
10847 struct remote_state *rs = get_remote_state ();
10848
10849 if (!rs->remote_desc)
10850 error (_("command can only be used with remote target"));
10851
10852 if (!args)
10853 error (_("remote-packet command requires packet text as argument"));
10854
10855 puts_filtered ("sending: ");
10856 print_packet (args);
10857 puts_filtered ("\n");
10858 putpkt (args);
10859
10860 getpkt (&rs->buf, &rs->buf_size, 0);
10861 puts_filtered ("received: ");
10862 print_packet (rs->buf);
10863 puts_filtered ("\n");
10864 }
10865
10866 #if 0
10867 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10868
10869 static void display_thread_info (struct gdb_ext_thread_info *info);
10870
10871 static void threadset_test_cmd (char *cmd, int tty);
10872
10873 static void threadalive_test (char *cmd, int tty);
10874
10875 static void threadlist_test_cmd (char *cmd, int tty);
10876
10877 int get_and_display_threadinfo (threadref *ref);
10878
10879 static void threadinfo_test_cmd (char *cmd, int tty);
10880
10881 static int thread_display_step (threadref *ref, void *context);
10882
10883 static void threadlist_update_test_cmd (char *cmd, int tty);
10884
10885 static void init_remote_threadtests (void);
10886
10887 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10888
10889 static void
10890 threadset_test_cmd (char *cmd, int tty)
10891 {
10892 int sample_thread = SAMPLE_THREAD;
10893
10894 printf_filtered (_("Remote threadset test\n"));
10895 set_general_thread (sample_thread);
10896 }
10897
10898
10899 static void
10900 threadalive_test (char *cmd, int tty)
10901 {
10902 int sample_thread = SAMPLE_THREAD;
10903 int pid = ptid_get_pid (inferior_ptid);
10904 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10905
10906 if (remote_thread_alive (ptid))
10907 printf_filtered ("PASS: Thread alive test\n");
10908 else
10909 printf_filtered ("FAIL: Thread alive test\n");
10910 }
10911
10912 void output_threadid (char *title, threadref *ref);
10913
10914 void
10915 output_threadid (char *title, threadref *ref)
10916 {
10917 char hexid[20];
10918
10919 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10920 hexid[16] = 0;
10921 printf_filtered ("%s %s\n", title, (&hexid[0]));
10922 }
10923
10924 static void
10925 threadlist_test_cmd (char *cmd, int tty)
10926 {
10927 int startflag = 1;
10928 threadref nextthread;
10929 int done, result_count;
10930 threadref threadlist[3];
10931
10932 printf_filtered ("Remote Threadlist test\n");
10933 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10934 &result_count, &threadlist[0]))
10935 printf_filtered ("FAIL: threadlist test\n");
10936 else
10937 {
10938 threadref *scan = threadlist;
10939 threadref *limit = scan + result_count;
10940
10941 while (scan < limit)
10942 output_threadid (" thread ", scan++);
10943 }
10944 }
10945
10946 void
10947 display_thread_info (struct gdb_ext_thread_info *info)
10948 {
10949 output_threadid ("Threadid: ", &info->threadid);
10950 printf_filtered ("Name: %s\n ", info->shortname);
10951 printf_filtered ("State: %s\n", info->display);
10952 printf_filtered ("other: %s\n\n", info->more_display);
10953 }
10954
10955 int
10956 get_and_display_threadinfo (threadref *ref)
10957 {
10958 int result;
10959 int set;
10960 struct gdb_ext_thread_info threadinfo;
10961
10962 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10963 | TAG_MOREDISPLAY | TAG_DISPLAY;
10964 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10965 display_thread_info (&threadinfo);
10966 return result;
10967 }
10968
10969 static void
10970 threadinfo_test_cmd (char *cmd, int tty)
10971 {
10972 int athread = SAMPLE_THREAD;
10973 threadref thread;
10974 int set;
10975
10976 int_to_threadref (&thread, athread);
10977 printf_filtered ("Remote Threadinfo test\n");
10978 if (!get_and_display_threadinfo (&thread))
10979 printf_filtered ("FAIL cannot get thread info\n");
10980 }
10981
10982 static int
10983 thread_display_step (threadref *ref, void *context)
10984 {
10985 /* output_threadid(" threadstep ",ref); *//* simple test */
10986 return get_and_display_threadinfo (ref);
10987 }
10988
10989 static void
10990 threadlist_update_test_cmd (char *cmd, int tty)
10991 {
10992 printf_filtered ("Remote Threadlist update test\n");
10993 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10994 }
10995
10996 static void
10997 init_remote_threadtests (void)
10998 {
10999 add_com ("tlist", class_obscure, threadlist_test_cmd,
11000 _("Fetch and print the remote list of "
11001 "thread identifiers, one pkt only"));
11002 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11003 _("Fetch and display info about one thread"));
11004 add_com ("tset", class_obscure, threadset_test_cmd,
11005 _("Test setting to a different thread"));
11006 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11007 _("Iterate through updating all remote thread info"));
11008 add_com ("talive", class_obscure, threadalive_test,
11009 _(" Remote thread alive test "));
11010 }
11011
11012 #endif /* 0 */
11013
11014 /* Convert a thread ID to a string. Returns the string in a static
11015 buffer. */
11016
11017 static const char *
11018 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
11019 {
11020 static char buf[64];
11021 struct remote_state *rs = get_remote_state ();
11022
11023 if (ptid_equal (ptid, null_ptid))
11024 return normal_pid_to_str (ptid);
11025 else if (ptid_is_pid (ptid))
11026 {
11027 /* Printing an inferior target id. */
11028
11029 /* When multi-process extensions are off, there's no way in the
11030 remote protocol to know the remote process id, if there's any
11031 at all. There's one exception --- when we're connected with
11032 target extended-remote, and we manually attached to a process
11033 with "attach PID". We don't record anywhere a flag that
11034 allows us to distinguish that case from the case of
11035 connecting with extended-remote and the stub already being
11036 attached to a process, and reporting yes to qAttached, hence
11037 no smart special casing here. */
11038 if (!remote_multi_process_p (rs))
11039 {
11040 xsnprintf (buf, sizeof buf, "Remote target");
11041 return buf;
11042 }
11043
11044 return normal_pid_to_str (ptid);
11045 }
11046 else
11047 {
11048 if (ptid_equal (magic_null_ptid, ptid))
11049 xsnprintf (buf, sizeof buf, "Thread <main>");
11050 else if (remote_multi_process_p (rs))
11051 if (ptid_get_lwp (ptid) == 0)
11052 return normal_pid_to_str (ptid);
11053 else
11054 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11055 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11056 else
11057 xsnprintf (buf, sizeof buf, "Thread %ld",
11058 ptid_get_lwp (ptid));
11059 return buf;
11060 }
11061 }
11062
11063 /* Get the address of the thread local variable in OBJFILE which is
11064 stored at OFFSET within the thread local storage for thread PTID. */
11065
11066 static CORE_ADDR
11067 remote_get_thread_local_address (struct target_ops *ops,
11068 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
11069 {
11070 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11071 {
11072 struct remote_state *rs = get_remote_state ();
11073 char *p = rs->buf;
11074 char *endp = rs->buf + get_remote_packet_size ();
11075 enum packet_result result;
11076
11077 strcpy (p, "qGetTLSAddr:");
11078 p += strlen (p);
11079 p = write_ptid (p, endp, ptid);
11080 *p++ = ',';
11081 p += hexnumstr (p, offset);
11082 *p++ = ',';
11083 p += hexnumstr (p, lm);
11084 *p++ = '\0';
11085
11086 putpkt (rs->buf);
11087 getpkt (&rs->buf, &rs->buf_size, 0);
11088 result = packet_ok (rs->buf,
11089 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11090 if (result == PACKET_OK)
11091 {
11092 ULONGEST result;
11093
11094 unpack_varlen_hex (rs->buf, &result);
11095 return result;
11096 }
11097 else if (result == PACKET_UNKNOWN)
11098 throw_error (TLS_GENERIC_ERROR,
11099 _("Remote target doesn't support qGetTLSAddr packet"));
11100 else
11101 throw_error (TLS_GENERIC_ERROR,
11102 _("Remote target failed to process qGetTLSAddr request"));
11103 }
11104 else
11105 throw_error (TLS_GENERIC_ERROR,
11106 _("TLS not supported or disabled on this target"));
11107 /* Not reached. */
11108 return 0;
11109 }
11110
11111 /* Provide thread local base, i.e. Thread Information Block address.
11112 Returns 1 if ptid is found and thread_local_base is non zero. */
11113
11114 static int
11115 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
11116 {
11117 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11118 {
11119 struct remote_state *rs = get_remote_state ();
11120 char *p = rs->buf;
11121 char *endp = rs->buf + get_remote_packet_size ();
11122 enum packet_result result;
11123
11124 strcpy (p, "qGetTIBAddr:");
11125 p += strlen (p);
11126 p = write_ptid (p, endp, ptid);
11127 *p++ = '\0';
11128
11129 putpkt (rs->buf);
11130 getpkt (&rs->buf, &rs->buf_size, 0);
11131 result = packet_ok (rs->buf,
11132 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11133 if (result == PACKET_OK)
11134 {
11135 ULONGEST result;
11136
11137 unpack_varlen_hex (rs->buf, &result);
11138 if (addr)
11139 *addr = (CORE_ADDR) result;
11140 return 1;
11141 }
11142 else if (result == PACKET_UNKNOWN)
11143 error (_("Remote target doesn't support qGetTIBAddr packet"));
11144 else
11145 error (_("Remote target failed to process qGetTIBAddr request"));
11146 }
11147 else
11148 error (_("qGetTIBAddr not supported or disabled on this target"));
11149 /* Not reached. */
11150 return 0;
11151 }
11152
11153 /* Support for inferring a target description based on the current
11154 architecture and the size of a 'g' packet. While the 'g' packet
11155 can have any size (since optional registers can be left off the
11156 end), some sizes are easily recognizable given knowledge of the
11157 approximate architecture. */
11158
11159 struct remote_g_packet_guess
11160 {
11161 int bytes;
11162 const struct target_desc *tdesc;
11163 };
11164 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11165 DEF_VEC_O(remote_g_packet_guess_s);
11166
11167 struct remote_g_packet_data
11168 {
11169 VEC(remote_g_packet_guess_s) *guesses;
11170 };
11171
11172 static struct gdbarch_data *remote_g_packet_data_handle;
11173
11174 static void *
11175 remote_g_packet_data_init (struct obstack *obstack)
11176 {
11177 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11178 }
11179
11180 void
11181 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11182 const struct target_desc *tdesc)
11183 {
11184 struct remote_g_packet_data *data
11185 = ((struct remote_g_packet_data *)
11186 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11187 struct remote_g_packet_guess new_guess, *guess;
11188 int ix;
11189
11190 gdb_assert (tdesc != NULL);
11191
11192 for (ix = 0;
11193 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11194 ix++)
11195 if (guess->bytes == bytes)
11196 internal_error (__FILE__, __LINE__,
11197 _("Duplicate g packet description added for size %d"),
11198 bytes);
11199
11200 new_guess.bytes = bytes;
11201 new_guess.tdesc = tdesc;
11202 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11203 }
11204
11205 /* Return 1 if remote_read_description would do anything on this target
11206 and architecture, 0 otherwise. */
11207
11208 static int
11209 remote_read_description_p (struct target_ops *target)
11210 {
11211 struct remote_g_packet_data *data
11212 = ((struct remote_g_packet_data *)
11213 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11214
11215 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11216 return 1;
11217
11218 return 0;
11219 }
11220
11221 static const struct target_desc *
11222 remote_read_description (struct target_ops *target)
11223 {
11224 struct remote_g_packet_data *data
11225 = ((struct remote_g_packet_data *)
11226 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11227
11228 /* Do not try this during initial connection, when we do not know
11229 whether there is a running but stopped thread. */
11230 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11231 return target->beneath->to_read_description (target->beneath);
11232
11233 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11234 {
11235 struct remote_g_packet_guess *guess;
11236 int ix;
11237 int bytes = send_g_packet ();
11238
11239 for (ix = 0;
11240 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11241 ix++)
11242 if (guess->bytes == bytes)
11243 return guess->tdesc;
11244
11245 /* We discard the g packet. A minor optimization would be to
11246 hold on to it, and fill the register cache once we have selected
11247 an architecture, but it's too tricky to do safely. */
11248 }
11249
11250 return target->beneath->to_read_description (target->beneath);
11251 }
11252
11253 /* Remote file transfer support. This is host-initiated I/O, not
11254 target-initiated; for target-initiated, see remote-fileio.c. */
11255
11256 /* If *LEFT is at least the length of STRING, copy STRING to
11257 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11258 decrease *LEFT. Otherwise raise an error. */
11259
11260 static void
11261 remote_buffer_add_string (char **buffer, int *left, const char *string)
11262 {
11263 int len = strlen (string);
11264
11265 if (len > *left)
11266 error (_("Packet too long for target."));
11267
11268 memcpy (*buffer, string, len);
11269 *buffer += len;
11270 *left -= len;
11271
11272 /* NUL-terminate the buffer as a convenience, if there is
11273 room. */
11274 if (*left)
11275 **buffer = '\0';
11276 }
11277
11278 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11279 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11280 decrease *LEFT. Otherwise raise an error. */
11281
11282 static void
11283 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11284 int len)
11285 {
11286 if (2 * len > *left)
11287 error (_("Packet too long for target."));
11288
11289 bin2hex (bytes, *buffer, len);
11290 *buffer += 2 * len;
11291 *left -= 2 * len;
11292
11293 /* NUL-terminate the buffer as a convenience, if there is
11294 room. */
11295 if (*left)
11296 **buffer = '\0';
11297 }
11298
11299 /* If *LEFT is large enough, convert VALUE to hex and add it to
11300 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11301 decrease *LEFT. Otherwise raise an error. */
11302
11303 static void
11304 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11305 {
11306 int len = hexnumlen (value);
11307
11308 if (len > *left)
11309 error (_("Packet too long for target."));
11310
11311 hexnumstr (*buffer, value);
11312 *buffer += len;
11313 *left -= len;
11314
11315 /* NUL-terminate the buffer as a convenience, if there is
11316 room. */
11317 if (*left)
11318 **buffer = '\0';
11319 }
11320
11321 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11322 value, *REMOTE_ERRNO to the remote error number or zero if none
11323 was included, and *ATTACHMENT to point to the start of the annex
11324 if any. The length of the packet isn't needed here; there may
11325 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11326
11327 Return 0 if the packet could be parsed, -1 if it could not. If
11328 -1 is returned, the other variables may not be initialized. */
11329
11330 static int
11331 remote_hostio_parse_result (char *buffer, int *retcode,
11332 int *remote_errno, char **attachment)
11333 {
11334 char *p, *p2;
11335
11336 *remote_errno = 0;
11337 *attachment = NULL;
11338
11339 if (buffer[0] != 'F')
11340 return -1;
11341
11342 errno = 0;
11343 *retcode = strtol (&buffer[1], &p, 16);
11344 if (errno != 0 || p == &buffer[1])
11345 return -1;
11346
11347 /* Check for ",errno". */
11348 if (*p == ',')
11349 {
11350 errno = 0;
11351 *remote_errno = strtol (p + 1, &p2, 16);
11352 if (errno != 0 || p + 1 == p2)
11353 return -1;
11354 p = p2;
11355 }
11356
11357 /* Check for ";attachment". If there is no attachment, the
11358 packet should end here. */
11359 if (*p == ';')
11360 {
11361 *attachment = p + 1;
11362 return 0;
11363 }
11364 else if (*p == '\0')
11365 return 0;
11366 else
11367 return -1;
11368 }
11369
11370 /* Send a prepared I/O packet to the target and read its response.
11371 The prepared packet is in the global RS->BUF before this function
11372 is called, and the answer is there when we return.
11373
11374 COMMAND_BYTES is the length of the request to send, which may include
11375 binary data. WHICH_PACKET is the packet configuration to check
11376 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11377 is set to the error number and -1 is returned. Otherwise the value
11378 returned by the function is returned.
11379
11380 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11381 attachment is expected; an error will be reported if there's a
11382 mismatch. If one is found, *ATTACHMENT will be set to point into
11383 the packet buffer and *ATTACHMENT_LEN will be set to the
11384 attachment's length. */
11385
11386 static int
11387 remote_hostio_send_command (int command_bytes, int which_packet,
11388 int *remote_errno, char **attachment,
11389 int *attachment_len)
11390 {
11391 struct remote_state *rs = get_remote_state ();
11392 int ret, bytes_read;
11393 char *attachment_tmp;
11394
11395 if (!rs->remote_desc
11396 || packet_support (which_packet) == PACKET_DISABLE)
11397 {
11398 *remote_errno = FILEIO_ENOSYS;
11399 return -1;
11400 }
11401
11402 putpkt_binary (rs->buf, command_bytes);
11403 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11404
11405 /* If it timed out, something is wrong. Don't try to parse the
11406 buffer. */
11407 if (bytes_read < 0)
11408 {
11409 *remote_errno = FILEIO_EINVAL;
11410 return -1;
11411 }
11412
11413 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11414 {
11415 case PACKET_ERROR:
11416 *remote_errno = FILEIO_EINVAL;
11417 return -1;
11418 case PACKET_UNKNOWN:
11419 *remote_errno = FILEIO_ENOSYS;
11420 return -1;
11421 case PACKET_OK:
11422 break;
11423 }
11424
11425 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11426 &attachment_tmp))
11427 {
11428 *remote_errno = FILEIO_EINVAL;
11429 return -1;
11430 }
11431
11432 /* Make sure we saw an attachment if and only if we expected one. */
11433 if ((attachment_tmp == NULL && attachment != NULL)
11434 || (attachment_tmp != NULL && attachment == NULL))
11435 {
11436 *remote_errno = FILEIO_EINVAL;
11437 return -1;
11438 }
11439
11440 /* If an attachment was found, it must point into the packet buffer;
11441 work out how many bytes there were. */
11442 if (attachment_tmp != NULL)
11443 {
11444 *attachment = attachment_tmp;
11445 *attachment_len = bytes_read - (*attachment - rs->buf);
11446 }
11447
11448 return ret;
11449 }
11450
11451 /* Invalidate the readahead cache. */
11452
11453 static void
11454 readahead_cache_invalidate (void)
11455 {
11456 struct remote_state *rs = get_remote_state ();
11457
11458 rs->readahead_cache.fd = -1;
11459 }
11460
11461 /* Invalidate the readahead cache if it is holding data for FD. */
11462
11463 static void
11464 readahead_cache_invalidate_fd (int fd)
11465 {
11466 struct remote_state *rs = get_remote_state ();
11467
11468 if (rs->readahead_cache.fd == fd)
11469 rs->readahead_cache.fd = -1;
11470 }
11471
11472 /* Set the filesystem remote_hostio functions that take FILENAME
11473 arguments will use. Return 0 on success, or -1 if an error
11474 occurs (and set *REMOTE_ERRNO). */
11475
11476 static int
11477 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11478 {
11479 struct remote_state *rs = get_remote_state ();
11480 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11481 char *p = rs->buf;
11482 int left = get_remote_packet_size () - 1;
11483 char arg[9];
11484 int ret;
11485
11486 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11487 return 0;
11488
11489 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11490 return 0;
11491
11492 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11493
11494 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11495 remote_buffer_add_string (&p, &left, arg);
11496
11497 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11498 remote_errno, NULL, NULL);
11499
11500 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11501 return 0;
11502
11503 if (ret == 0)
11504 rs->fs_pid = required_pid;
11505
11506 return ret;
11507 }
11508
11509 /* Implementation of to_fileio_open. */
11510
11511 static int
11512 remote_hostio_open (struct target_ops *self,
11513 struct inferior *inf, const char *filename,
11514 int flags, int mode, int warn_if_slow,
11515 int *remote_errno)
11516 {
11517 struct remote_state *rs = get_remote_state ();
11518 char *p = rs->buf;
11519 int left = get_remote_packet_size () - 1;
11520
11521 if (warn_if_slow)
11522 {
11523 static int warning_issued = 0;
11524
11525 printf_unfiltered (_("Reading %s from remote target...\n"),
11526 filename);
11527
11528 if (!warning_issued)
11529 {
11530 warning (_("File transfers from remote targets can be slow."
11531 " Use \"set sysroot\" to access files locally"
11532 " instead."));
11533 warning_issued = 1;
11534 }
11535 }
11536
11537 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11538 return -1;
11539
11540 remote_buffer_add_string (&p, &left, "vFile:open:");
11541
11542 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11543 strlen (filename));
11544 remote_buffer_add_string (&p, &left, ",");
11545
11546 remote_buffer_add_int (&p, &left, flags);
11547 remote_buffer_add_string (&p, &left, ",");
11548
11549 remote_buffer_add_int (&p, &left, mode);
11550
11551 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11552 remote_errno, NULL, NULL);
11553 }
11554
11555 /* Implementation of to_fileio_pwrite. */
11556
11557 static int
11558 remote_hostio_pwrite (struct target_ops *self,
11559 int fd, const gdb_byte *write_buf, int len,
11560 ULONGEST offset, int *remote_errno)
11561 {
11562 struct remote_state *rs = get_remote_state ();
11563 char *p = rs->buf;
11564 int left = get_remote_packet_size ();
11565 int out_len;
11566
11567 readahead_cache_invalidate_fd (fd);
11568
11569 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11570
11571 remote_buffer_add_int (&p, &left, fd);
11572 remote_buffer_add_string (&p, &left, ",");
11573
11574 remote_buffer_add_int (&p, &left, offset);
11575 remote_buffer_add_string (&p, &left, ",");
11576
11577 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11578 get_remote_packet_size () - (p - rs->buf));
11579
11580 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11581 remote_errno, NULL, NULL);
11582 }
11583
11584 /* Helper for the implementation of to_fileio_pread. Read the file
11585 from the remote side with vFile:pread. */
11586
11587 static int
11588 remote_hostio_pread_vFile (struct target_ops *self,
11589 int fd, gdb_byte *read_buf, int len,
11590 ULONGEST offset, int *remote_errno)
11591 {
11592 struct remote_state *rs = get_remote_state ();
11593 char *p = rs->buf;
11594 char *attachment;
11595 int left = get_remote_packet_size ();
11596 int ret, attachment_len;
11597 int read_len;
11598
11599 remote_buffer_add_string (&p, &left, "vFile:pread:");
11600
11601 remote_buffer_add_int (&p, &left, fd);
11602 remote_buffer_add_string (&p, &left, ",");
11603
11604 remote_buffer_add_int (&p, &left, len);
11605 remote_buffer_add_string (&p, &left, ",");
11606
11607 remote_buffer_add_int (&p, &left, offset);
11608
11609 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11610 remote_errno, &attachment,
11611 &attachment_len);
11612
11613 if (ret < 0)
11614 return ret;
11615
11616 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11617 read_buf, len);
11618 if (read_len != ret)
11619 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11620
11621 return ret;
11622 }
11623
11624 /* Serve pread from the readahead cache. Returns number of bytes
11625 read, or 0 if the request can't be served from the cache. */
11626
11627 static int
11628 remote_hostio_pread_from_cache (struct remote_state *rs,
11629 int fd, gdb_byte *read_buf, size_t len,
11630 ULONGEST offset)
11631 {
11632 struct readahead_cache *cache = &rs->readahead_cache;
11633
11634 if (cache->fd == fd
11635 && cache->offset <= offset
11636 && offset < cache->offset + cache->bufsize)
11637 {
11638 ULONGEST max = cache->offset + cache->bufsize;
11639
11640 if (offset + len > max)
11641 len = max - offset;
11642
11643 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11644 return len;
11645 }
11646
11647 return 0;
11648 }
11649
11650 /* Implementation of to_fileio_pread. */
11651
11652 static int
11653 remote_hostio_pread (struct target_ops *self,
11654 int fd, gdb_byte *read_buf, int len,
11655 ULONGEST offset, int *remote_errno)
11656 {
11657 int ret;
11658 struct remote_state *rs = get_remote_state ();
11659 struct readahead_cache *cache = &rs->readahead_cache;
11660
11661 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11662 if (ret > 0)
11663 {
11664 cache->hit_count++;
11665
11666 if (remote_debug)
11667 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11668 pulongest (cache->hit_count));
11669 return ret;
11670 }
11671
11672 cache->miss_count++;
11673 if (remote_debug)
11674 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11675 pulongest (cache->miss_count));
11676
11677 cache->fd = fd;
11678 cache->offset = offset;
11679 cache->bufsize = get_remote_packet_size ();
11680 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11681
11682 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11683 cache->offset, remote_errno);
11684 if (ret <= 0)
11685 {
11686 readahead_cache_invalidate_fd (fd);
11687 return ret;
11688 }
11689
11690 cache->bufsize = ret;
11691 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11692 }
11693
11694 /* Implementation of to_fileio_close. */
11695
11696 static int
11697 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11698 {
11699 struct remote_state *rs = get_remote_state ();
11700 char *p = rs->buf;
11701 int left = get_remote_packet_size () - 1;
11702
11703 readahead_cache_invalidate_fd (fd);
11704
11705 remote_buffer_add_string (&p, &left, "vFile:close:");
11706
11707 remote_buffer_add_int (&p, &left, fd);
11708
11709 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11710 remote_errno, NULL, NULL);
11711 }
11712
11713 /* Implementation of to_fileio_unlink. */
11714
11715 static int
11716 remote_hostio_unlink (struct target_ops *self,
11717 struct inferior *inf, const char *filename,
11718 int *remote_errno)
11719 {
11720 struct remote_state *rs = get_remote_state ();
11721 char *p = rs->buf;
11722 int left = get_remote_packet_size () - 1;
11723
11724 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11725 return -1;
11726
11727 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11728
11729 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11730 strlen (filename));
11731
11732 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11733 remote_errno, NULL, NULL);
11734 }
11735
11736 /* Implementation of to_fileio_readlink. */
11737
11738 static char *
11739 remote_hostio_readlink (struct target_ops *self,
11740 struct inferior *inf, const char *filename,
11741 int *remote_errno)
11742 {
11743 struct remote_state *rs = get_remote_state ();
11744 char *p = rs->buf;
11745 char *attachment;
11746 int left = get_remote_packet_size ();
11747 int len, attachment_len;
11748 int read_len;
11749 char *ret;
11750
11751 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11752 return NULL;
11753
11754 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11755
11756 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11757 strlen (filename));
11758
11759 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11760 remote_errno, &attachment,
11761 &attachment_len);
11762
11763 if (len < 0)
11764 return NULL;
11765
11766 ret = (char *) xmalloc (len + 1);
11767
11768 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11769 (gdb_byte *) ret, len);
11770 if (read_len != len)
11771 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11772
11773 ret[len] = '\0';
11774 return ret;
11775 }
11776
11777 /* Implementation of to_fileio_fstat. */
11778
11779 static int
11780 remote_hostio_fstat (struct target_ops *self,
11781 int fd, struct stat *st,
11782 int *remote_errno)
11783 {
11784 struct remote_state *rs = get_remote_state ();
11785 char *p = rs->buf;
11786 int left = get_remote_packet_size ();
11787 int attachment_len, ret;
11788 char *attachment;
11789 struct fio_stat fst;
11790 int read_len;
11791
11792 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11793
11794 remote_buffer_add_int (&p, &left, fd);
11795
11796 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11797 remote_errno, &attachment,
11798 &attachment_len);
11799 if (ret < 0)
11800 {
11801 if (*remote_errno != FILEIO_ENOSYS)
11802 return ret;
11803
11804 /* Strictly we should return -1, ENOSYS here, but when
11805 "set sysroot remote:" was implemented in August 2008
11806 BFD's need for a stat function was sidestepped with
11807 this hack. This was not remedied until March 2015
11808 so we retain the previous behavior to avoid breaking
11809 compatibility.
11810
11811 Note that the memset is a March 2015 addition; older
11812 GDBs set st_size *and nothing else* so the structure
11813 would have garbage in all other fields. This might
11814 break something but retaining the previous behavior
11815 here would be just too wrong. */
11816
11817 memset (st, 0, sizeof (struct stat));
11818 st->st_size = INT_MAX;
11819 return 0;
11820 }
11821
11822 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11823 (gdb_byte *) &fst, sizeof (fst));
11824
11825 if (read_len != ret)
11826 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11827
11828 if (read_len != sizeof (fst))
11829 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11830 read_len, (int) sizeof (fst));
11831
11832 remote_fileio_to_host_stat (&fst, st);
11833
11834 return 0;
11835 }
11836
11837 /* Implementation of to_filesystem_is_local. */
11838
11839 static int
11840 remote_filesystem_is_local (struct target_ops *self)
11841 {
11842 /* Valgrind GDB presents itself as a remote target but works
11843 on the local filesystem: it does not implement remote get
11844 and users are not expected to set a sysroot. To handle
11845 this case we treat the remote filesystem as local if the
11846 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11847 does not support vFile:open. */
11848 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11849 {
11850 enum packet_support ps = packet_support (PACKET_vFile_open);
11851
11852 if (ps == PACKET_SUPPORT_UNKNOWN)
11853 {
11854 int fd, remote_errno;
11855
11856 /* Try opening a file to probe support. The supplied
11857 filename is irrelevant, we only care about whether
11858 the stub recognizes the packet or not. */
11859 fd = remote_hostio_open (self, NULL, "just probing",
11860 FILEIO_O_RDONLY, 0700, 0,
11861 &remote_errno);
11862
11863 if (fd >= 0)
11864 remote_hostio_close (self, fd, &remote_errno);
11865
11866 ps = packet_support (PACKET_vFile_open);
11867 }
11868
11869 if (ps == PACKET_DISABLE)
11870 {
11871 static int warning_issued = 0;
11872
11873 if (!warning_issued)
11874 {
11875 warning (_("remote target does not support file"
11876 " transfer, attempting to access files"
11877 " from local filesystem."));
11878 warning_issued = 1;
11879 }
11880
11881 return 1;
11882 }
11883 }
11884
11885 return 0;
11886 }
11887
11888 static int
11889 remote_fileio_errno_to_host (int errnum)
11890 {
11891 switch (errnum)
11892 {
11893 case FILEIO_EPERM:
11894 return EPERM;
11895 case FILEIO_ENOENT:
11896 return ENOENT;
11897 case FILEIO_EINTR:
11898 return EINTR;
11899 case FILEIO_EIO:
11900 return EIO;
11901 case FILEIO_EBADF:
11902 return EBADF;
11903 case FILEIO_EACCES:
11904 return EACCES;
11905 case FILEIO_EFAULT:
11906 return EFAULT;
11907 case FILEIO_EBUSY:
11908 return EBUSY;
11909 case FILEIO_EEXIST:
11910 return EEXIST;
11911 case FILEIO_ENODEV:
11912 return ENODEV;
11913 case FILEIO_ENOTDIR:
11914 return ENOTDIR;
11915 case FILEIO_EISDIR:
11916 return EISDIR;
11917 case FILEIO_EINVAL:
11918 return EINVAL;
11919 case FILEIO_ENFILE:
11920 return ENFILE;
11921 case FILEIO_EMFILE:
11922 return EMFILE;
11923 case FILEIO_EFBIG:
11924 return EFBIG;
11925 case FILEIO_ENOSPC:
11926 return ENOSPC;
11927 case FILEIO_ESPIPE:
11928 return ESPIPE;
11929 case FILEIO_EROFS:
11930 return EROFS;
11931 case FILEIO_ENOSYS:
11932 return ENOSYS;
11933 case FILEIO_ENAMETOOLONG:
11934 return ENAMETOOLONG;
11935 }
11936 return -1;
11937 }
11938
11939 static char *
11940 remote_hostio_error (int errnum)
11941 {
11942 int host_error = remote_fileio_errno_to_host (errnum);
11943
11944 if (host_error == -1)
11945 error (_("Unknown remote I/O error %d"), errnum);
11946 else
11947 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11948 }
11949
11950 static void
11951 remote_hostio_close_cleanup (void *opaque)
11952 {
11953 int fd = *(int *) opaque;
11954 int remote_errno;
11955
11956 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11957 }
11958
11959 void
11960 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11961 {
11962 struct cleanup *back_to, *close_cleanup;
11963 int retcode, fd, remote_errno, bytes, io_size;
11964 gdb_byte *buffer;
11965 int bytes_in_buffer;
11966 int saw_eof;
11967 ULONGEST offset;
11968 struct remote_state *rs = get_remote_state ();
11969
11970 if (!rs->remote_desc)
11971 error (_("command can only be used with remote target"));
11972
11973 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
11974 if (file == NULL)
11975 perror_with_name (local_file);
11976
11977 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11978 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11979 | FILEIO_O_TRUNC),
11980 0700, 0, &remote_errno);
11981 if (fd == -1)
11982 remote_hostio_error (remote_errno);
11983
11984 /* Send up to this many bytes at once. They won't all fit in the
11985 remote packet limit, so we'll transfer slightly fewer. */
11986 io_size = get_remote_packet_size ();
11987 buffer = (gdb_byte *) xmalloc (io_size);
11988 back_to = make_cleanup (xfree, buffer);
11989
11990 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11991
11992 bytes_in_buffer = 0;
11993 saw_eof = 0;
11994 offset = 0;
11995 while (bytes_in_buffer || !saw_eof)
11996 {
11997 if (!saw_eof)
11998 {
11999 bytes = fread (buffer + bytes_in_buffer, 1,
12000 io_size - bytes_in_buffer,
12001 file.get ());
12002 if (bytes == 0)
12003 {
12004 if (ferror (file.get ()))
12005 error (_("Error reading %s."), local_file);
12006 else
12007 {
12008 /* EOF. Unless there is something still in the
12009 buffer from the last iteration, we are done. */
12010 saw_eof = 1;
12011 if (bytes_in_buffer == 0)
12012 break;
12013 }
12014 }
12015 }
12016 else
12017 bytes = 0;
12018
12019 bytes += bytes_in_buffer;
12020 bytes_in_buffer = 0;
12021
12022 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12023 fd, buffer, bytes,
12024 offset, &remote_errno);
12025
12026 if (retcode < 0)
12027 remote_hostio_error (remote_errno);
12028 else if (retcode == 0)
12029 error (_("Remote write of %d bytes returned 0!"), bytes);
12030 else if (retcode < bytes)
12031 {
12032 /* Short write. Save the rest of the read data for the next
12033 write. */
12034 bytes_in_buffer = bytes - retcode;
12035 memmove (buffer, buffer + retcode, bytes_in_buffer);
12036 }
12037
12038 offset += retcode;
12039 }
12040
12041 discard_cleanups (close_cleanup);
12042 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12043 remote_hostio_error (remote_errno);
12044
12045 if (from_tty)
12046 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12047 do_cleanups (back_to);
12048 }
12049
12050 void
12051 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12052 {
12053 struct cleanup *back_to, *close_cleanup;
12054 int fd, remote_errno, bytes, io_size;
12055 gdb_byte *buffer;
12056 ULONGEST offset;
12057 struct remote_state *rs = get_remote_state ();
12058
12059 if (!rs->remote_desc)
12060 error (_("command can only be used with remote target"));
12061
12062 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12063 remote_file, FILEIO_O_RDONLY, 0, 0,
12064 &remote_errno);
12065 if (fd == -1)
12066 remote_hostio_error (remote_errno);
12067
12068 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12069 if (file == NULL)
12070 perror_with_name (local_file);
12071
12072 /* Send up to this many bytes at once. They won't all fit in the
12073 remote packet limit, so we'll transfer slightly fewer. */
12074 io_size = get_remote_packet_size ();
12075 buffer = (gdb_byte *) xmalloc (io_size);
12076 back_to = make_cleanup (xfree, buffer);
12077
12078 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12079
12080 offset = 0;
12081 while (1)
12082 {
12083 bytes = remote_hostio_pread (find_target_at (process_stratum),
12084 fd, buffer, io_size, offset, &remote_errno);
12085 if (bytes == 0)
12086 /* Success, but no bytes, means end-of-file. */
12087 break;
12088 if (bytes == -1)
12089 remote_hostio_error (remote_errno);
12090
12091 offset += bytes;
12092
12093 bytes = fwrite (buffer, 1, bytes, file.get ());
12094 if (bytes == 0)
12095 perror_with_name (local_file);
12096 }
12097
12098 discard_cleanups (close_cleanup);
12099 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12100 remote_hostio_error (remote_errno);
12101
12102 if (from_tty)
12103 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12104 do_cleanups (back_to);
12105 }
12106
12107 void
12108 remote_file_delete (const char *remote_file, int from_tty)
12109 {
12110 int retcode, remote_errno;
12111 struct remote_state *rs = get_remote_state ();
12112
12113 if (!rs->remote_desc)
12114 error (_("command can only be used with remote target"));
12115
12116 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12117 NULL, remote_file, &remote_errno);
12118 if (retcode == -1)
12119 remote_hostio_error (remote_errno);
12120
12121 if (from_tty)
12122 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12123 }
12124
12125 static void
12126 remote_put_command (const char *args, int from_tty)
12127 {
12128 if (args == NULL)
12129 error_no_arg (_("file to put"));
12130
12131 gdb_argv argv (args);
12132 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12133 error (_("Invalid parameters to remote put"));
12134
12135 remote_file_put (argv[0], argv[1], from_tty);
12136 }
12137
12138 static void
12139 remote_get_command (const char *args, int from_tty)
12140 {
12141 if (args == NULL)
12142 error_no_arg (_("file to get"));
12143
12144 gdb_argv argv (args);
12145 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12146 error (_("Invalid parameters to remote get"));
12147
12148 remote_file_get (argv[0], argv[1], from_tty);
12149 }
12150
12151 static void
12152 remote_delete_command (const char *args, int from_tty)
12153 {
12154 if (args == NULL)
12155 error_no_arg (_("file to delete"));
12156
12157 gdb_argv argv (args);
12158 if (argv[0] == NULL || argv[1] != NULL)
12159 error (_("Invalid parameters to remote delete"));
12160
12161 remote_file_delete (argv[0], from_tty);
12162 }
12163
12164 static void
12165 remote_command (char *args, int from_tty)
12166 {
12167 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12168 }
12169
12170 static int
12171 remote_can_execute_reverse (struct target_ops *self)
12172 {
12173 if (packet_support (PACKET_bs) == PACKET_ENABLE
12174 || packet_support (PACKET_bc) == PACKET_ENABLE)
12175 return 1;
12176 else
12177 return 0;
12178 }
12179
12180 static int
12181 remote_supports_non_stop (struct target_ops *self)
12182 {
12183 return 1;
12184 }
12185
12186 static int
12187 remote_supports_disable_randomization (struct target_ops *self)
12188 {
12189 /* Only supported in extended mode. */
12190 return 0;
12191 }
12192
12193 static int
12194 remote_supports_multi_process (struct target_ops *self)
12195 {
12196 struct remote_state *rs = get_remote_state ();
12197
12198 return remote_multi_process_p (rs);
12199 }
12200
12201 static int
12202 remote_supports_cond_tracepoints (void)
12203 {
12204 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12205 }
12206
12207 static int
12208 remote_supports_cond_breakpoints (struct target_ops *self)
12209 {
12210 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12211 }
12212
12213 static int
12214 remote_supports_fast_tracepoints (void)
12215 {
12216 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12217 }
12218
12219 static int
12220 remote_supports_static_tracepoints (void)
12221 {
12222 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12223 }
12224
12225 static int
12226 remote_supports_install_in_trace (void)
12227 {
12228 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12229 }
12230
12231 static int
12232 remote_supports_enable_disable_tracepoint (struct target_ops *self)
12233 {
12234 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12235 == PACKET_ENABLE);
12236 }
12237
12238 static int
12239 remote_supports_string_tracing (struct target_ops *self)
12240 {
12241 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12242 }
12243
12244 static int
12245 remote_can_run_breakpoint_commands (struct target_ops *self)
12246 {
12247 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12248 }
12249
12250 static void
12251 remote_trace_init (struct target_ops *self)
12252 {
12253 putpkt ("QTinit");
12254 remote_get_noisy_reply (&target_buf, &target_buf_size);
12255 if (strcmp (target_buf, "OK") != 0)
12256 error (_("Target does not support this command."));
12257 }
12258
12259 static void free_actions_list (char **actions_list);
12260 static void free_actions_list_cleanup_wrapper (void *);
12261 static void
12262 free_actions_list_cleanup_wrapper (void *al)
12263 {
12264 free_actions_list ((char **) al);
12265 }
12266
12267 static void
12268 free_actions_list (char **actions_list)
12269 {
12270 int ndx;
12271
12272 if (actions_list == 0)
12273 return;
12274
12275 for (ndx = 0; actions_list[ndx]; ndx++)
12276 xfree (actions_list[ndx]);
12277
12278 xfree (actions_list);
12279 }
12280
12281 /* Recursive routine to walk through command list including loops, and
12282 download packets for each command. */
12283
12284 static void
12285 remote_download_command_source (int num, ULONGEST addr,
12286 struct command_line *cmds)
12287 {
12288 struct remote_state *rs = get_remote_state ();
12289 struct command_line *cmd;
12290
12291 for (cmd = cmds; cmd; cmd = cmd->next)
12292 {
12293 QUIT; /* Allow user to bail out with ^C. */
12294 strcpy (rs->buf, "QTDPsrc:");
12295 encode_source_string (num, addr, "cmd", cmd->line,
12296 rs->buf + strlen (rs->buf),
12297 rs->buf_size - strlen (rs->buf));
12298 putpkt (rs->buf);
12299 remote_get_noisy_reply (&target_buf, &target_buf_size);
12300 if (strcmp (target_buf, "OK"))
12301 warning (_("Target does not support source download."));
12302
12303 if (cmd->control_type == while_control
12304 || cmd->control_type == while_stepping_control)
12305 {
12306 remote_download_command_source (num, addr, *cmd->body_list);
12307
12308 QUIT; /* Allow user to bail out with ^C. */
12309 strcpy (rs->buf, "QTDPsrc:");
12310 encode_source_string (num, addr, "cmd", "end",
12311 rs->buf + strlen (rs->buf),
12312 rs->buf_size - strlen (rs->buf));
12313 putpkt (rs->buf);
12314 remote_get_noisy_reply (&target_buf, &target_buf_size);
12315 if (strcmp (target_buf, "OK"))
12316 warning (_("Target does not support source download."));
12317 }
12318 }
12319 }
12320
12321 static void
12322 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
12323 {
12324 #define BUF_SIZE 2048
12325
12326 CORE_ADDR tpaddr;
12327 char addrbuf[40];
12328 char buf[BUF_SIZE];
12329 char **tdp_actions;
12330 char **stepping_actions;
12331 int ndx;
12332 struct cleanup *old_chain = NULL;
12333 char *pkt;
12334 struct breakpoint *b = loc->owner;
12335 struct tracepoint *t = (struct tracepoint *) b;
12336
12337 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12338 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
12339 tdp_actions);
12340 (void) make_cleanup (free_actions_list_cleanup_wrapper,
12341 stepping_actions);
12342
12343 tpaddr = loc->address;
12344 sprintf_vma (addrbuf, tpaddr);
12345 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12346 addrbuf, /* address */
12347 (b->enable_state == bp_enabled ? 'E' : 'D'),
12348 t->step_count, t->pass_count);
12349 /* Fast tracepoints are mostly handled by the target, but we can
12350 tell the target how big of an instruction block should be moved
12351 around. */
12352 if (b->type == bp_fast_tracepoint)
12353 {
12354 /* Only test for support at download time; we may not know
12355 target capabilities at definition time. */
12356 if (remote_supports_fast_tracepoints ())
12357 {
12358 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12359 NULL))
12360 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12361 gdb_insn_length (loc->gdbarch, tpaddr));
12362 else
12363 /* If it passed validation at definition but fails now,
12364 something is very wrong. */
12365 internal_error (__FILE__, __LINE__,
12366 _("Fast tracepoint not "
12367 "valid during download"));
12368 }
12369 else
12370 /* Fast tracepoints are functionally identical to regular
12371 tracepoints, so don't take lack of support as a reason to
12372 give up on the trace run. */
12373 warning (_("Target does not support fast tracepoints, "
12374 "downloading %d as regular tracepoint"), b->number);
12375 }
12376 else if (b->type == bp_static_tracepoint)
12377 {
12378 /* Only test for support at download time; we may not know
12379 target capabilities at definition time. */
12380 if (remote_supports_static_tracepoints ())
12381 {
12382 struct static_tracepoint_marker marker;
12383
12384 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12385 strcat (buf, ":S");
12386 else
12387 error (_("Static tracepoint not valid during download"));
12388 }
12389 else
12390 /* Fast tracepoints are functionally identical to regular
12391 tracepoints, so don't take lack of support as a reason
12392 to give up on the trace run. */
12393 error (_("Target does not support static tracepoints"));
12394 }
12395 /* If the tracepoint has a conditional, make it into an agent
12396 expression and append to the definition. */
12397 if (loc->cond)
12398 {
12399 /* Only test support at download time, we may not know target
12400 capabilities at definition time. */
12401 if (remote_supports_cond_tracepoints ())
12402 {
12403 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12404 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12405 aexpr->len);
12406 pkt = buf + strlen (buf);
12407 for (ndx = 0; ndx < aexpr->len; ++ndx)
12408 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12409 *pkt = '\0';
12410 }
12411 else
12412 warning (_("Target does not support conditional tracepoints, "
12413 "ignoring tp %d cond"), b->number);
12414 }
12415
12416 if (b->commands || *default_collect)
12417 strcat (buf, "-");
12418 putpkt (buf);
12419 remote_get_noisy_reply (&target_buf, &target_buf_size);
12420 if (strcmp (target_buf, "OK"))
12421 error (_("Target does not support tracepoints."));
12422
12423 /* do_single_steps (t); */
12424 if (tdp_actions)
12425 {
12426 for (ndx = 0; tdp_actions[ndx]; ndx++)
12427 {
12428 QUIT; /* Allow user to bail out with ^C. */
12429 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12430 b->number, addrbuf, /* address */
12431 tdp_actions[ndx],
12432 ((tdp_actions[ndx + 1] || stepping_actions)
12433 ? '-' : 0));
12434 putpkt (buf);
12435 remote_get_noisy_reply (&target_buf,
12436 &target_buf_size);
12437 if (strcmp (target_buf, "OK"))
12438 error (_("Error on target while setting tracepoints."));
12439 }
12440 }
12441 if (stepping_actions)
12442 {
12443 for (ndx = 0; stepping_actions[ndx]; ndx++)
12444 {
12445 QUIT; /* Allow user to bail out with ^C. */
12446 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12447 b->number, addrbuf, /* address */
12448 ((ndx == 0) ? "S" : ""),
12449 stepping_actions[ndx],
12450 (stepping_actions[ndx + 1] ? "-" : ""));
12451 putpkt (buf);
12452 remote_get_noisy_reply (&target_buf,
12453 &target_buf_size);
12454 if (strcmp (target_buf, "OK"))
12455 error (_("Error on target while setting tracepoints."));
12456 }
12457 }
12458
12459 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12460 {
12461 if (b->location != NULL)
12462 {
12463 strcpy (buf, "QTDPsrc:");
12464 encode_source_string (b->number, loc->address, "at",
12465 event_location_to_string (b->location.get ()),
12466 buf + strlen (buf), 2048 - strlen (buf));
12467 putpkt (buf);
12468 remote_get_noisy_reply (&target_buf, &target_buf_size);
12469 if (strcmp (target_buf, "OK"))
12470 warning (_("Target does not support source download."));
12471 }
12472 if (b->cond_string)
12473 {
12474 strcpy (buf, "QTDPsrc:");
12475 encode_source_string (b->number, loc->address,
12476 "cond", b->cond_string, buf + strlen (buf),
12477 2048 - strlen (buf));
12478 putpkt (buf);
12479 remote_get_noisy_reply (&target_buf, &target_buf_size);
12480 if (strcmp (target_buf, "OK"))
12481 warning (_("Target does not support source download."));
12482 }
12483 remote_download_command_source (b->number, loc->address,
12484 breakpoint_commands (b));
12485 }
12486
12487 do_cleanups (old_chain);
12488 }
12489
12490 static int
12491 remote_can_download_tracepoint (struct target_ops *self)
12492 {
12493 struct remote_state *rs = get_remote_state ();
12494 struct trace_status *ts;
12495 int status;
12496
12497 /* Don't try to install tracepoints until we've relocated our
12498 symbols, and fetched and merged the target's tracepoint list with
12499 ours. */
12500 if (rs->starting_up)
12501 return 0;
12502
12503 ts = current_trace_status ();
12504 status = remote_get_trace_status (self, ts);
12505
12506 if (status == -1 || !ts->running_known || !ts->running)
12507 return 0;
12508
12509 /* If we are in a tracing experiment, but remote stub doesn't support
12510 installing tracepoint in trace, we have to return. */
12511 if (!remote_supports_install_in_trace ())
12512 return 0;
12513
12514 return 1;
12515 }
12516
12517
12518 static void
12519 remote_download_trace_state_variable (struct target_ops *self,
12520 struct trace_state_variable *tsv)
12521 {
12522 struct remote_state *rs = get_remote_state ();
12523 char *p;
12524
12525 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12526 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12527 tsv->builtin);
12528 p = rs->buf + strlen (rs->buf);
12529 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12530 error (_("Trace state variable name too long for tsv definition packet"));
12531 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12532 *p++ = '\0';
12533 putpkt (rs->buf);
12534 remote_get_noisy_reply (&target_buf, &target_buf_size);
12535 if (*target_buf == '\0')
12536 error (_("Target does not support this command."));
12537 if (strcmp (target_buf, "OK") != 0)
12538 error (_("Error on target while downloading trace state variable."));
12539 }
12540
12541 static void
12542 remote_enable_tracepoint (struct target_ops *self,
12543 struct bp_location *location)
12544 {
12545 struct remote_state *rs = get_remote_state ();
12546 char addr_buf[40];
12547
12548 sprintf_vma (addr_buf, location->address);
12549 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12550 location->owner->number, addr_buf);
12551 putpkt (rs->buf);
12552 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12553 if (*rs->buf == '\0')
12554 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12555 if (strcmp (rs->buf, "OK") != 0)
12556 error (_("Error on target while enabling tracepoint."));
12557 }
12558
12559 static void
12560 remote_disable_tracepoint (struct target_ops *self,
12561 struct bp_location *location)
12562 {
12563 struct remote_state *rs = get_remote_state ();
12564 char addr_buf[40];
12565
12566 sprintf_vma (addr_buf, location->address);
12567 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12568 location->owner->number, addr_buf);
12569 putpkt (rs->buf);
12570 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12571 if (*rs->buf == '\0')
12572 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12573 if (strcmp (rs->buf, "OK") != 0)
12574 error (_("Error on target while disabling tracepoint."));
12575 }
12576
12577 static void
12578 remote_trace_set_readonly_regions (struct target_ops *self)
12579 {
12580 asection *s;
12581 bfd *abfd = NULL;
12582 bfd_size_type size;
12583 bfd_vma vma;
12584 int anysecs = 0;
12585 int offset = 0;
12586
12587 if (!exec_bfd)
12588 return; /* No information to give. */
12589
12590 strcpy (target_buf, "QTro");
12591 offset = strlen (target_buf);
12592 for (s = exec_bfd->sections; s; s = s->next)
12593 {
12594 char tmp1[40], tmp2[40];
12595 int sec_length;
12596
12597 if ((s->flags & SEC_LOAD) == 0 ||
12598 /* (s->flags & SEC_CODE) == 0 || */
12599 (s->flags & SEC_READONLY) == 0)
12600 continue;
12601
12602 anysecs = 1;
12603 vma = bfd_get_section_vma (abfd, s);
12604 size = bfd_get_section_size (s);
12605 sprintf_vma (tmp1, vma);
12606 sprintf_vma (tmp2, vma + size);
12607 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12608 if (offset + sec_length + 1 > target_buf_size)
12609 {
12610 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12611 warning (_("\
12612 Too many sections for read-only sections definition packet."));
12613 break;
12614 }
12615 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12616 tmp1, tmp2);
12617 offset += sec_length;
12618 }
12619 if (anysecs)
12620 {
12621 putpkt (target_buf);
12622 getpkt (&target_buf, &target_buf_size, 0);
12623 }
12624 }
12625
12626 static void
12627 remote_trace_start (struct target_ops *self)
12628 {
12629 putpkt ("QTStart");
12630 remote_get_noisy_reply (&target_buf, &target_buf_size);
12631 if (*target_buf == '\0')
12632 error (_("Target does not support this command."));
12633 if (strcmp (target_buf, "OK") != 0)
12634 error (_("Bogus reply from target: %s"), target_buf);
12635 }
12636
12637 static int
12638 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12639 {
12640 /* Initialize it just to avoid a GCC false warning. */
12641 char *p = NULL;
12642 /* FIXME we need to get register block size some other way. */
12643 extern int trace_regblock_size;
12644 enum packet_result result;
12645
12646 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12647 return -1;
12648
12649 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12650
12651 putpkt ("qTStatus");
12652
12653 TRY
12654 {
12655 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12656 }
12657 CATCH (ex, RETURN_MASK_ERROR)
12658 {
12659 if (ex.error != TARGET_CLOSE_ERROR)
12660 {
12661 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12662 return -1;
12663 }
12664 throw_exception (ex);
12665 }
12666 END_CATCH
12667
12668 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12669
12670 /* If the remote target doesn't do tracing, flag it. */
12671 if (result == PACKET_UNKNOWN)
12672 return -1;
12673
12674 /* We're working with a live target. */
12675 ts->filename = NULL;
12676
12677 if (*p++ != 'T')
12678 error (_("Bogus trace status reply from target: %s"), target_buf);
12679
12680 /* Function 'parse_trace_status' sets default value of each field of
12681 'ts' at first, so we don't have to do it here. */
12682 parse_trace_status (p, ts);
12683
12684 return ts->running;
12685 }
12686
12687 static void
12688 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12689 struct uploaded_tp *utp)
12690 {
12691 struct remote_state *rs = get_remote_state ();
12692 char *reply;
12693 struct bp_location *loc;
12694 struct tracepoint *tp = (struct tracepoint *) bp;
12695 size_t size = get_remote_packet_size ();
12696
12697 if (tp)
12698 {
12699 tp->hit_count = 0;
12700 tp->traceframe_usage = 0;
12701 for (loc = tp->loc; loc; loc = loc->next)
12702 {
12703 /* If the tracepoint was never downloaded, don't go asking for
12704 any status. */
12705 if (tp->number_on_target == 0)
12706 continue;
12707 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12708 phex_nz (loc->address, 0));
12709 putpkt (rs->buf);
12710 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12711 if (reply && *reply)
12712 {
12713 if (*reply == 'V')
12714 parse_tracepoint_status (reply + 1, bp, utp);
12715 }
12716 }
12717 }
12718 else if (utp)
12719 {
12720 utp->hit_count = 0;
12721 utp->traceframe_usage = 0;
12722 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12723 phex_nz (utp->addr, 0));
12724 putpkt (rs->buf);
12725 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12726 if (reply && *reply)
12727 {
12728 if (*reply == 'V')
12729 parse_tracepoint_status (reply + 1, bp, utp);
12730 }
12731 }
12732 }
12733
12734 static void
12735 remote_trace_stop (struct target_ops *self)
12736 {
12737 putpkt ("QTStop");
12738 remote_get_noisy_reply (&target_buf, &target_buf_size);
12739 if (*target_buf == '\0')
12740 error (_("Target does not support this command."));
12741 if (strcmp (target_buf, "OK") != 0)
12742 error (_("Bogus reply from target: %s"), target_buf);
12743 }
12744
12745 static int
12746 remote_trace_find (struct target_ops *self,
12747 enum trace_find_type type, int num,
12748 CORE_ADDR addr1, CORE_ADDR addr2,
12749 int *tpp)
12750 {
12751 struct remote_state *rs = get_remote_state ();
12752 char *endbuf = rs->buf + get_remote_packet_size ();
12753 char *p, *reply;
12754 int target_frameno = -1, target_tracept = -1;
12755
12756 /* Lookups other than by absolute frame number depend on the current
12757 trace selected, so make sure it is correct on the remote end
12758 first. */
12759 if (type != tfind_number)
12760 set_remote_traceframe ();
12761
12762 p = rs->buf;
12763 strcpy (p, "QTFrame:");
12764 p = strchr (p, '\0');
12765 switch (type)
12766 {
12767 case tfind_number:
12768 xsnprintf (p, endbuf - p, "%x", num);
12769 break;
12770 case tfind_pc:
12771 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12772 break;
12773 case tfind_tp:
12774 xsnprintf (p, endbuf - p, "tdp:%x", num);
12775 break;
12776 case tfind_range:
12777 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12778 phex_nz (addr2, 0));
12779 break;
12780 case tfind_outside:
12781 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12782 phex_nz (addr2, 0));
12783 break;
12784 default:
12785 error (_("Unknown trace find type %d"), type);
12786 }
12787
12788 putpkt (rs->buf);
12789 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12790 if (*reply == '\0')
12791 error (_("Target does not support this command."));
12792
12793 while (reply && *reply)
12794 switch (*reply)
12795 {
12796 case 'F':
12797 p = ++reply;
12798 target_frameno = (int) strtol (p, &reply, 16);
12799 if (reply == p)
12800 error (_("Unable to parse trace frame number"));
12801 /* Don't update our remote traceframe number cache on failure
12802 to select a remote traceframe. */
12803 if (target_frameno == -1)
12804 return -1;
12805 break;
12806 case 'T':
12807 p = ++reply;
12808 target_tracept = (int) strtol (p, &reply, 16);
12809 if (reply == p)
12810 error (_("Unable to parse tracepoint number"));
12811 break;
12812 case 'O': /* "OK"? */
12813 if (reply[1] == 'K' && reply[2] == '\0')
12814 reply += 2;
12815 else
12816 error (_("Bogus reply from target: %s"), reply);
12817 break;
12818 default:
12819 error (_("Bogus reply from target: %s"), reply);
12820 }
12821 if (tpp)
12822 *tpp = target_tracept;
12823
12824 rs->remote_traceframe_number = target_frameno;
12825 return target_frameno;
12826 }
12827
12828 static int
12829 remote_get_trace_state_variable_value (struct target_ops *self,
12830 int tsvnum, LONGEST *val)
12831 {
12832 struct remote_state *rs = get_remote_state ();
12833 char *reply;
12834 ULONGEST uval;
12835
12836 set_remote_traceframe ();
12837
12838 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12839 putpkt (rs->buf);
12840 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12841 if (reply && *reply)
12842 {
12843 if (*reply == 'V')
12844 {
12845 unpack_varlen_hex (reply + 1, &uval);
12846 *val = (LONGEST) uval;
12847 return 1;
12848 }
12849 }
12850 return 0;
12851 }
12852
12853 static int
12854 remote_save_trace_data (struct target_ops *self, const char *filename)
12855 {
12856 struct remote_state *rs = get_remote_state ();
12857 char *p, *reply;
12858
12859 p = rs->buf;
12860 strcpy (p, "QTSave:");
12861 p += strlen (p);
12862 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12863 error (_("Remote file name too long for trace save packet"));
12864 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12865 *p++ = '\0';
12866 putpkt (rs->buf);
12867 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12868 if (*reply == '\0')
12869 error (_("Target does not support this command."));
12870 if (strcmp (reply, "OK") != 0)
12871 error (_("Bogus reply from target: %s"), reply);
12872 return 0;
12873 }
12874
12875 /* This is basically a memory transfer, but needs to be its own packet
12876 because we don't know how the target actually organizes its trace
12877 memory, plus we want to be able to ask for as much as possible, but
12878 not be unhappy if we don't get as much as we ask for. */
12879
12880 static LONGEST
12881 remote_get_raw_trace_data (struct target_ops *self,
12882 gdb_byte *buf, ULONGEST offset, LONGEST len)
12883 {
12884 struct remote_state *rs = get_remote_state ();
12885 char *reply;
12886 char *p;
12887 int rslt;
12888
12889 p = rs->buf;
12890 strcpy (p, "qTBuffer:");
12891 p += strlen (p);
12892 p += hexnumstr (p, offset);
12893 *p++ = ',';
12894 p += hexnumstr (p, len);
12895 *p++ = '\0';
12896
12897 putpkt (rs->buf);
12898 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12899 if (reply && *reply)
12900 {
12901 /* 'l' by itself means we're at the end of the buffer and
12902 there is nothing more to get. */
12903 if (*reply == 'l')
12904 return 0;
12905
12906 /* Convert the reply into binary. Limit the number of bytes to
12907 convert according to our passed-in buffer size, rather than
12908 what was returned in the packet; if the target is
12909 unexpectedly generous and gives us a bigger reply than we
12910 asked for, we don't want to crash. */
12911 rslt = hex2bin (target_buf, buf, len);
12912 return rslt;
12913 }
12914
12915 /* Something went wrong, flag as an error. */
12916 return -1;
12917 }
12918
12919 static void
12920 remote_set_disconnected_tracing (struct target_ops *self, int val)
12921 {
12922 struct remote_state *rs = get_remote_state ();
12923
12924 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12925 {
12926 char *reply;
12927
12928 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12929 putpkt (rs->buf);
12930 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12931 if (*reply == '\0')
12932 error (_("Target does not support this command."));
12933 if (strcmp (reply, "OK") != 0)
12934 error (_("Bogus reply from target: %s"), reply);
12935 }
12936 else if (val)
12937 warning (_("Target does not support disconnected tracing."));
12938 }
12939
12940 static int
12941 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12942 {
12943 struct thread_info *info = find_thread_ptid (ptid);
12944
12945 if (info && info->priv)
12946 return info->priv->core;
12947 return -1;
12948 }
12949
12950 static void
12951 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12952 {
12953 struct remote_state *rs = get_remote_state ();
12954 char *reply;
12955
12956 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12957 putpkt (rs->buf);
12958 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12959 if (*reply == '\0')
12960 error (_("Target does not support this command."));
12961 if (strcmp (reply, "OK") != 0)
12962 error (_("Bogus reply from target: %s"), reply);
12963 }
12964
12965 static struct traceframe_info *
12966 remote_traceframe_info (struct target_ops *self)
12967 {
12968 char *text;
12969
12970 text = target_read_stralloc (&current_target,
12971 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12972 if (text != NULL)
12973 {
12974 struct traceframe_info *info;
12975 struct cleanup *back_to = make_cleanup (xfree, text);
12976
12977 info = parse_traceframe_info (text);
12978 do_cleanups (back_to);
12979 return info;
12980 }
12981
12982 return NULL;
12983 }
12984
12985 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12986 instruction on which a fast tracepoint may be placed. Returns -1
12987 if the packet is not supported, and 0 if the minimum instruction
12988 length is unknown. */
12989
12990 static int
12991 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12992 {
12993 struct remote_state *rs = get_remote_state ();
12994 char *reply;
12995
12996 /* If we're not debugging a process yet, the IPA can't be
12997 loaded. */
12998 if (!target_has_execution)
12999 return 0;
13000
13001 /* Make sure the remote is pointing at the right process. */
13002 set_general_process ();
13003
13004 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13005 putpkt (rs->buf);
13006 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
13007 if (*reply == '\0')
13008 return -1;
13009 else
13010 {
13011 ULONGEST min_insn_len;
13012
13013 unpack_varlen_hex (reply, &min_insn_len);
13014
13015 return (int) min_insn_len;
13016 }
13017 }
13018
13019 static void
13020 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
13021 {
13022 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13023 {
13024 struct remote_state *rs = get_remote_state ();
13025 char *buf = rs->buf;
13026 char *endbuf = rs->buf + get_remote_packet_size ();
13027 enum packet_result result;
13028
13029 gdb_assert (val >= 0 || val == -1);
13030 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13031 /* Send -1 as literal "-1" to avoid host size dependency. */
13032 if (val < 0)
13033 {
13034 *buf++ = '-';
13035 buf += hexnumstr (buf, (ULONGEST) -val);
13036 }
13037 else
13038 buf += hexnumstr (buf, (ULONGEST) val);
13039
13040 putpkt (rs->buf);
13041 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
13042 result = packet_ok (rs->buf,
13043 &remote_protocol_packets[PACKET_QTBuffer_size]);
13044
13045 if (result != PACKET_OK)
13046 warning (_("Bogus reply from target: %s"), rs->buf);
13047 }
13048 }
13049
13050 static int
13051 remote_set_trace_notes (struct target_ops *self,
13052 const char *user, const char *notes,
13053 const char *stop_notes)
13054 {
13055 struct remote_state *rs = get_remote_state ();
13056 char *reply;
13057 char *buf = rs->buf;
13058 char *endbuf = rs->buf + get_remote_packet_size ();
13059 int nbytes;
13060
13061 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13062 if (user)
13063 {
13064 buf += xsnprintf (buf, endbuf - buf, "user:");
13065 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13066 buf += 2 * nbytes;
13067 *buf++ = ';';
13068 }
13069 if (notes)
13070 {
13071 buf += xsnprintf (buf, endbuf - buf, "notes:");
13072 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13073 buf += 2 * nbytes;
13074 *buf++ = ';';
13075 }
13076 if (stop_notes)
13077 {
13078 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13079 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13080 buf += 2 * nbytes;
13081 *buf++ = ';';
13082 }
13083 /* Ensure the buffer is terminated. */
13084 *buf = '\0';
13085
13086 putpkt (rs->buf);
13087 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
13088 if (*reply == '\0')
13089 return 0;
13090
13091 if (strcmp (reply, "OK") != 0)
13092 error (_("Bogus reply from target: %s"), reply);
13093
13094 return 1;
13095 }
13096
13097 static int
13098 remote_use_agent (struct target_ops *self, int use)
13099 {
13100 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13101 {
13102 struct remote_state *rs = get_remote_state ();
13103
13104 /* If the stub supports QAgent. */
13105 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13106 putpkt (rs->buf);
13107 getpkt (&rs->buf, &rs->buf_size, 0);
13108
13109 if (strcmp (rs->buf, "OK") == 0)
13110 {
13111 use_agent = use;
13112 return 1;
13113 }
13114 }
13115
13116 return 0;
13117 }
13118
13119 static int
13120 remote_can_use_agent (struct target_ops *self)
13121 {
13122 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13123 }
13124
13125 struct btrace_target_info
13126 {
13127 /* The ptid of the traced thread. */
13128 ptid_t ptid;
13129
13130 /* The obtained branch trace configuration. */
13131 struct btrace_config conf;
13132 };
13133
13134 /* Reset our idea of our target's btrace configuration. */
13135
13136 static void
13137 remote_btrace_reset (void)
13138 {
13139 struct remote_state *rs = get_remote_state ();
13140
13141 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13142 }
13143
13144 /* Check whether the target supports branch tracing. */
13145
13146 static int
13147 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
13148 {
13149 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
13150 return 0;
13151 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
13152 return 0;
13153
13154 switch (format)
13155 {
13156 case BTRACE_FORMAT_NONE:
13157 return 0;
13158
13159 case BTRACE_FORMAT_BTS:
13160 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
13161
13162 case BTRACE_FORMAT_PT:
13163 /* The trace is decoded on the host. Even if our target supports it,
13164 we still need to have libipt to decode the trace. */
13165 #if defined (HAVE_LIBIPT)
13166 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
13167 #else /* !defined (HAVE_LIBIPT) */
13168 return 0;
13169 #endif /* !defined (HAVE_LIBIPT) */
13170 }
13171
13172 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
13173 }
13174
13175 /* Synchronize the configuration with the target. */
13176
13177 static void
13178 btrace_sync_conf (const struct btrace_config *conf)
13179 {
13180 struct packet_config *packet;
13181 struct remote_state *rs;
13182 char *buf, *pos, *endbuf;
13183
13184 rs = get_remote_state ();
13185 buf = rs->buf;
13186 endbuf = buf + get_remote_packet_size ();
13187
13188 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13189 if (packet_config_support (packet) == PACKET_ENABLE
13190 && conf->bts.size != rs->btrace_config.bts.size)
13191 {
13192 pos = buf;
13193 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13194 conf->bts.size);
13195
13196 putpkt (buf);
13197 getpkt (&buf, &rs->buf_size, 0);
13198
13199 if (packet_ok (buf, packet) == PACKET_ERROR)
13200 {
13201 if (buf[0] == 'E' && buf[1] == '.')
13202 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13203 else
13204 error (_("Failed to configure the BTS buffer size."));
13205 }
13206
13207 rs->btrace_config.bts.size = conf->bts.size;
13208 }
13209
13210 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13211 if (packet_config_support (packet) == PACKET_ENABLE
13212 && conf->pt.size != rs->btrace_config.pt.size)
13213 {
13214 pos = buf;
13215 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13216 conf->pt.size);
13217
13218 putpkt (buf);
13219 getpkt (&buf, &rs->buf_size, 0);
13220
13221 if (packet_ok (buf, packet) == PACKET_ERROR)
13222 {
13223 if (buf[0] == 'E' && buf[1] == '.')
13224 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13225 else
13226 error (_("Failed to configure the trace buffer size."));
13227 }
13228
13229 rs->btrace_config.pt.size = conf->pt.size;
13230 }
13231 }
13232
13233 /* Read the current thread's btrace configuration from the target and
13234 store it into CONF. */
13235
13236 static void
13237 btrace_read_config (struct btrace_config *conf)
13238 {
13239 char *xml;
13240
13241 xml = target_read_stralloc (&current_target,
13242 TARGET_OBJECT_BTRACE_CONF, "");
13243 if (xml != NULL)
13244 {
13245 struct cleanup *cleanup;
13246
13247 cleanup = make_cleanup (xfree, xml);
13248 parse_xml_btrace_conf (conf, xml);
13249 do_cleanups (cleanup);
13250 }
13251 }
13252
13253 /* Maybe reopen target btrace. */
13254
13255 static void
13256 remote_btrace_maybe_reopen (void)
13257 {
13258 struct remote_state *rs = get_remote_state ();
13259 struct thread_info *tp;
13260 int btrace_target_pushed = 0;
13261 int warned = 0;
13262
13263 scoped_restore_current_thread restore_thread;
13264
13265 ALL_NON_EXITED_THREADS (tp)
13266 {
13267 set_general_thread (tp->ptid);
13268
13269 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13270 btrace_read_config (&rs->btrace_config);
13271
13272 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13273 continue;
13274
13275 #if !defined (HAVE_LIBIPT)
13276 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13277 {
13278 if (!warned)
13279 {
13280 warned = 1;
13281 warning (_("GDB does not support Intel Processor Trace. "
13282 "\"record\" will not work in this session."));
13283 }
13284
13285 continue;
13286 }
13287 #endif /* !defined (HAVE_LIBIPT) */
13288
13289 /* Push target, once, but before anything else happens. This way our
13290 changes to the threads will be cleaned up by unpushing the target
13291 in case btrace_read_config () throws. */
13292 if (!btrace_target_pushed)
13293 {
13294 btrace_target_pushed = 1;
13295 record_btrace_push_target ();
13296 printf_filtered (_("Target is recording using %s.\n"),
13297 btrace_format_string (rs->btrace_config.format));
13298 }
13299
13300 tp->btrace.target = XCNEW (struct btrace_target_info);
13301 tp->btrace.target->ptid = tp->ptid;
13302 tp->btrace.target->conf = rs->btrace_config;
13303 }
13304 }
13305
13306 /* Enable branch tracing. */
13307
13308 static struct btrace_target_info *
13309 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13310 const struct btrace_config *conf)
13311 {
13312 struct btrace_target_info *tinfo = NULL;
13313 struct packet_config *packet = NULL;
13314 struct remote_state *rs = get_remote_state ();
13315 char *buf = rs->buf;
13316 char *endbuf = rs->buf + get_remote_packet_size ();
13317
13318 switch (conf->format)
13319 {
13320 case BTRACE_FORMAT_BTS:
13321 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13322 break;
13323
13324 case BTRACE_FORMAT_PT:
13325 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13326 break;
13327 }
13328
13329 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13330 error (_("Target does not support branch tracing."));
13331
13332 btrace_sync_conf (conf);
13333
13334 set_general_thread (ptid);
13335
13336 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13337 putpkt (rs->buf);
13338 getpkt (&rs->buf, &rs->buf_size, 0);
13339
13340 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13341 {
13342 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13343 error (_("Could not enable branch tracing for %s: %s"),
13344 target_pid_to_str (ptid), rs->buf + 2);
13345 else
13346 error (_("Could not enable branch tracing for %s."),
13347 target_pid_to_str (ptid));
13348 }
13349
13350 tinfo = XCNEW (struct btrace_target_info);
13351 tinfo->ptid = ptid;
13352
13353 /* If we fail to read the configuration, we lose some information, but the
13354 tracing itself is not impacted. */
13355 TRY
13356 {
13357 btrace_read_config (&tinfo->conf);
13358 }
13359 CATCH (err, RETURN_MASK_ERROR)
13360 {
13361 if (err.message != NULL)
13362 warning ("%s", err.message);
13363 }
13364 END_CATCH
13365
13366 return tinfo;
13367 }
13368
13369 /* Disable branch tracing. */
13370
13371 static void
13372 remote_disable_btrace (struct target_ops *self,
13373 struct btrace_target_info *tinfo)
13374 {
13375 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13376 struct remote_state *rs = get_remote_state ();
13377 char *buf = rs->buf;
13378 char *endbuf = rs->buf + get_remote_packet_size ();
13379
13380 if (packet_config_support (packet) != PACKET_ENABLE)
13381 error (_("Target does not support branch tracing."));
13382
13383 set_general_thread (tinfo->ptid);
13384
13385 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13386 putpkt (rs->buf);
13387 getpkt (&rs->buf, &rs->buf_size, 0);
13388
13389 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13390 {
13391 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13392 error (_("Could not disable branch tracing for %s: %s"),
13393 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13394 else
13395 error (_("Could not disable branch tracing for %s."),
13396 target_pid_to_str (tinfo->ptid));
13397 }
13398
13399 xfree (tinfo);
13400 }
13401
13402 /* Teardown branch tracing. */
13403
13404 static void
13405 remote_teardown_btrace (struct target_ops *self,
13406 struct btrace_target_info *tinfo)
13407 {
13408 /* We must not talk to the target during teardown. */
13409 xfree (tinfo);
13410 }
13411
13412 /* Read the branch trace. */
13413
13414 static enum btrace_error
13415 remote_read_btrace (struct target_ops *self,
13416 struct btrace_data *btrace,
13417 struct btrace_target_info *tinfo,
13418 enum btrace_read_type type)
13419 {
13420 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13421 struct cleanup *cleanup;
13422 const char *annex;
13423 char *xml;
13424
13425 if (packet_config_support (packet) != PACKET_ENABLE)
13426 error (_("Target does not support branch tracing."));
13427
13428 #if !defined(HAVE_LIBEXPAT)
13429 error (_("Cannot process branch tracing result. XML parsing not supported."));
13430 #endif
13431
13432 switch (type)
13433 {
13434 case BTRACE_READ_ALL:
13435 annex = "all";
13436 break;
13437 case BTRACE_READ_NEW:
13438 annex = "new";
13439 break;
13440 case BTRACE_READ_DELTA:
13441 annex = "delta";
13442 break;
13443 default:
13444 internal_error (__FILE__, __LINE__,
13445 _("Bad branch tracing read type: %u."),
13446 (unsigned int) type);
13447 }
13448
13449 xml = target_read_stralloc (&current_target,
13450 TARGET_OBJECT_BTRACE, annex);
13451 if (xml == NULL)
13452 return BTRACE_ERR_UNKNOWN;
13453
13454 cleanup = make_cleanup (xfree, xml);
13455 parse_xml_btrace (btrace, xml);
13456 do_cleanups (cleanup);
13457
13458 return BTRACE_ERR_NONE;
13459 }
13460
13461 static const struct btrace_config *
13462 remote_btrace_conf (struct target_ops *self,
13463 const struct btrace_target_info *tinfo)
13464 {
13465 return &tinfo->conf;
13466 }
13467
13468 static int
13469 remote_augmented_libraries_svr4_read (struct target_ops *self)
13470 {
13471 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13472 == PACKET_ENABLE);
13473 }
13474
13475 /* Implementation of to_load. */
13476
13477 static void
13478 remote_load (struct target_ops *self, const char *name, int from_tty)
13479 {
13480 generic_load (name, from_tty);
13481 }
13482
13483 /* Accepts an integer PID; returns a string representing a file that
13484 can be opened on the remote side to get the symbols for the child
13485 process. Returns NULL if the operation is not supported. */
13486
13487 static char *
13488 remote_pid_to_exec_file (struct target_ops *self, int pid)
13489 {
13490 static char *filename = NULL;
13491 struct inferior *inf;
13492 char *annex = NULL;
13493
13494 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13495 return NULL;
13496
13497 if (filename != NULL)
13498 xfree (filename);
13499
13500 inf = find_inferior_pid (pid);
13501 if (inf == NULL)
13502 internal_error (__FILE__, __LINE__,
13503 _("not currently attached to process %d"), pid);
13504
13505 if (!inf->fake_pid_p)
13506 {
13507 const int annex_size = 9;
13508
13509 annex = (char *) alloca (annex_size);
13510 xsnprintf (annex, annex_size, "%x", pid);
13511 }
13512
13513 filename = target_read_stralloc (&current_target,
13514 TARGET_OBJECT_EXEC_FILE, annex);
13515
13516 return filename;
13517 }
13518
13519 /* Implement the to_can_do_single_step target_ops method. */
13520
13521 static int
13522 remote_can_do_single_step (struct target_ops *ops)
13523 {
13524 /* We can only tell whether target supports single step or not by
13525 supported s and S vCont actions if the stub supports vContSupported
13526 feature. If the stub doesn't support vContSupported feature,
13527 we have conservatively to think target doesn't supports single
13528 step. */
13529 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13530 {
13531 struct remote_state *rs = get_remote_state ();
13532
13533 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13534 remote_vcont_probe (rs);
13535
13536 return rs->supports_vCont.s && rs->supports_vCont.S;
13537 }
13538 else
13539 return 0;
13540 }
13541
13542 /* Implementation of the to_execution_direction method for the remote
13543 target. */
13544
13545 static enum exec_direction_kind
13546 remote_execution_direction (struct target_ops *self)
13547 {
13548 struct remote_state *rs = get_remote_state ();
13549
13550 return rs->last_resume_exec_dir;
13551 }
13552
13553 /* Return pointer to the thread_info struct which corresponds to
13554 THREAD_HANDLE (having length HANDLE_LEN). */
13555
13556 static struct thread_info *
13557 remote_thread_handle_to_thread_info (struct target_ops *ops,
13558 const gdb_byte *thread_handle,
13559 int handle_len,
13560 struct inferior *inf)
13561 {
13562 struct thread_info *tp;
13563
13564 ALL_NON_EXITED_THREADS (tp)
13565 {
13566 struct private_thread_info *priv = get_private_info_thread (tp);
13567
13568 if (tp->inf == inf && priv != NULL)
13569 {
13570 if (handle_len != priv->thread_handle->size ())
13571 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13572 handle_len, priv->thread_handle->size ());
13573 if (memcmp (thread_handle, priv->thread_handle->data (),
13574 handle_len) == 0)
13575 return tp;
13576 }
13577 }
13578
13579 return NULL;
13580 }
13581
13582 static void
13583 init_remote_ops (void)
13584 {
13585 remote_ops.to_shortname = "remote";
13586 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13587 remote_ops.to_doc =
13588 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13589 Specify the serial device it is connected to\n\
13590 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13591 remote_ops.to_open = remote_open;
13592 remote_ops.to_close = remote_close;
13593 remote_ops.to_detach = remote_detach;
13594 remote_ops.to_disconnect = remote_disconnect;
13595 remote_ops.to_resume = remote_resume;
13596 remote_ops.to_commit_resume = remote_commit_resume;
13597 remote_ops.to_wait = remote_wait;
13598 remote_ops.to_fetch_registers = remote_fetch_registers;
13599 remote_ops.to_store_registers = remote_store_registers;
13600 remote_ops.to_prepare_to_store = remote_prepare_to_store;
13601 remote_ops.to_files_info = remote_files_info;
13602 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13603 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13604 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13605 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13606 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13607 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13608 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13609 remote_ops.to_stopped_data_address = remote_stopped_data_address;
13610 remote_ops.to_watchpoint_addr_within_range =
13611 remote_watchpoint_addr_within_range;
13612 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13613 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13614 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13615 remote_ops.to_region_ok_for_hw_watchpoint
13616 = remote_region_ok_for_hw_watchpoint;
13617 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13618 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13619 remote_ops.to_kill = remote_kill;
13620 remote_ops.to_load = remote_load;
13621 remote_ops.to_mourn_inferior = remote_mourn;
13622 remote_ops.to_pass_signals = remote_pass_signals;
13623 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13624 remote_ops.to_program_signals = remote_program_signals;
13625 remote_ops.to_thread_alive = remote_thread_alive;
13626 remote_ops.to_thread_name = remote_thread_name;
13627 remote_ops.to_update_thread_list = remote_update_thread_list;
13628 remote_ops.to_pid_to_str = remote_pid_to_str;
13629 remote_ops.to_extra_thread_info = remote_threads_extra_info;
13630 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13631 remote_ops.to_stop = remote_stop;
13632 remote_ops.to_interrupt = remote_interrupt;
13633 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13634 remote_ops.to_xfer_partial = remote_xfer_partial;
13635 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
13636 remote_ops.to_rcmd = remote_rcmd;
13637 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13638 remote_ops.to_log_command = serial_log_command;
13639 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13640 remote_ops.to_stratum = process_stratum;
13641 remote_ops.to_has_all_memory = default_child_has_all_memory;
13642 remote_ops.to_has_memory = default_child_has_memory;
13643 remote_ops.to_has_stack = default_child_has_stack;
13644 remote_ops.to_has_registers = default_child_has_registers;
13645 remote_ops.to_has_execution = default_child_has_execution;
13646 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
13647 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13648 remote_ops.to_magic = OPS_MAGIC;
13649 remote_ops.to_memory_map = remote_memory_map;
13650 remote_ops.to_flash_erase = remote_flash_erase;
13651 remote_ops.to_flash_done = remote_flash_done;
13652 remote_ops.to_read_description = remote_read_description;
13653 remote_ops.to_search_memory = remote_search_memory;
13654 remote_ops.to_can_async_p = remote_can_async_p;
13655 remote_ops.to_is_async_p = remote_is_async_p;
13656 remote_ops.to_async = remote_async;
13657 remote_ops.to_thread_events = remote_thread_events;
13658 remote_ops.to_can_do_single_step = remote_can_do_single_step;
13659 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13660 remote_ops.to_terminal_ours = remote_terminal_ours;
13661 remote_ops.to_supports_non_stop = remote_supports_non_stop;
13662 remote_ops.to_supports_multi_process = remote_supports_multi_process;
13663 remote_ops.to_supports_disable_randomization
13664 = remote_supports_disable_randomization;
13665 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13666 remote_ops.to_fileio_open = remote_hostio_open;
13667 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13668 remote_ops.to_fileio_pread = remote_hostio_pread;
13669 remote_ops.to_fileio_fstat = remote_hostio_fstat;
13670 remote_ops.to_fileio_close = remote_hostio_close;
13671 remote_ops.to_fileio_unlink = remote_hostio_unlink;
13672 remote_ops.to_fileio_readlink = remote_hostio_readlink;
13673 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13674 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13675 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13676 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13677 remote_ops.to_trace_init = remote_trace_init;
13678 remote_ops.to_download_tracepoint = remote_download_tracepoint;
13679 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13680 remote_ops.to_download_trace_state_variable
13681 = remote_download_trace_state_variable;
13682 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13683 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13684 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13685 remote_ops.to_trace_start = remote_trace_start;
13686 remote_ops.to_get_trace_status = remote_get_trace_status;
13687 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13688 remote_ops.to_trace_stop = remote_trace_stop;
13689 remote_ops.to_trace_find = remote_trace_find;
13690 remote_ops.to_get_trace_state_variable_value
13691 = remote_get_trace_state_variable_value;
13692 remote_ops.to_save_trace_data = remote_save_trace_data;
13693 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13694 remote_ops.to_upload_trace_state_variables
13695 = remote_upload_trace_state_variables;
13696 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13697 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13698 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13699 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13700 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13701 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13702 remote_ops.to_core_of_thread = remote_core_of_thread;
13703 remote_ops.to_verify_memory = remote_verify_memory;
13704 remote_ops.to_get_tib_address = remote_get_tib_address;
13705 remote_ops.to_set_permissions = remote_set_permissions;
13706 remote_ops.to_static_tracepoint_marker_at
13707 = remote_static_tracepoint_marker_at;
13708 remote_ops.to_static_tracepoint_markers_by_strid
13709 = remote_static_tracepoint_markers_by_strid;
13710 remote_ops.to_traceframe_info = remote_traceframe_info;
13711 remote_ops.to_use_agent = remote_use_agent;
13712 remote_ops.to_can_use_agent = remote_can_use_agent;
13713 remote_ops.to_supports_btrace = remote_supports_btrace;
13714 remote_ops.to_enable_btrace = remote_enable_btrace;
13715 remote_ops.to_disable_btrace = remote_disable_btrace;
13716 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13717 remote_ops.to_read_btrace = remote_read_btrace;
13718 remote_ops.to_btrace_conf = remote_btrace_conf;
13719 remote_ops.to_augmented_libraries_svr4_read =
13720 remote_augmented_libraries_svr4_read;
13721 remote_ops.to_follow_fork = remote_follow_fork;
13722 remote_ops.to_follow_exec = remote_follow_exec;
13723 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13724 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13725 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13726 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13727 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13728 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13729 remote_ops.to_execution_direction = remote_execution_direction;
13730 remote_ops.to_thread_handle_to_thread_info =
13731 remote_thread_handle_to_thread_info;
13732 }
13733
13734 /* Set up the extended remote vector by making a copy of the standard
13735 remote vector and adding to it. */
13736
13737 static void
13738 init_extended_remote_ops (void)
13739 {
13740 extended_remote_ops = remote_ops;
13741
13742 extended_remote_ops.to_shortname = "extended-remote";
13743 extended_remote_ops.to_longname =
13744 "Extended remote serial target in gdb-specific protocol";
13745 extended_remote_ops.to_doc =
13746 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13747 Specify the serial device it is connected to (e.g. /dev/ttya).";
13748 extended_remote_ops.to_open = extended_remote_open;
13749 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13750 extended_remote_ops.to_detach = extended_remote_detach;
13751 extended_remote_ops.to_attach = extended_remote_attach;
13752 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13753 extended_remote_ops.to_supports_disable_randomization
13754 = extended_remote_supports_disable_randomization;
13755 }
13756
13757 static int
13758 remote_can_async_p (struct target_ops *ops)
13759 {
13760 struct remote_state *rs = get_remote_state ();
13761
13762 /* We don't go async if the user has explicitly prevented it with the
13763 "maint set target-async" command. */
13764 if (!target_async_permitted)
13765 return 0;
13766
13767 /* We're async whenever the serial device is. */
13768 return serial_can_async_p (rs->remote_desc);
13769 }
13770
13771 static int
13772 remote_is_async_p (struct target_ops *ops)
13773 {
13774 struct remote_state *rs = get_remote_state ();
13775
13776 if (!target_async_permitted)
13777 /* We only enable async when the user specifically asks for it. */
13778 return 0;
13779
13780 /* We're async whenever the serial device is. */
13781 return serial_is_async_p (rs->remote_desc);
13782 }
13783
13784 /* Pass the SERIAL event on and up to the client. One day this code
13785 will be able to delay notifying the client of an event until the
13786 point where an entire packet has been received. */
13787
13788 static serial_event_ftype remote_async_serial_handler;
13789
13790 static void
13791 remote_async_serial_handler (struct serial *scb, void *context)
13792 {
13793 /* Don't propogate error information up to the client. Instead let
13794 the client find out about the error by querying the target. */
13795 inferior_event_handler (INF_REG_EVENT, NULL);
13796 }
13797
13798 static void
13799 remote_async_inferior_event_handler (gdb_client_data data)
13800 {
13801 inferior_event_handler (INF_REG_EVENT, NULL);
13802 }
13803
13804 static void
13805 remote_async (struct target_ops *ops, int enable)
13806 {
13807 struct remote_state *rs = get_remote_state ();
13808
13809 if (enable)
13810 {
13811 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13812
13813 /* If there are pending events in the stop reply queue tell the
13814 event loop to process them. */
13815 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13816 mark_async_event_handler (remote_async_inferior_event_token);
13817 /* For simplicity, below we clear the pending events token
13818 without remembering whether it is marked, so here we always
13819 mark it. If there's actually no pending notification to
13820 process, this ends up being a no-op (other than a spurious
13821 event-loop wakeup). */
13822 if (target_is_non_stop_p ())
13823 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13824 }
13825 else
13826 {
13827 serial_async (rs->remote_desc, NULL, NULL);
13828 /* If the core is disabling async, it doesn't want to be
13829 disturbed with target events. Clear all async event sources
13830 too. */
13831 clear_async_event_handler (remote_async_inferior_event_token);
13832 if (target_is_non_stop_p ())
13833 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13834 }
13835 }
13836
13837 /* Implementation of the to_thread_events method. */
13838
13839 static void
13840 remote_thread_events (struct target_ops *ops, int enable)
13841 {
13842 struct remote_state *rs = get_remote_state ();
13843 size_t size = get_remote_packet_size ();
13844
13845 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13846 return;
13847
13848 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13849 putpkt (rs->buf);
13850 getpkt (&rs->buf, &rs->buf_size, 0);
13851
13852 switch (packet_ok (rs->buf,
13853 &remote_protocol_packets[PACKET_QThreadEvents]))
13854 {
13855 case PACKET_OK:
13856 if (strcmp (rs->buf, "OK") != 0)
13857 error (_("Remote refused setting thread events: %s"), rs->buf);
13858 break;
13859 case PACKET_ERROR:
13860 warning (_("Remote failure reply: %s"), rs->buf);
13861 break;
13862 case PACKET_UNKNOWN:
13863 break;
13864 }
13865 }
13866
13867 static void
13868 set_remote_cmd (char *args, int from_tty)
13869 {
13870 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13871 }
13872
13873 static void
13874 show_remote_cmd (char *args, int from_tty)
13875 {
13876 /* We can't just use cmd_show_list here, because we want to skip
13877 the redundant "show remote Z-packet" and the legacy aliases. */
13878 struct cmd_list_element *list = remote_show_cmdlist;
13879 struct ui_out *uiout = current_uiout;
13880
13881 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13882 for (; list != NULL; list = list->next)
13883 if (strcmp (list->name, "Z-packet") == 0)
13884 continue;
13885 else if (list->type == not_set_cmd)
13886 /* Alias commands are exactly like the original, except they
13887 don't have the normal type. */
13888 continue;
13889 else
13890 {
13891 ui_out_emit_tuple option_emitter (uiout, "option");
13892
13893 uiout->field_string ("name", list->name);
13894 uiout->text (": ");
13895 if (list->type == show_cmd)
13896 do_show_command (NULL, from_tty, list);
13897 else
13898 cmd_func (list, NULL, from_tty);
13899 }
13900 }
13901
13902
13903 /* Function to be called whenever a new objfile (shlib) is detected. */
13904 static void
13905 remote_new_objfile (struct objfile *objfile)
13906 {
13907 struct remote_state *rs = get_remote_state ();
13908
13909 if (rs->remote_desc != 0) /* Have a remote connection. */
13910 remote_check_symbols ();
13911 }
13912
13913 /* Pull all the tracepoints defined on the target and create local
13914 data structures representing them. We don't want to create real
13915 tracepoints yet, we don't want to mess up the user's existing
13916 collection. */
13917
13918 static int
13919 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13920 {
13921 struct remote_state *rs = get_remote_state ();
13922 char *p;
13923
13924 /* Ask for a first packet of tracepoint definition. */
13925 putpkt ("qTfP");
13926 getpkt (&rs->buf, &rs->buf_size, 0);
13927 p = rs->buf;
13928 while (*p && *p != 'l')
13929 {
13930 parse_tracepoint_definition (p, utpp);
13931 /* Ask for another packet of tracepoint definition. */
13932 putpkt ("qTsP");
13933 getpkt (&rs->buf, &rs->buf_size, 0);
13934 p = rs->buf;
13935 }
13936 return 0;
13937 }
13938
13939 static int
13940 remote_upload_trace_state_variables (struct target_ops *self,
13941 struct uploaded_tsv **utsvp)
13942 {
13943 struct remote_state *rs = get_remote_state ();
13944 char *p;
13945
13946 /* Ask for a first packet of variable definition. */
13947 putpkt ("qTfV");
13948 getpkt (&rs->buf, &rs->buf_size, 0);
13949 p = rs->buf;
13950 while (*p && *p != 'l')
13951 {
13952 parse_tsv_definition (p, utsvp);
13953 /* Ask for another packet of variable definition. */
13954 putpkt ("qTsV");
13955 getpkt (&rs->buf, &rs->buf_size, 0);
13956 p = rs->buf;
13957 }
13958 return 0;
13959 }
13960
13961 /* The "set/show range-stepping" show hook. */
13962
13963 static void
13964 show_range_stepping (struct ui_file *file, int from_tty,
13965 struct cmd_list_element *c,
13966 const char *value)
13967 {
13968 fprintf_filtered (file,
13969 _("Debugger's willingness to use range stepping "
13970 "is %s.\n"), value);
13971 }
13972
13973 /* The "set/show range-stepping" set hook. */
13974
13975 static void
13976 set_range_stepping (char *ignore_args, int from_tty,
13977 struct cmd_list_element *c)
13978 {
13979 struct remote_state *rs = get_remote_state ();
13980
13981 /* Whene enabling, check whether range stepping is actually
13982 supported by the target, and warn if not. */
13983 if (use_range_stepping)
13984 {
13985 if (rs->remote_desc != NULL)
13986 {
13987 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13988 remote_vcont_probe (rs);
13989
13990 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13991 && rs->supports_vCont.r)
13992 return;
13993 }
13994
13995 warning (_("Range stepping is not supported by the current target"));
13996 }
13997 }
13998
13999 void
14000 _initialize_remote (void)
14001 {
14002 struct cmd_list_element *cmd;
14003 const char *cmd_name;
14004
14005 /* architecture specific data */
14006 remote_gdbarch_data_handle =
14007 gdbarch_data_register_post_init (init_remote_state);
14008 remote_g_packet_data_handle =
14009 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14010
14011 remote_pspace_data
14012 = register_program_space_data_with_cleanup (NULL,
14013 remote_pspace_data_cleanup);
14014
14015 /* Initialize the per-target state. At the moment there is only one
14016 of these, not one per target. Only one target is active at a
14017 time. */
14018 remote_state = new_remote_state ();
14019
14020 init_remote_ops ();
14021 add_target (&remote_ops);
14022
14023 init_extended_remote_ops ();
14024 add_target (&extended_remote_ops);
14025
14026 /* Hook into new objfile notification. */
14027 observer_attach_new_objfile (remote_new_objfile);
14028 /* We're no longer interested in notification events of an inferior
14029 when it exits. */
14030 observer_attach_inferior_exit (discard_pending_stop_replies);
14031
14032 #if 0
14033 init_remote_threadtests ();
14034 #endif
14035
14036 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14037 /* set/show remote ... */
14038
14039 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14040 Remote protocol specific variables\n\
14041 Configure various remote-protocol specific variables such as\n\
14042 the packets being used"),
14043 &remote_set_cmdlist, "set remote ",
14044 0 /* allow-unknown */, &setlist);
14045 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14046 Remote protocol specific variables\n\
14047 Configure various remote-protocol specific variables such as\n\
14048 the packets being used"),
14049 &remote_show_cmdlist, "show remote ",
14050 0 /* allow-unknown */, &showlist);
14051
14052 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14053 Compare section data on target to the exec file.\n\
14054 Argument is a single section name (default: all loaded sections).\n\
14055 To compare only read-only loaded sections, specify the -r option."),
14056 &cmdlist);
14057
14058 add_cmd ("packet", class_maintenance, packet_command, _("\
14059 Send an arbitrary packet to a remote target.\n\
14060 maintenance packet TEXT\n\
14061 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14062 this command sends the string TEXT to the inferior, and displays the\n\
14063 response packet. GDB supplies the initial `$' character, and the\n\
14064 terminating `#' character and checksum."),
14065 &maintenancelist);
14066
14067 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14068 Set whether to send break if interrupted."), _("\
14069 Show whether to send break if interrupted."), _("\
14070 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14071 set_remotebreak, show_remotebreak,
14072 &setlist, &showlist);
14073 cmd_name = "remotebreak";
14074 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14075 deprecate_cmd (cmd, "set remote interrupt-sequence");
14076 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14077 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14078 deprecate_cmd (cmd, "show remote interrupt-sequence");
14079
14080 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14081 interrupt_sequence_modes, &interrupt_sequence_mode,
14082 _("\
14083 Set interrupt sequence to remote target."), _("\
14084 Show interrupt sequence to remote target."), _("\
14085 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14086 NULL, show_interrupt_sequence,
14087 &remote_set_cmdlist,
14088 &remote_show_cmdlist);
14089
14090 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14091 &interrupt_on_connect, _("\
14092 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14093 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14094 If set, interrupt sequence is sent to remote target."),
14095 NULL, NULL,
14096 &remote_set_cmdlist, &remote_show_cmdlist);
14097
14098 /* Install commands for configuring memory read/write packets. */
14099
14100 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14101 Set the maximum number of bytes per memory write packet (deprecated)."),
14102 &setlist);
14103 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14104 Show the maximum number of bytes per memory write packet (deprecated)."),
14105 &showlist);
14106 add_cmd ("memory-write-packet-size", no_class,
14107 set_memory_write_packet_size, _("\
14108 Set the maximum number of bytes per memory-write packet.\n\
14109 Specify the number of bytes in a packet or 0 (zero) for the\n\
14110 default packet size. The actual limit is further reduced\n\
14111 dependent on the target. Specify ``fixed'' to disable the\n\
14112 further restriction and ``limit'' to enable that restriction."),
14113 &remote_set_cmdlist);
14114 add_cmd ("memory-read-packet-size", no_class,
14115 set_memory_read_packet_size, _("\
14116 Set the maximum number of bytes per memory-read packet.\n\
14117 Specify the number of bytes in a packet or 0 (zero) for the\n\
14118 default packet size. The actual limit is further reduced\n\
14119 dependent on the target. Specify ``fixed'' to disable the\n\
14120 further restriction and ``limit'' to enable that restriction."),
14121 &remote_set_cmdlist);
14122 add_cmd ("memory-write-packet-size", no_class,
14123 show_memory_write_packet_size,
14124 _("Show the maximum number of bytes per memory-write packet."),
14125 &remote_show_cmdlist);
14126 add_cmd ("memory-read-packet-size", no_class,
14127 show_memory_read_packet_size,
14128 _("Show the maximum number of bytes per memory-read packet."),
14129 &remote_show_cmdlist);
14130
14131 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14132 &remote_hw_watchpoint_limit, _("\
14133 Set the maximum number of target hardware watchpoints."), _("\
14134 Show the maximum number of target hardware watchpoints."), _("\
14135 Specify a negative limit for unlimited."),
14136 NULL, NULL, /* FIXME: i18n: The maximum
14137 number of target hardware
14138 watchpoints is %s. */
14139 &remote_set_cmdlist, &remote_show_cmdlist);
14140 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14141 &remote_hw_watchpoint_length_limit, _("\
14142 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14143 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14144 Specify a negative limit for unlimited."),
14145 NULL, NULL, /* FIXME: i18n: The maximum
14146 length (in bytes) of a target
14147 hardware watchpoint is %s. */
14148 &remote_set_cmdlist, &remote_show_cmdlist);
14149 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14150 &remote_hw_breakpoint_limit, _("\
14151 Set the maximum number of target hardware breakpoints."), _("\
14152 Show the maximum number of target hardware breakpoints."), _("\
14153 Specify a negative limit for unlimited."),
14154 NULL, NULL, /* FIXME: i18n: The maximum
14155 number of target hardware
14156 breakpoints is %s. */
14157 &remote_set_cmdlist, &remote_show_cmdlist);
14158
14159 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14160 &remote_address_size, _("\
14161 Set the maximum size of the address (in bits) in a memory packet."), _("\
14162 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14163 NULL,
14164 NULL, /* FIXME: i18n: */
14165 &setlist, &showlist);
14166
14167 init_all_packet_configs ();
14168
14169 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14170 "X", "binary-download", 1);
14171
14172 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14173 "vCont", "verbose-resume", 0);
14174
14175 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14176 "QPassSignals", "pass-signals", 0);
14177
14178 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14179 "QCatchSyscalls", "catch-syscalls", 0);
14180
14181 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14182 "QProgramSignals", "program-signals", 0);
14183
14184 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14185 "QStartupWithShell", "startup-with-shell", 0);
14186
14187 add_packet_config_cmd (&remote_protocol_packets
14188 [PACKET_QEnvironmentHexEncoded],
14189 "QEnvironmentHexEncoded", "environment-hex-encoded",
14190 0);
14191
14192 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14193 "QEnvironmentReset", "environment-reset",
14194 0);
14195
14196 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14197 "QEnvironmentUnset", "environment-unset",
14198 0);
14199
14200 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14201 "qSymbol", "symbol-lookup", 0);
14202
14203 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14204 "P", "set-register", 1);
14205
14206 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14207 "p", "fetch-register", 1);
14208
14209 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14210 "Z0", "software-breakpoint", 0);
14211
14212 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14213 "Z1", "hardware-breakpoint", 0);
14214
14215 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14216 "Z2", "write-watchpoint", 0);
14217
14218 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14219 "Z3", "read-watchpoint", 0);
14220
14221 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14222 "Z4", "access-watchpoint", 0);
14223
14224 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14225 "qXfer:auxv:read", "read-aux-vector", 0);
14226
14227 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14228 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14229
14230 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14231 "qXfer:features:read", "target-features", 0);
14232
14233 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14234 "qXfer:libraries:read", "library-info", 0);
14235
14236 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14237 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14238
14239 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14240 "qXfer:memory-map:read", "memory-map", 0);
14241
14242 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14243 "qXfer:spu:read", "read-spu-object", 0);
14244
14245 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14246 "qXfer:spu:write", "write-spu-object", 0);
14247
14248 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14249 "qXfer:osdata:read", "osdata", 0);
14250
14251 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14252 "qXfer:threads:read", "threads", 0);
14253
14254 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14255 "qXfer:siginfo:read", "read-siginfo-object", 0);
14256
14257 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14258 "qXfer:siginfo:write", "write-siginfo-object", 0);
14259
14260 add_packet_config_cmd
14261 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14262 "qXfer:traceframe-info:read", "traceframe-info", 0);
14263
14264 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14265 "qXfer:uib:read", "unwind-info-block", 0);
14266
14267 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14268 "qGetTLSAddr", "get-thread-local-storage-address",
14269 0);
14270
14271 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14272 "qGetTIBAddr", "get-thread-information-block-address",
14273 0);
14274
14275 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14276 "bc", "reverse-continue", 0);
14277
14278 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14279 "bs", "reverse-step", 0);
14280
14281 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14282 "qSupported", "supported-packets", 0);
14283
14284 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14285 "qSearch:memory", "search-memory", 0);
14286
14287 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14288 "qTStatus", "trace-status", 0);
14289
14290 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14291 "vFile:setfs", "hostio-setfs", 0);
14292
14293 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14294 "vFile:open", "hostio-open", 0);
14295
14296 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14297 "vFile:pread", "hostio-pread", 0);
14298
14299 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14300 "vFile:pwrite", "hostio-pwrite", 0);
14301
14302 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14303 "vFile:close", "hostio-close", 0);
14304
14305 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14306 "vFile:unlink", "hostio-unlink", 0);
14307
14308 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14309 "vFile:readlink", "hostio-readlink", 0);
14310
14311 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14312 "vFile:fstat", "hostio-fstat", 0);
14313
14314 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14315 "vAttach", "attach", 0);
14316
14317 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14318 "vRun", "run", 0);
14319
14320 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14321 "QStartNoAckMode", "noack", 0);
14322
14323 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14324 "vKill", "kill", 0);
14325
14326 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14327 "qAttached", "query-attached", 0);
14328
14329 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14330 "ConditionalTracepoints",
14331 "conditional-tracepoints", 0);
14332
14333 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14334 "ConditionalBreakpoints",
14335 "conditional-breakpoints", 0);
14336
14337 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14338 "BreakpointCommands",
14339 "breakpoint-commands", 0);
14340
14341 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14342 "FastTracepoints", "fast-tracepoints", 0);
14343
14344 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14345 "TracepointSource", "TracepointSource", 0);
14346
14347 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14348 "QAllow", "allow", 0);
14349
14350 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14351 "StaticTracepoints", "static-tracepoints", 0);
14352
14353 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14354 "InstallInTrace", "install-in-trace", 0);
14355
14356 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14357 "qXfer:statictrace:read", "read-sdata-object", 0);
14358
14359 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14360 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14361
14362 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14363 "QDisableRandomization", "disable-randomization", 0);
14364
14365 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14366 "QAgent", "agent", 0);
14367
14368 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14369 "QTBuffer:size", "trace-buffer-size", 0);
14370
14371 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14372 "Qbtrace:off", "disable-btrace", 0);
14373
14374 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14375 "Qbtrace:bts", "enable-btrace-bts", 0);
14376
14377 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14378 "Qbtrace:pt", "enable-btrace-pt", 0);
14379
14380 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14381 "qXfer:btrace", "read-btrace", 0);
14382
14383 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14384 "qXfer:btrace-conf", "read-btrace-conf", 0);
14385
14386 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14387 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14388
14389 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14390 "multiprocess-feature", "multiprocess-feature", 0);
14391
14392 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14393 "swbreak-feature", "swbreak-feature", 0);
14394
14395 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14396 "hwbreak-feature", "hwbreak-feature", 0);
14397
14398 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14399 "fork-event-feature", "fork-event-feature", 0);
14400
14401 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14402 "vfork-event-feature", "vfork-event-feature", 0);
14403
14404 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14405 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14406
14407 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14408 "vContSupported", "verbose-resume-supported", 0);
14409
14410 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14411 "exec-event-feature", "exec-event-feature", 0);
14412
14413 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14414 "vCtrlC", "ctrl-c", 0);
14415
14416 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14417 "QThreadEvents", "thread-events", 0);
14418
14419 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14420 "N stop reply", "no-resumed-stop-reply", 0);
14421
14422 /* Assert that we've registered "set remote foo-packet" commands
14423 for all packet configs. */
14424 {
14425 int i;
14426
14427 for (i = 0; i < PACKET_MAX; i++)
14428 {
14429 /* Ideally all configs would have a command associated. Some
14430 still don't though. */
14431 int excepted;
14432
14433 switch (i)
14434 {
14435 case PACKET_QNonStop:
14436 case PACKET_EnableDisableTracepoints_feature:
14437 case PACKET_tracenz_feature:
14438 case PACKET_DisconnectedTracing_feature:
14439 case PACKET_augmented_libraries_svr4_read_feature:
14440 case PACKET_qCRC:
14441 /* Additions to this list need to be well justified:
14442 pre-existing packets are OK; new packets are not. */
14443 excepted = 1;
14444 break;
14445 default:
14446 excepted = 0;
14447 break;
14448 }
14449
14450 /* This catches both forgetting to add a config command, and
14451 forgetting to remove a packet from the exception list. */
14452 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14453 }
14454 }
14455
14456 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14457 Z sub-packet has its own set and show commands, but users may
14458 have sets to this variable in their .gdbinit files (or in their
14459 documentation). */
14460 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14461 &remote_Z_packet_detect, _("\
14462 Set use of remote protocol `Z' packets"), _("\
14463 Show use of remote protocol `Z' packets "), _("\
14464 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14465 packets."),
14466 set_remote_protocol_Z_packet_cmd,
14467 show_remote_protocol_Z_packet_cmd,
14468 /* FIXME: i18n: Use of remote protocol
14469 `Z' packets is %s. */
14470 &remote_set_cmdlist, &remote_show_cmdlist);
14471
14472 add_prefix_cmd ("remote", class_files, remote_command, _("\
14473 Manipulate files on the remote system\n\
14474 Transfer files to and from the remote target system."),
14475 &remote_cmdlist, "remote ",
14476 0 /* allow-unknown */, &cmdlist);
14477
14478 add_cmd ("put", class_files, remote_put_command,
14479 _("Copy a local file to the remote system."),
14480 &remote_cmdlist);
14481
14482 add_cmd ("get", class_files, remote_get_command,
14483 _("Copy a remote file to the local system."),
14484 &remote_cmdlist);
14485
14486 add_cmd ("delete", class_files, remote_delete_command,
14487 _("Delete a remote file."),
14488 &remote_cmdlist);
14489
14490 add_setshow_string_noescape_cmd ("exec-file", class_files,
14491 &remote_exec_file_var, _("\
14492 Set the remote pathname for \"run\""), _("\
14493 Show the remote pathname for \"run\""), NULL,
14494 set_remote_exec_file,
14495 show_remote_exec_file,
14496 &remote_set_cmdlist,
14497 &remote_show_cmdlist);
14498
14499 add_setshow_boolean_cmd ("range-stepping", class_run,
14500 &use_range_stepping, _("\
14501 Enable or disable range stepping."), _("\
14502 Show whether target-assisted range stepping is enabled."), _("\
14503 If on, and the target supports it, when stepping a source line, GDB\n\
14504 tells the target to step the corresponding range of addresses itself instead\n\
14505 of issuing multiple single-steps. This speeds up source level\n\
14506 stepping. If off, GDB always issues single-steps, even if range\n\
14507 stepping is supported by the target. The default is on."),
14508 set_range_stepping,
14509 show_range_stepping,
14510 &setlist,
14511 &showlist);
14512
14513 /* Eventually initialize fileio. See fileio.c */
14514 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14515
14516 /* Take advantage of the fact that the TID field is not used, to tag
14517 special ptids with it set to != 0. */
14518 magic_null_ptid = ptid_build (42000, -1, 1);
14519 not_sent_ptid = ptid_build (42000, -2, 1);
14520 any_thread_ptid = ptid_build (42000, 0, 1);
14521
14522 target_buf_size = 2048;
14523 target_buf = (char *) xmalloc (target_buf_size);
14524 }
14525