Add thread_handle_to_thread_info support for remote targets
[deliverable/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 void compare_sections_command (char *, int);
175
176 static void packet_command (char *, int);
177
178 static int stub_unpack_int (char *buff, int fieldlength);
179
180 static ptid_t remote_current_thread (ptid_t oldptid);
181
182 static int putpkt_binary (const char *buf, int cnt);
183
184 static void check_binary_download (CORE_ADDR addr);
185
186 struct packet_config;
187
188 static void show_packet_config_cmd (struct packet_config *config);
189
190 static void show_remote_protocol_packet_cmd (struct ui_file *file,
191 int from_tty,
192 struct cmd_list_element *c,
193 const char *value);
194
195 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
196 static ptid_t read_ptid (char *buf, char **obuf);
197
198 static void remote_set_permissions (struct target_ops *self);
199
200 static int remote_get_trace_status (struct target_ops *self,
201 struct trace_status *ts);
202
203 static int remote_upload_tracepoints (struct target_ops *self,
204 struct uploaded_tp **utpp);
205
206 static int remote_upload_trace_state_variables (struct target_ops *self,
207 struct uploaded_tsv **utsvp);
208
209 static void remote_query_supported (void);
210
211 static void remote_check_symbols (void);
212
213 struct stop_reply;
214 static void stop_reply_xfree (struct stop_reply *);
215 static void remote_parse_stop_reply (char *, struct stop_reply *);
216 static void push_stop_reply (struct stop_reply *);
217 static void discard_pending_stop_replies_in_queue (struct remote_state *);
218 static int peek_stop_reply (ptid_t ptid);
219
220 struct threads_listing_context;
221 static void remove_new_fork_children (struct threads_listing_context *);
222
223 static void remote_async_inferior_event_handler (gdb_client_data);
224
225 static void remote_terminal_ours (struct target_ops *self);
226
227 static int remote_read_description_p (struct target_ops *target);
228
229 static void remote_console_output (char *msg);
230
231 static int remote_supports_cond_breakpoints (struct target_ops *self);
232
233 static int remote_can_run_breakpoint_commands (struct target_ops *self);
234
235 static void remote_btrace_reset (void);
236
237 static void remote_btrace_maybe_reopen (void);
238
239 static int stop_reply_queue_length (void);
240
241 static void readahead_cache_invalidate (void);
242
243 static void remote_unpush_and_throw (void);
244
245 /* For "remote". */
246
247 static struct cmd_list_element *remote_cmdlist;
248
249 /* For "set remote" and "show remote". */
250
251 static struct cmd_list_element *remote_set_cmdlist;
252 static struct cmd_list_element *remote_show_cmdlist;
253
254 /* Stub vCont actions support.
255
256 Each field is a boolean flag indicating whether the stub reports
257 support for the corresponding action. */
258
259 struct vCont_action_support
260 {
261 /* vCont;t */
262 int t;
263
264 /* vCont;r */
265 int r;
266
267 /* vCont;s */
268 int s;
269
270 /* vCont;S */
271 int S;
272 };
273
274 /* Controls whether GDB is willing to use range stepping. */
275
276 static int use_range_stepping = 1;
277
278 #define OPAQUETHREADBYTES 8
279
280 /* a 64 bit opaque identifier */
281 typedef unsigned char threadref[OPAQUETHREADBYTES];
282
283 /* About this many threadisds fit in a packet. */
284
285 #define MAXTHREADLISTRESULTS 32
286
287 /* The max number of chars in debug output. The rest of chars are
288 omitted. */
289
290 #define REMOTE_DEBUG_MAX_CHAR 512
291
292 /* Data for the vFile:pread readahead cache. */
293
294 struct readahead_cache
295 {
296 /* The file descriptor for the file that is being cached. -1 if the
297 cache is invalid. */
298 int fd;
299
300 /* The offset into the file that the cache buffer corresponds
301 to. */
302 ULONGEST offset;
303
304 /* The buffer holding the cache contents. */
305 gdb_byte *buf;
306 /* The buffer's size. We try to read as much as fits into a packet
307 at a time. */
308 size_t bufsize;
309
310 /* Cache hit and miss counters. */
311 ULONGEST hit_count;
312 ULONGEST miss_count;
313 };
314
315 /* Description of the remote protocol state for the currently
316 connected target. This is per-target state, and independent of the
317 selected architecture. */
318
319 struct remote_state
320 {
321 /* A buffer to use for incoming packets, and its current size. The
322 buffer is grown dynamically for larger incoming packets.
323 Outgoing packets may also be constructed in this buffer.
324 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
325 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
326 packets. */
327 char *buf;
328 long buf_size;
329
330 /* True if we're going through initial connection setup (finding out
331 about the remote side's threads, relocating symbols, etc.). */
332 int starting_up;
333
334 /* If we negotiated packet size explicitly (and thus can bypass
335 heuristics for the largest packet size that will not overflow
336 a buffer in the stub), this will be set to that packet size.
337 Otherwise zero, meaning to use the guessed size. */
338 long explicit_packet_size;
339
340 /* remote_wait is normally called when the target is running and
341 waits for a stop reply packet. But sometimes we need to call it
342 when the target is already stopped. We can send a "?" packet
343 and have remote_wait read the response. Or, if we already have
344 the response, we can stash it in BUF and tell remote_wait to
345 skip calling getpkt. This flag is set when BUF contains a
346 stop reply packet and the target is not waiting. */
347 int cached_wait_status;
348
349 /* True, if in no ack mode. That is, neither GDB nor the stub will
350 expect acks from each other. The connection is assumed to be
351 reliable. */
352 int noack_mode;
353
354 /* True if we're connected in extended remote mode. */
355 int extended;
356
357 /* True if we resumed the target and we're waiting for the target to
358 stop. In the mean time, we can't start another command/query.
359 The remote server wouldn't be ready to process it, so we'd
360 timeout waiting for a reply that would never come and eventually
361 we'd close the connection. This can happen in asynchronous mode
362 because we allow GDB commands while the target is running. */
363 int waiting_for_stop_reply;
364
365 /* The status of the stub support for the various vCont actions. */
366 struct vCont_action_support supports_vCont;
367
368 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
369 responded to that. */
370 int ctrlc_pending_p;
371
372 /* True if we saw a Ctrl-C while reading or writing from/to the
373 remote descriptor. At that point it is not safe to send a remote
374 interrupt packet, so we instead remember we saw the Ctrl-C and
375 process it once we're done with sending/receiving the current
376 packet, which should be shortly. If however that takes too long,
377 and the user presses Ctrl-C again, we offer to disconnect. */
378 int got_ctrlc_during_io;
379
380 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
381 remote_open knows that we don't have a file open when the program
382 starts. */
383 struct serial *remote_desc;
384
385 /* These are the threads which we last sent to the remote system. The
386 TID member will be -1 for all or -2 for not sent yet. */
387 ptid_t general_thread;
388 ptid_t continue_thread;
389
390 /* This is the traceframe which we last selected on the remote system.
391 It will be -1 if no traceframe is selected. */
392 int remote_traceframe_number;
393
394 char *last_pass_packet;
395
396 /* The last QProgramSignals packet sent to the target. We bypass
397 sending a new program signals list down to the target if the new
398 packet is exactly the same as the last we sent. IOW, we only let
399 the target know about program signals list changes. */
400 char *last_program_signals_packet;
401
402 enum gdb_signal last_sent_signal;
403
404 int last_sent_step;
405
406 /* The execution direction of the last resume we got. */
407 enum exec_direction_kind last_resume_exec_dir;
408
409 char *finished_object;
410 char *finished_annex;
411 ULONGEST finished_offset;
412
413 /* Should we try the 'ThreadInfo' query packet?
414
415 This variable (NOT available to the user: auto-detect only!)
416 determines whether GDB will use the new, simpler "ThreadInfo"
417 query or the older, more complex syntax for thread queries.
418 This is an auto-detect variable (set to true at each connect,
419 and set to false when the target fails to recognize it). */
420 int use_threadinfo_query;
421 int use_threadextra_query;
422
423 threadref echo_nextthread;
424 threadref nextthread;
425 threadref resultthreadlist[MAXTHREADLISTRESULTS];
426
427 /* The state of remote notification. */
428 struct remote_notif_state *notif_state;
429
430 /* The branch trace configuration. */
431 struct btrace_config btrace_config;
432
433 /* The argument to the last "vFile:setfs:" packet we sent, used
434 to avoid sending repeated unnecessary "vFile:setfs:" packets.
435 Initialized to -1 to indicate that no "vFile:setfs:" packet
436 has yet been sent. */
437 int fs_pid;
438
439 /* A readahead cache for vFile:pread. Often, reading a binary
440 involves a sequence of small reads. E.g., when parsing an ELF
441 file. A readahead cache helps mostly the case of remote
442 debugging on a connection with higher latency, due to the
443 request/reply nature of the RSP. We only cache data for a single
444 file descriptor at a time. */
445 struct readahead_cache readahead_cache;
446 };
447
448 /* Private data that we'll store in (struct thread_info)->private. */
449 struct private_thread_info
450 {
451 char *extra;
452 char *name;
453 int core;
454
455 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
456 sequence of bytes. */
457 gdb::byte_vector *thread_handle;
458
459 /* Whether the target stopped for a breakpoint/watchpoint. */
460 enum target_stop_reason stop_reason;
461
462 /* This is set to the data address of the access causing the target
463 to stop for a watchpoint. */
464 CORE_ADDR watch_data_address;
465
466 /* Fields used by the vCont action coalescing implemented in
467 remote_resume / remote_commit_resume. remote_resume stores each
468 thread's last resume request in these fields, so that a later
469 remote_commit_resume knows which is the proper action for this
470 thread to include in the vCont packet. */
471
472 /* True if the last target_resume call for this thread was a step
473 request, false if a continue request. */
474 int last_resume_step;
475
476 /* The signal specified in the last target_resume call for this
477 thread. */
478 enum gdb_signal last_resume_sig;
479
480 /* Whether this thread was already vCont-resumed on the remote
481 side. */
482 int vcont_resumed;
483 };
484
485 static void
486 free_private_thread_info (struct private_thread_info *info)
487 {
488 xfree (info->extra);
489 xfree (info->name);
490 delete info->thread_handle;
491 xfree (info);
492 }
493
494 /* This data could be associated with a target, but we do not always
495 have access to the current target when we need it, so for now it is
496 static. This will be fine for as long as only one target is in use
497 at a time. */
498 static struct remote_state *remote_state;
499
500 static struct remote_state *
501 get_remote_state_raw (void)
502 {
503 return remote_state;
504 }
505
506 /* Allocate a new struct remote_state with xmalloc, initialize it, and
507 return it. */
508
509 static struct remote_state *
510 new_remote_state (void)
511 {
512 struct remote_state *result = XCNEW (struct remote_state);
513
514 /* The default buffer size is unimportant; it will be expanded
515 whenever a larger buffer is needed. */
516 result->buf_size = 400;
517 result->buf = (char *) xmalloc (result->buf_size);
518 result->remote_traceframe_number = -1;
519 result->last_sent_signal = GDB_SIGNAL_0;
520 result->last_resume_exec_dir = EXEC_FORWARD;
521 result->fs_pid = -1;
522
523 return result;
524 }
525
526 /* Description of the remote protocol for a given architecture. */
527
528 struct packet_reg
529 {
530 long offset; /* Offset into G packet. */
531 long regnum; /* GDB's internal register number. */
532 LONGEST pnum; /* Remote protocol register number. */
533 int in_g_packet; /* Always part of G packet. */
534 /* long size in bytes; == register_size (target_gdbarch (), regnum);
535 at present. */
536 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
537 at present. */
538 };
539
540 struct remote_arch_state
541 {
542 /* Description of the remote protocol registers. */
543 long sizeof_g_packet;
544
545 /* Description of the remote protocol registers indexed by REGNUM
546 (making an array gdbarch_num_regs in size). */
547 struct packet_reg *regs;
548
549 /* This is the size (in chars) of the first response to the ``g''
550 packet. It is used as a heuristic when determining the maximum
551 size of memory-read and memory-write packets. A target will
552 typically only reserve a buffer large enough to hold the ``g''
553 packet. The size does not include packet overhead (headers and
554 trailers). */
555 long actual_register_packet_size;
556
557 /* This is the maximum size (in chars) of a non read/write packet.
558 It is also used as a cap on the size of read/write packets. */
559 long remote_packet_size;
560 };
561
562 /* Utility: generate error from an incoming stub packet. */
563 static void
564 trace_error (char *buf)
565 {
566 if (*buf++ != 'E')
567 return; /* not an error msg */
568 switch (*buf)
569 {
570 case '1': /* malformed packet error */
571 if (*++buf == '0') /* general case: */
572 error (_("remote.c: error in outgoing packet."));
573 else
574 error (_("remote.c: error in outgoing packet at field #%ld."),
575 strtol (buf, NULL, 16));
576 default:
577 error (_("Target returns error code '%s'."), buf);
578 }
579 }
580
581 /* Utility: wait for reply from stub, while accepting "O" packets. */
582 static char *
583 remote_get_noisy_reply (char **buf_p,
584 long *sizeof_buf)
585 {
586 do /* Loop on reply from remote stub. */
587 {
588 char *buf;
589
590 QUIT; /* Allow user to bail out with ^C. */
591 getpkt (buf_p, sizeof_buf, 0);
592 buf = *buf_p;
593 if (buf[0] == 'E')
594 trace_error (buf);
595 else if (startswith (buf, "qRelocInsn:"))
596 {
597 ULONGEST ul;
598 CORE_ADDR from, to, org_to;
599 char *p, *pp;
600 int adjusted_size = 0;
601 int relocated = 0;
602
603 p = buf + strlen ("qRelocInsn:");
604 pp = unpack_varlen_hex (p, &ul);
605 if (*pp != ';')
606 error (_("invalid qRelocInsn packet: %s"), buf);
607 from = ul;
608
609 p = pp + 1;
610 unpack_varlen_hex (p, &ul);
611 to = ul;
612
613 org_to = to;
614
615 TRY
616 {
617 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
618 relocated = 1;
619 }
620 CATCH (ex, RETURN_MASK_ALL)
621 {
622 if (ex.error == MEMORY_ERROR)
623 {
624 /* Propagate memory errors silently back to the
625 target. The stub may have limited the range of
626 addresses we can write to, for example. */
627 }
628 else
629 {
630 /* Something unexpectedly bad happened. Be verbose
631 so we can tell what, and propagate the error back
632 to the stub, so it doesn't get stuck waiting for
633 a response. */
634 exception_fprintf (gdb_stderr, ex,
635 _("warning: relocating instruction: "));
636 }
637 putpkt ("E01");
638 }
639 END_CATCH
640
641 if (relocated)
642 {
643 adjusted_size = to - org_to;
644
645 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
646 putpkt (buf);
647 }
648 }
649 else if (buf[0] == 'O' && buf[1] != 'K')
650 remote_console_output (buf + 1); /* 'O' message from stub */
651 else
652 return buf; /* Here's the actual reply. */
653 }
654 while (1);
655 }
656
657 /* Handle for retreving the remote protocol data from gdbarch. */
658 static struct gdbarch_data *remote_gdbarch_data_handle;
659
660 static struct remote_arch_state *
661 get_remote_arch_state (void)
662 {
663 gdb_assert (target_gdbarch () != NULL);
664 return ((struct remote_arch_state *)
665 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
666 }
667
668 /* Fetch the global remote target state. */
669
670 static struct remote_state *
671 get_remote_state (void)
672 {
673 /* Make sure that the remote architecture state has been
674 initialized, because doing so might reallocate rs->buf. Any
675 function which calls getpkt also needs to be mindful of changes
676 to rs->buf, but this call limits the number of places which run
677 into trouble. */
678 get_remote_arch_state ();
679
680 return get_remote_state_raw ();
681 }
682
683 /* Cleanup routine for the remote module's pspace data. */
684
685 static void
686 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
687 {
688 char *remote_exec_file = (char *) arg;
689
690 xfree (remote_exec_file);
691 }
692
693 /* Fetch the remote exec-file from the current program space. */
694
695 static const char *
696 get_remote_exec_file (void)
697 {
698 char *remote_exec_file;
699
700 remote_exec_file
701 = (char *) program_space_data (current_program_space,
702 remote_pspace_data);
703 if (remote_exec_file == NULL)
704 return "";
705
706 return remote_exec_file;
707 }
708
709 /* Set the remote exec file for PSPACE. */
710
711 static void
712 set_pspace_remote_exec_file (struct program_space *pspace,
713 char *remote_exec_file)
714 {
715 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
716
717 xfree (old_file);
718 set_program_space_data (pspace, remote_pspace_data,
719 xstrdup (remote_exec_file));
720 }
721
722 /* The "set/show remote exec-file" set command hook. */
723
724 static void
725 set_remote_exec_file (char *ignored, int from_tty,
726 struct cmd_list_element *c)
727 {
728 gdb_assert (remote_exec_file_var != NULL);
729 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
730 }
731
732 /* The "set/show remote exec-file" show command hook. */
733
734 static void
735 show_remote_exec_file (struct ui_file *file, int from_tty,
736 struct cmd_list_element *cmd, const char *value)
737 {
738 fprintf_filtered (file, "%s\n", remote_exec_file_var);
739 }
740
741 static int
742 compare_pnums (const void *lhs_, const void *rhs_)
743 {
744 const struct packet_reg * const *lhs
745 = (const struct packet_reg * const *) lhs_;
746 const struct packet_reg * const *rhs
747 = (const struct packet_reg * const *) rhs_;
748
749 if ((*lhs)->pnum < (*rhs)->pnum)
750 return -1;
751 else if ((*lhs)->pnum == (*rhs)->pnum)
752 return 0;
753 else
754 return 1;
755 }
756
757 static int
758 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
759 {
760 int regnum, num_remote_regs, offset;
761 struct packet_reg **remote_regs;
762
763 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
764 {
765 struct packet_reg *r = &regs[regnum];
766
767 if (register_size (gdbarch, regnum) == 0)
768 /* Do not try to fetch zero-sized (placeholder) registers. */
769 r->pnum = -1;
770 else
771 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
772
773 r->regnum = regnum;
774 }
775
776 /* Define the g/G packet format as the contents of each register
777 with a remote protocol number, in order of ascending protocol
778 number. */
779
780 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
781 for (num_remote_regs = 0, regnum = 0;
782 regnum < gdbarch_num_regs (gdbarch);
783 regnum++)
784 if (regs[regnum].pnum != -1)
785 remote_regs[num_remote_regs++] = &regs[regnum];
786
787 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
788 compare_pnums);
789
790 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
791 {
792 remote_regs[regnum]->in_g_packet = 1;
793 remote_regs[regnum]->offset = offset;
794 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
795 }
796
797 return offset;
798 }
799
800 /* Given the architecture described by GDBARCH, return the remote
801 protocol register's number and the register's offset in the g/G
802 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
803 If the target does not have a mapping for REGNUM, return false,
804 otherwise, return true. */
805
806 int
807 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
808 int *pnum, int *poffset)
809 {
810 struct packet_reg *regs;
811 struct cleanup *old_chain;
812
813 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
814
815 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
816 old_chain = make_cleanup (xfree, regs);
817
818 map_regcache_remote_table (gdbarch, regs);
819
820 *pnum = regs[regnum].pnum;
821 *poffset = regs[regnum].offset;
822
823 do_cleanups (old_chain);
824
825 return *pnum != -1;
826 }
827
828 static void *
829 init_remote_state (struct gdbarch *gdbarch)
830 {
831 struct remote_state *rs = get_remote_state_raw ();
832 struct remote_arch_state *rsa;
833
834 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
835
836 /* Use the architecture to build a regnum<->pnum table, which will be
837 1:1 unless a feature set specifies otherwise. */
838 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
839 gdbarch_num_regs (gdbarch),
840 struct packet_reg);
841
842 /* Record the maximum possible size of the g packet - it may turn out
843 to be smaller. */
844 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
845
846 /* Default maximum number of characters in a packet body. Many
847 remote stubs have a hardwired buffer size of 400 bytes
848 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
849 as the maximum packet-size to ensure that the packet and an extra
850 NUL character can always fit in the buffer. This stops GDB
851 trashing stubs that try to squeeze an extra NUL into what is
852 already a full buffer (As of 1999-12-04 that was most stubs). */
853 rsa->remote_packet_size = 400 - 1;
854
855 /* This one is filled in when a ``g'' packet is received. */
856 rsa->actual_register_packet_size = 0;
857
858 /* Should rsa->sizeof_g_packet needs more space than the
859 default, adjust the size accordingly. Remember that each byte is
860 encoded as two characters. 32 is the overhead for the packet
861 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
862 (``$NN:G...#NN'') is a better guess, the below has been padded a
863 little. */
864 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
865 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
866
867 /* Make sure that the packet buffer is plenty big enough for
868 this architecture. */
869 if (rs->buf_size < rsa->remote_packet_size)
870 {
871 rs->buf_size = 2 * rsa->remote_packet_size;
872 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
873 }
874
875 return rsa;
876 }
877
878 /* Return the current allowed size of a remote packet. This is
879 inferred from the current architecture, and should be used to
880 limit the length of outgoing packets. */
881 static long
882 get_remote_packet_size (void)
883 {
884 struct remote_state *rs = get_remote_state ();
885 struct remote_arch_state *rsa = get_remote_arch_state ();
886
887 if (rs->explicit_packet_size)
888 return rs->explicit_packet_size;
889
890 return rsa->remote_packet_size;
891 }
892
893 static struct packet_reg *
894 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
895 {
896 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
897 return NULL;
898 else
899 {
900 struct packet_reg *r = &rsa->regs[regnum];
901
902 gdb_assert (r->regnum == regnum);
903 return r;
904 }
905 }
906
907 static struct packet_reg *
908 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
909 {
910 int i;
911
912 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
913 {
914 struct packet_reg *r = &rsa->regs[i];
915
916 if (r->pnum == pnum)
917 return r;
918 }
919 return NULL;
920 }
921
922 static struct target_ops remote_ops;
923
924 static struct target_ops extended_remote_ops;
925
926 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
927 ``forever'' still use the normal timeout mechanism. This is
928 currently used by the ASYNC code to guarentee that target reads
929 during the initial connect always time-out. Once getpkt has been
930 modified to return a timeout indication and, in turn
931 remote_wait()/wait_for_inferior() have gained a timeout parameter
932 this can go away. */
933 static int wait_forever_enabled_p = 1;
934
935 /* Allow the user to specify what sequence to send to the remote
936 when he requests a program interruption: Although ^C is usually
937 what remote systems expect (this is the default, here), it is
938 sometimes preferable to send a break. On other systems such
939 as the Linux kernel, a break followed by g, which is Magic SysRq g
940 is required in order to interrupt the execution. */
941 const char interrupt_sequence_control_c[] = "Ctrl-C";
942 const char interrupt_sequence_break[] = "BREAK";
943 const char interrupt_sequence_break_g[] = "BREAK-g";
944 static const char *const interrupt_sequence_modes[] =
945 {
946 interrupt_sequence_control_c,
947 interrupt_sequence_break,
948 interrupt_sequence_break_g,
949 NULL
950 };
951 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
952
953 static void
954 show_interrupt_sequence (struct ui_file *file, int from_tty,
955 struct cmd_list_element *c,
956 const char *value)
957 {
958 if (interrupt_sequence_mode == interrupt_sequence_control_c)
959 fprintf_filtered (file,
960 _("Send the ASCII ETX character (Ctrl-c) "
961 "to the remote target to interrupt the "
962 "execution of the program.\n"));
963 else if (interrupt_sequence_mode == interrupt_sequence_break)
964 fprintf_filtered (file,
965 _("send a break signal to the remote target "
966 "to interrupt the execution of the program.\n"));
967 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
968 fprintf_filtered (file,
969 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
970 "the remote target to interrupt the execution "
971 "of Linux kernel.\n"));
972 else
973 internal_error (__FILE__, __LINE__,
974 _("Invalid value for interrupt_sequence_mode: %s."),
975 interrupt_sequence_mode);
976 }
977
978 /* This boolean variable specifies whether interrupt_sequence is sent
979 to the remote target when gdb connects to it.
980 This is mostly needed when you debug the Linux kernel: The Linux kernel
981 expects BREAK g which is Magic SysRq g for connecting gdb. */
982 static int interrupt_on_connect = 0;
983
984 /* This variable is used to implement the "set/show remotebreak" commands.
985 Since these commands are now deprecated in favor of "set/show remote
986 interrupt-sequence", it no longer has any effect on the code. */
987 static int remote_break;
988
989 static void
990 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
991 {
992 if (remote_break)
993 interrupt_sequence_mode = interrupt_sequence_break;
994 else
995 interrupt_sequence_mode = interrupt_sequence_control_c;
996 }
997
998 static void
999 show_remotebreak (struct ui_file *file, int from_tty,
1000 struct cmd_list_element *c,
1001 const char *value)
1002 {
1003 }
1004
1005 /* This variable sets the number of bits in an address that are to be
1006 sent in a memory ("M" or "m") packet. Normally, after stripping
1007 leading zeros, the entire address would be sent. This variable
1008 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1009 initial implementation of remote.c restricted the address sent in
1010 memory packets to ``host::sizeof long'' bytes - (typically 32
1011 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1012 address was never sent. Since fixing this bug may cause a break in
1013 some remote targets this variable is principly provided to
1014 facilitate backward compatibility. */
1015
1016 static unsigned int remote_address_size;
1017
1018 /* Temporary to track who currently owns the terminal. See
1019 remote_terminal_* for more details. */
1020
1021 static int remote_async_terminal_ours_p;
1022
1023 \f
1024 /* User configurable variables for the number of characters in a
1025 memory read/write packet. MIN (rsa->remote_packet_size,
1026 rsa->sizeof_g_packet) is the default. Some targets need smaller
1027 values (fifo overruns, et.al.) and some users need larger values
1028 (speed up transfers). The variables ``preferred_*'' (the user
1029 request), ``current_*'' (what was actually set) and ``forced_*''
1030 (Positive - a soft limit, negative - a hard limit). */
1031
1032 struct memory_packet_config
1033 {
1034 const char *name;
1035 long size;
1036 int fixed_p;
1037 };
1038
1039 /* The default max memory-write-packet-size. The 16k is historical.
1040 (It came from older GDB's using alloca for buffers and the
1041 knowledge (folklore?) that some hosts don't cope very well with
1042 large alloca calls.) */
1043 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1044
1045 /* The minimum remote packet size for memory transfers. Ensures we
1046 can write at least one byte. */
1047 #define MIN_MEMORY_PACKET_SIZE 20
1048
1049 /* Compute the current size of a read/write packet. Since this makes
1050 use of ``actual_register_packet_size'' the computation is dynamic. */
1051
1052 static long
1053 get_memory_packet_size (struct memory_packet_config *config)
1054 {
1055 struct remote_state *rs = get_remote_state ();
1056 struct remote_arch_state *rsa = get_remote_arch_state ();
1057
1058 long what_they_get;
1059 if (config->fixed_p)
1060 {
1061 if (config->size <= 0)
1062 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1063 else
1064 what_they_get = config->size;
1065 }
1066 else
1067 {
1068 what_they_get = get_remote_packet_size ();
1069 /* Limit the packet to the size specified by the user. */
1070 if (config->size > 0
1071 && what_they_get > config->size)
1072 what_they_get = config->size;
1073
1074 /* Limit it to the size of the targets ``g'' response unless we have
1075 permission from the stub to use a larger packet size. */
1076 if (rs->explicit_packet_size == 0
1077 && rsa->actual_register_packet_size > 0
1078 && what_they_get > rsa->actual_register_packet_size)
1079 what_they_get = rsa->actual_register_packet_size;
1080 }
1081 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1082 what_they_get = MIN_MEMORY_PACKET_SIZE;
1083
1084 /* Make sure there is room in the global buffer for this packet
1085 (including its trailing NUL byte). */
1086 if (rs->buf_size < what_they_get + 1)
1087 {
1088 rs->buf_size = 2 * what_they_get;
1089 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1090 }
1091
1092 return what_they_get;
1093 }
1094
1095 /* Update the size of a read/write packet. If they user wants
1096 something really big then do a sanity check. */
1097
1098 static void
1099 set_memory_packet_size (char *args, struct memory_packet_config *config)
1100 {
1101 int fixed_p = config->fixed_p;
1102 long size = config->size;
1103
1104 if (args == NULL)
1105 error (_("Argument required (integer, `fixed' or `limited')."));
1106 else if (strcmp (args, "hard") == 0
1107 || strcmp (args, "fixed") == 0)
1108 fixed_p = 1;
1109 else if (strcmp (args, "soft") == 0
1110 || strcmp (args, "limit") == 0)
1111 fixed_p = 0;
1112 else
1113 {
1114 char *end;
1115
1116 size = strtoul (args, &end, 0);
1117 if (args == end)
1118 error (_("Invalid %s (bad syntax)."), config->name);
1119
1120 /* Instead of explicitly capping the size of a packet to or
1121 disallowing it, the user is allowed to set the size to
1122 something arbitrarily large. */
1123 }
1124
1125 /* So that the query shows the correct value. */
1126 if (size <= 0)
1127 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1128
1129 /* Extra checks? */
1130 if (fixed_p && !config->fixed_p)
1131 {
1132 if (! query (_("The target may not be able to correctly handle a %s\n"
1133 "of %ld bytes. Change the packet size? "),
1134 config->name, size))
1135 error (_("Packet size not changed."));
1136 }
1137 /* Update the config. */
1138 config->fixed_p = fixed_p;
1139 config->size = size;
1140 }
1141
1142 static void
1143 show_memory_packet_size (struct memory_packet_config *config)
1144 {
1145 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1146 if (config->fixed_p)
1147 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1148 get_memory_packet_size (config));
1149 else
1150 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1151 get_memory_packet_size (config));
1152 }
1153
1154 static struct memory_packet_config memory_write_packet_config =
1155 {
1156 "memory-write-packet-size",
1157 };
1158
1159 static void
1160 set_memory_write_packet_size (char *args, int from_tty)
1161 {
1162 set_memory_packet_size (args, &memory_write_packet_config);
1163 }
1164
1165 static void
1166 show_memory_write_packet_size (char *args, int from_tty)
1167 {
1168 show_memory_packet_size (&memory_write_packet_config);
1169 }
1170
1171 static long
1172 get_memory_write_packet_size (void)
1173 {
1174 return get_memory_packet_size (&memory_write_packet_config);
1175 }
1176
1177 static struct memory_packet_config memory_read_packet_config =
1178 {
1179 "memory-read-packet-size",
1180 };
1181
1182 static void
1183 set_memory_read_packet_size (char *args, int from_tty)
1184 {
1185 set_memory_packet_size (args, &memory_read_packet_config);
1186 }
1187
1188 static void
1189 show_memory_read_packet_size (char *args, int from_tty)
1190 {
1191 show_memory_packet_size (&memory_read_packet_config);
1192 }
1193
1194 static long
1195 get_memory_read_packet_size (void)
1196 {
1197 long size = get_memory_packet_size (&memory_read_packet_config);
1198
1199 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1200 extra buffer size argument before the memory read size can be
1201 increased beyond this. */
1202 if (size > get_remote_packet_size ())
1203 size = get_remote_packet_size ();
1204 return size;
1205 }
1206
1207 \f
1208 /* Generic configuration support for packets the stub optionally
1209 supports. Allows the user to specify the use of the packet as well
1210 as allowing GDB to auto-detect support in the remote stub. */
1211
1212 enum packet_support
1213 {
1214 PACKET_SUPPORT_UNKNOWN = 0,
1215 PACKET_ENABLE,
1216 PACKET_DISABLE
1217 };
1218
1219 struct packet_config
1220 {
1221 const char *name;
1222 const char *title;
1223
1224 /* If auto, GDB auto-detects support for this packet or feature,
1225 either through qSupported, or by trying the packet and looking
1226 at the response. If true, GDB assumes the target supports this
1227 packet. If false, the packet is disabled. Configs that don't
1228 have an associated command always have this set to auto. */
1229 enum auto_boolean detect;
1230
1231 /* Does the target support this packet? */
1232 enum packet_support support;
1233 };
1234
1235 /* Analyze a packet's return value and update the packet config
1236 accordingly. */
1237
1238 enum packet_result
1239 {
1240 PACKET_ERROR,
1241 PACKET_OK,
1242 PACKET_UNKNOWN
1243 };
1244
1245 static enum packet_support packet_config_support (struct packet_config *config);
1246 static enum packet_support packet_support (int packet);
1247
1248 static void
1249 show_packet_config_cmd (struct packet_config *config)
1250 {
1251 const char *support = "internal-error";
1252
1253 switch (packet_config_support (config))
1254 {
1255 case PACKET_ENABLE:
1256 support = "enabled";
1257 break;
1258 case PACKET_DISABLE:
1259 support = "disabled";
1260 break;
1261 case PACKET_SUPPORT_UNKNOWN:
1262 support = "unknown";
1263 break;
1264 }
1265 switch (config->detect)
1266 {
1267 case AUTO_BOOLEAN_AUTO:
1268 printf_filtered (_("Support for the `%s' packet "
1269 "is auto-detected, currently %s.\n"),
1270 config->name, support);
1271 break;
1272 case AUTO_BOOLEAN_TRUE:
1273 case AUTO_BOOLEAN_FALSE:
1274 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1275 config->name, support);
1276 break;
1277 }
1278 }
1279
1280 static void
1281 add_packet_config_cmd (struct packet_config *config, const char *name,
1282 const char *title, int legacy)
1283 {
1284 char *set_doc;
1285 char *show_doc;
1286 char *cmd_name;
1287
1288 config->name = name;
1289 config->title = title;
1290 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1291 name, title);
1292 show_doc = xstrprintf ("Show current use of remote "
1293 "protocol `%s' (%s) packet",
1294 name, title);
1295 /* set/show TITLE-packet {auto,on,off} */
1296 cmd_name = xstrprintf ("%s-packet", title);
1297 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1298 &config->detect, set_doc,
1299 show_doc, NULL, /* help_doc */
1300 NULL,
1301 show_remote_protocol_packet_cmd,
1302 &remote_set_cmdlist, &remote_show_cmdlist);
1303 /* The command code copies the documentation strings. */
1304 xfree (set_doc);
1305 xfree (show_doc);
1306 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1307 if (legacy)
1308 {
1309 char *legacy_name;
1310
1311 legacy_name = xstrprintf ("%s-packet", name);
1312 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1313 &remote_set_cmdlist);
1314 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1315 &remote_show_cmdlist);
1316 }
1317 }
1318
1319 static enum packet_result
1320 packet_check_result (const char *buf)
1321 {
1322 if (buf[0] != '\0')
1323 {
1324 /* The stub recognized the packet request. Check that the
1325 operation succeeded. */
1326 if (buf[0] == 'E'
1327 && isxdigit (buf[1]) && isxdigit (buf[2])
1328 && buf[3] == '\0')
1329 /* "Enn" - definitly an error. */
1330 return PACKET_ERROR;
1331
1332 /* Always treat "E." as an error. This will be used for
1333 more verbose error messages, such as E.memtypes. */
1334 if (buf[0] == 'E' && buf[1] == '.')
1335 return PACKET_ERROR;
1336
1337 /* The packet may or may not be OK. Just assume it is. */
1338 return PACKET_OK;
1339 }
1340 else
1341 /* The stub does not support the packet. */
1342 return PACKET_UNKNOWN;
1343 }
1344
1345 static enum packet_result
1346 packet_ok (const char *buf, struct packet_config *config)
1347 {
1348 enum packet_result result;
1349
1350 if (config->detect != AUTO_BOOLEAN_TRUE
1351 && config->support == PACKET_DISABLE)
1352 internal_error (__FILE__, __LINE__,
1353 _("packet_ok: attempt to use a disabled packet"));
1354
1355 result = packet_check_result (buf);
1356 switch (result)
1357 {
1358 case PACKET_OK:
1359 case PACKET_ERROR:
1360 /* The stub recognized the packet request. */
1361 if (config->support == PACKET_SUPPORT_UNKNOWN)
1362 {
1363 if (remote_debug)
1364 fprintf_unfiltered (gdb_stdlog,
1365 "Packet %s (%s) is supported\n",
1366 config->name, config->title);
1367 config->support = PACKET_ENABLE;
1368 }
1369 break;
1370 case PACKET_UNKNOWN:
1371 /* The stub does not support the packet. */
1372 if (config->detect == AUTO_BOOLEAN_AUTO
1373 && config->support == PACKET_ENABLE)
1374 {
1375 /* If the stub previously indicated that the packet was
1376 supported then there is a protocol error. */
1377 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1378 config->name, config->title);
1379 }
1380 else if (config->detect == AUTO_BOOLEAN_TRUE)
1381 {
1382 /* The user set it wrong. */
1383 error (_("Enabled packet %s (%s) not recognized by stub"),
1384 config->name, config->title);
1385 }
1386
1387 if (remote_debug)
1388 fprintf_unfiltered (gdb_stdlog,
1389 "Packet %s (%s) is NOT supported\n",
1390 config->name, config->title);
1391 config->support = PACKET_DISABLE;
1392 break;
1393 }
1394
1395 return result;
1396 }
1397
1398 enum {
1399 PACKET_vCont = 0,
1400 PACKET_X,
1401 PACKET_qSymbol,
1402 PACKET_P,
1403 PACKET_p,
1404 PACKET_Z0,
1405 PACKET_Z1,
1406 PACKET_Z2,
1407 PACKET_Z3,
1408 PACKET_Z4,
1409 PACKET_vFile_setfs,
1410 PACKET_vFile_open,
1411 PACKET_vFile_pread,
1412 PACKET_vFile_pwrite,
1413 PACKET_vFile_close,
1414 PACKET_vFile_unlink,
1415 PACKET_vFile_readlink,
1416 PACKET_vFile_fstat,
1417 PACKET_qXfer_auxv,
1418 PACKET_qXfer_features,
1419 PACKET_qXfer_exec_file,
1420 PACKET_qXfer_libraries,
1421 PACKET_qXfer_libraries_svr4,
1422 PACKET_qXfer_memory_map,
1423 PACKET_qXfer_spu_read,
1424 PACKET_qXfer_spu_write,
1425 PACKET_qXfer_osdata,
1426 PACKET_qXfer_threads,
1427 PACKET_qXfer_statictrace_read,
1428 PACKET_qXfer_traceframe_info,
1429 PACKET_qXfer_uib,
1430 PACKET_qGetTIBAddr,
1431 PACKET_qGetTLSAddr,
1432 PACKET_qSupported,
1433 PACKET_qTStatus,
1434 PACKET_QPassSignals,
1435 PACKET_QCatchSyscalls,
1436 PACKET_QProgramSignals,
1437 PACKET_QStartupWithShell,
1438 PACKET_QEnvironmentHexEncoded,
1439 PACKET_QEnvironmentReset,
1440 PACKET_QEnvironmentUnset,
1441 PACKET_qCRC,
1442 PACKET_qSearch_memory,
1443 PACKET_vAttach,
1444 PACKET_vRun,
1445 PACKET_QStartNoAckMode,
1446 PACKET_vKill,
1447 PACKET_qXfer_siginfo_read,
1448 PACKET_qXfer_siginfo_write,
1449 PACKET_qAttached,
1450
1451 /* Support for conditional tracepoints. */
1452 PACKET_ConditionalTracepoints,
1453
1454 /* Support for target-side breakpoint conditions. */
1455 PACKET_ConditionalBreakpoints,
1456
1457 /* Support for target-side breakpoint commands. */
1458 PACKET_BreakpointCommands,
1459
1460 /* Support for fast tracepoints. */
1461 PACKET_FastTracepoints,
1462
1463 /* Support for static tracepoints. */
1464 PACKET_StaticTracepoints,
1465
1466 /* Support for installing tracepoints while a trace experiment is
1467 running. */
1468 PACKET_InstallInTrace,
1469
1470 PACKET_bc,
1471 PACKET_bs,
1472 PACKET_TracepointSource,
1473 PACKET_QAllow,
1474 PACKET_qXfer_fdpic,
1475 PACKET_QDisableRandomization,
1476 PACKET_QAgent,
1477 PACKET_QTBuffer_size,
1478 PACKET_Qbtrace_off,
1479 PACKET_Qbtrace_bts,
1480 PACKET_Qbtrace_pt,
1481 PACKET_qXfer_btrace,
1482
1483 /* Support for the QNonStop packet. */
1484 PACKET_QNonStop,
1485
1486 /* Support for the QThreadEvents packet. */
1487 PACKET_QThreadEvents,
1488
1489 /* Support for multi-process extensions. */
1490 PACKET_multiprocess_feature,
1491
1492 /* Support for enabling and disabling tracepoints while a trace
1493 experiment is running. */
1494 PACKET_EnableDisableTracepoints_feature,
1495
1496 /* Support for collecting strings using the tracenz bytecode. */
1497 PACKET_tracenz_feature,
1498
1499 /* Support for continuing to run a trace experiment while GDB is
1500 disconnected. */
1501 PACKET_DisconnectedTracing_feature,
1502
1503 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1504 PACKET_augmented_libraries_svr4_read_feature,
1505
1506 /* Support for the qXfer:btrace-conf:read packet. */
1507 PACKET_qXfer_btrace_conf,
1508
1509 /* Support for the Qbtrace-conf:bts:size packet. */
1510 PACKET_Qbtrace_conf_bts_size,
1511
1512 /* Support for swbreak+ feature. */
1513 PACKET_swbreak_feature,
1514
1515 /* Support for hwbreak+ feature. */
1516 PACKET_hwbreak_feature,
1517
1518 /* Support for fork events. */
1519 PACKET_fork_event_feature,
1520
1521 /* Support for vfork events. */
1522 PACKET_vfork_event_feature,
1523
1524 /* Support for the Qbtrace-conf:pt:size packet. */
1525 PACKET_Qbtrace_conf_pt_size,
1526
1527 /* Support for exec events. */
1528 PACKET_exec_event_feature,
1529
1530 /* Support for query supported vCont actions. */
1531 PACKET_vContSupported,
1532
1533 /* Support remote CTRL-C. */
1534 PACKET_vCtrlC,
1535
1536 /* Support TARGET_WAITKIND_NO_RESUMED. */
1537 PACKET_no_resumed,
1538
1539 PACKET_MAX
1540 };
1541
1542 static struct packet_config remote_protocol_packets[PACKET_MAX];
1543
1544 /* Returns the packet's corresponding "set remote foo-packet" command
1545 state. See struct packet_config for more details. */
1546
1547 static enum auto_boolean
1548 packet_set_cmd_state (int packet)
1549 {
1550 return remote_protocol_packets[packet].detect;
1551 }
1552
1553 /* Returns whether a given packet or feature is supported. This takes
1554 into account the state of the corresponding "set remote foo-packet"
1555 command, which may be used to bypass auto-detection. */
1556
1557 static enum packet_support
1558 packet_config_support (struct packet_config *config)
1559 {
1560 switch (config->detect)
1561 {
1562 case AUTO_BOOLEAN_TRUE:
1563 return PACKET_ENABLE;
1564 case AUTO_BOOLEAN_FALSE:
1565 return PACKET_DISABLE;
1566 case AUTO_BOOLEAN_AUTO:
1567 return config->support;
1568 default:
1569 gdb_assert_not_reached (_("bad switch"));
1570 }
1571 }
1572
1573 /* Same as packet_config_support, but takes the packet's enum value as
1574 argument. */
1575
1576 static enum packet_support
1577 packet_support (int packet)
1578 {
1579 struct packet_config *config = &remote_protocol_packets[packet];
1580
1581 return packet_config_support (config);
1582 }
1583
1584 static void
1585 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1586 struct cmd_list_element *c,
1587 const char *value)
1588 {
1589 struct packet_config *packet;
1590
1591 for (packet = remote_protocol_packets;
1592 packet < &remote_protocol_packets[PACKET_MAX];
1593 packet++)
1594 {
1595 if (&packet->detect == c->var)
1596 {
1597 show_packet_config_cmd (packet);
1598 return;
1599 }
1600 }
1601 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1602 c->name);
1603 }
1604
1605 /* Should we try one of the 'Z' requests? */
1606
1607 enum Z_packet_type
1608 {
1609 Z_PACKET_SOFTWARE_BP,
1610 Z_PACKET_HARDWARE_BP,
1611 Z_PACKET_WRITE_WP,
1612 Z_PACKET_READ_WP,
1613 Z_PACKET_ACCESS_WP,
1614 NR_Z_PACKET_TYPES
1615 };
1616
1617 /* For compatibility with older distributions. Provide a ``set remote
1618 Z-packet ...'' command that updates all the Z packet types. */
1619
1620 static enum auto_boolean remote_Z_packet_detect;
1621
1622 static void
1623 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1624 struct cmd_list_element *c)
1625 {
1626 int i;
1627
1628 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1629 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1630 }
1631
1632 static void
1633 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1634 struct cmd_list_element *c,
1635 const char *value)
1636 {
1637 int i;
1638
1639 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1640 {
1641 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1642 }
1643 }
1644
1645 /* Returns true if the multi-process extensions are in effect. */
1646
1647 static int
1648 remote_multi_process_p (struct remote_state *rs)
1649 {
1650 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1651 }
1652
1653 /* Returns true if fork events are supported. */
1654
1655 static int
1656 remote_fork_event_p (struct remote_state *rs)
1657 {
1658 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1659 }
1660
1661 /* Returns true if vfork events are supported. */
1662
1663 static int
1664 remote_vfork_event_p (struct remote_state *rs)
1665 {
1666 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1667 }
1668
1669 /* Returns true if exec events are supported. */
1670
1671 static int
1672 remote_exec_event_p (struct remote_state *rs)
1673 {
1674 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1675 }
1676
1677 /* Insert fork catchpoint target routine. If fork events are enabled
1678 then return success, nothing more to do. */
1679
1680 static int
1681 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1682 {
1683 struct remote_state *rs = get_remote_state ();
1684
1685 return !remote_fork_event_p (rs);
1686 }
1687
1688 /* Remove fork catchpoint target routine. Nothing to do, just
1689 return success. */
1690
1691 static int
1692 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1693 {
1694 return 0;
1695 }
1696
1697 /* Insert vfork catchpoint target routine. If vfork events are enabled
1698 then return success, nothing more to do. */
1699
1700 static int
1701 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1702 {
1703 struct remote_state *rs = get_remote_state ();
1704
1705 return !remote_vfork_event_p (rs);
1706 }
1707
1708 /* Remove vfork catchpoint target routine. Nothing to do, just
1709 return success. */
1710
1711 static int
1712 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1713 {
1714 return 0;
1715 }
1716
1717 /* Insert exec catchpoint target routine. If exec events are
1718 enabled, just return success. */
1719
1720 static int
1721 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1722 {
1723 struct remote_state *rs = get_remote_state ();
1724
1725 return !remote_exec_event_p (rs);
1726 }
1727
1728 /* Remove exec catchpoint target routine. Nothing to do, just
1729 return success. */
1730
1731 static int
1732 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1733 {
1734 return 0;
1735 }
1736
1737 \f
1738 /* Asynchronous signal handle registered as event loop source for
1739 when we have pending events ready to be passed to the core. */
1740
1741 static struct async_event_handler *remote_async_inferior_event_token;
1742
1743 \f
1744
1745 static ptid_t magic_null_ptid;
1746 static ptid_t not_sent_ptid;
1747 static ptid_t any_thread_ptid;
1748
1749 /* Find out if the stub attached to PID (and hence GDB should offer to
1750 detach instead of killing it when bailing out). */
1751
1752 static int
1753 remote_query_attached (int pid)
1754 {
1755 struct remote_state *rs = get_remote_state ();
1756 size_t size = get_remote_packet_size ();
1757
1758 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1759 return 0;
1760
1761 if (remote_multi_process_p (rs))
1762 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1763 else
1764 xsnprintf (rs->buf, size, "qAttached");
1765
1766 putpkt (rs->buf);
1767 getpkt (&rs->buf, &rs->buf_size, 0);
1768
1769 switch (packet_ok (rs->buf,
1770 &remote_protocol_packets[PACKET_qAttached]))
1771 {
1772 case PACKET_OK:
1773 if (strcmp (rs->buf, "1") == 0)
1774 return 1;
1775 break;
1776 case PACKET_ERROR:
1777 warning (_("Remote failure reply: %s"), rs->buf);
1778 break;
1779 case PACKET_UNKNOWN:
1780 break;
1781 }
1782
1783 return 0;
1784 }
1785
1786 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1787 has been invented by GDB, instead of reported by the target. Since
1788 we can be connected to a remote system before before knowing about
1789 any inferior, mark the target with execution when we find the first
1790 inferior. If ATTACHED is 1, then we had just attached to this
1791 inferior. If it is 0, then we just created this inferior. If it
1792 is -1, then try querying the remote stub to find out if it had
1793 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1794 attempt to open this inferior's executable as the main executable
1795 if no main executable is open already. */
1796
1797 static struct inferior *
1798 remote_add_inferior (int fake_pid_p, int pid, int attached,
1799 int try_open_exec)
1800 {
1801 struct inferior *inf;
1802
1803 /* Check whether this process we're learning about is to be
1804 considered attached, or if is to be considered to have been
1805 spawned by the stub. */
1806 if (attached == -1)
1807 attached = remote_query_attached (pid);
1808
1809 if (gdbarch_has_global_solist (target_gdbarch ()))
1810 {
1811 /* If the target shares code across all inferiors, then every
1812 attach adds a new inferior. */
1813 inf = add_inferior (pid);
1814
1815 /* ... and every inferior is bound to the same program space.
1816 However, each inferior may still have its own address
1817 space. */
1818 inf->aspace = maybe_new_address_space ();
1819 inf->pspace = current_program_space;
1820 }
1821 else
1822 {
1823 /* In the traditional debugging scenario, there's a 1-1 match
1824 between program/address spaces. We simply bind the inferior
1825 to the program space's address space. */
1826 inf = current_inferior ();
1827 inferior_appeared (inf, pid);
1828 }
1829
1830 inf->attach_flag = attached;
1831 inf->fake_pid_p = fake_pid_p;
1832
1833 /* If no main executable is currently open then attempt to
1834 open the file that was executed to create this inferior. */
1835 if (try_open_exec && get_exec_file (0) == NULL)
1836 exec_file_locate_attach (pid, 0, 1);
1837
1838 return inf;
1839 }
1840
1841 static struct private_thread_info *
1842 get_private_info_thread (struct thread_info *info);
1843
1844 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1845 according to RUNNING. */
1846
1847 static void
1848 remote_add_thread (ptid_t ptid, int running, int executing)
1849 {
1850 struct remote_state *rs = get_remote_state ();
1851 struct thread_info *thread;
1852
1853 /* GDB historically didn't pull threads in the initial connection
1854 setup. If the remote target doesn't even have a concept of
1855 threads (e.g., a bare-metal target), even if internally we
1856 consider that a single-threaded target, mentioning a new thread
1857 might be confusing to the user. Be silent then, preserving the
1858 age old behavior. */
1859 if (rs->starting_up)
1860 thread = add_thread_silent (ptid);
1861 else
1862 thread = add_thread (ptid);
1863
1864 get_private_info_thread (thread)->vcont_resumed = executing;
1865 set_executing (ptid, executing);
1866 set_running (ptid, running);
1867 }
1868
1869 /* Come here when we learn about a thread id from the remote target.
1870 It may be the first time we hear about such thread, so take the
1871 opportunity to add it to GDB's thread list. In case this is the
1872 first time we're noticing its corresponding inferior, add it to
1873 GDB's inferior list as well. EXECUTING indicates whether the
1874 thread is (internally) executing or stopped. */
1875
1876 static void
1877 remote_notice_new_inferior (ptid_t currthread, int executing)
1878 {
1879 /* In non-stop mode, we assume new found threads are (externally)
1880 running until proven otherwise with a stop reply. In all-stop,
1881 we can only get here if all threads are stopped. */
1882 int running = target_is_non_stop_p () ? 1 : 0;
1883
1884 /* If this is a new thread, add it to GDB's thread list.
1885 If we leave it up to WFI to do this, bad things will happen. */
1886
1887 if (in_thread_list (currthread) && is_exited (currthread))
1888 {
1889 /* We're seeing an event on a thread id we knew had exited.
1890 This has to be a new thread reusing the old id. Add it. */
1891 remote_add_thread (currthread, running, executing);
1892 return;
1893 }
1894
1895 if (!in_thread_list (currthread))
1896 {
1897 struct inferior *inf = NULL;
1898 int pid = ptid_get_pid (currthread);
1899
1900 if (ptid_is_pid (inferior_ptid)
1901 && pid == ptid_get_pid (inferior_ptid))
1902 {
1903 /* inferior_ptid has no thread member yet. This can happen
1904 with the vAttach -> remote_wait,"TAAthread:" path if the
1905 stub doesn't support qC. This is the first stop reported
1906 after an attach, so this is the main thread. Update the
1907 ptid in the thread list. */
1908 if (in_thread_list (pid_to_ptid (pid)))
1909 thread_change_ptid (inferior_ptid, currthread);
1910 else
1911 {
1912 remote_add_thread (currthread, running, executing);
1913 inferior_ptid = currthread;
1914 }
1915 return;
1916 }
1917
1918 if (ptid_equal (magic_null_ptid, inferior_ptid))
1919 {
1920 /* inferior_ptid is not set yet. This can happen with the
1921 vRun -> remote_wait,"TAAthread:" path if the stub
1922 doesn't support qC. This is the first stop reported
1923 after an attach, so this is the main thread. Update the
1924 ptid in the thread list. */
1925 thread_change_ptid (inferior_ptid, currthread);
1926 return;
1927 }
1928
1929 /* When connecting to a target remote, or to a target
1930 extended-remote which already was debugging an inferior, we
1931 may not know about it yet. Add it before adding its child
1932 thread, so notifications are emitted in a sensible order. */
1933 if (!in_inferior_list (ptid_get_pid (currthread)))
1934 {
1935 struct remote_state *rs = get_remote_state ();
1936 int fake_pid_p = !remote_multi_process_p (rs);
1937
1938 inf = remote_add_inferior (fake_pid_p,
1939 ptid_get_pid (currthread), -1, 1);
1940 }
1941
1942 /* This is really a new thread. Add it. */
1943 remote_add_thread (currthread, running, executing);
1944
1945 /* If we found a new inferior, let the common code do whatever
1946 it needs to with it (e.g., read shared libraries, insert
1947 breakpoints), unless we're just setting up an all-stop
1948 connection. */
1949 if (inf != NULL)
1950 {
1951 struct remote_state *rs = get_remote_state ();
1952
1953 if (!rs->starting_up)
1954 notice_new_inferior (currthread, executing, 0);
1955 }
1956 }
1957 }
1958
1959 /* Return THREAD's private thread data, creating it if necessary. */
1960
1961 static struct private_thread_info *
1962 get_private_info_thread (struct thread_info *thread)
1963 {
1964 gdb_assert (thread != NULL);
1965
1966 if (thread->priv == NULL)
1967 {
1968 struct private_thread_info *priv = XNEW (struct private_thread_info);
1969
1970 thread->private_dtor = free_private_thread_info;
1971 thread->priv = priv;
1972
1973 priv->core = -1;
1974 priv->extra = NULL;
1975 priv->name = NULL;
1976 priv->name = NULL;
1977 priv->last_resume_step = 0;
1978 priv->last_resume_sig = GDB_SIGNAL_0;
1979 priv->vcont_resumed = 0;
1980 priv->thread_handle = nullptr;
1981 }
1982
1983 return thread->priv;
1984 }
1985
1986 /* Return PTID's private thread data, creating it if necessary. */
1987
1988 static struct private_thread_info *
1989 get_private_info_ptid (ptid_t ptid)
1990 {
1991 struct thread_info *info = find_thread_ptid (ptid);
1992
1993 return get_private_info_thread (info);
1994 }
1995
1996 /* Call this function as a result of
1997 1) A halt indication (T packet) containing a thread id
1998 2) A direct query of currthread
1999 3) Successful execution of set thread */
2000
2001 static void
2002 record_currthread (struct remote_state *rs, ptid_t currthread)
2003 {
2004 rs->general_thread = currthread;
2005 }
2006
2007 /* If 'QPassSignals' is supported, tell the remote stub what signals
2008 it can simply pass through to the inferior without reporting. */
2009
2010 static void
2011 remote_pass_signals (struct target_ops *self,
2012 int numsigs, unsigned char *pass_signals)
2013 {
2014 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2015 {
2016 char *pass_packet, *p;
2017 int count = 0, i;
2018 struct remote_state *rs = get_remote_state ();
2019
2020 gdb_assert (numsigs < 256);
2021 for (i = 0; i < numsigs; i++)
2022 {
2023 if (pass_signals[i])
2024 count++;
2025 }
2026 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2027 strcpy (pass_packet, "QPassSignals:");
2028 p = pass_packet + strlen (pass_packet);
2029 for (i = 0; i < numsigs; i++)
2030 {
2031 if (pass_signals[i])
2032 {
2033 if (i >= 16)
2034 *p++ = tohex (i >> 4);
2035 *p++ = tohex (i & 15);
2036 if (count)
2037 *p++ = ';';
2038 else
2039 break;
2040 count--;
2041 }
2042 }
2043 *p = 0;
2044 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2045 {
2046 putpkt (pass_packet);
2047 getpkt (&rs->buf, &rs->buf_size, 0);
2048 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2049 if (rs->last_pass_packet)
2050 xfree (rs->last_pass_packet);
2051 rs->last_pass_packet = pass_packet;
2052 }
2053 else
2054 xfree (pass_packet);
2055 }
2056 }
2057
2058 /* If 'QCatchSyscalls' is supported, tell the remote stub
2059 to report syscalls to GDB. */
2060
2061 static int
2062 remote_set_syscall_catchpoint (struct target_ops *self,
2063 int pid, int needed, int any_count,
2064 int table_size, int *table)
2065 {
2066 char *catch_packet;
2067 enum packet_result result;
2068 int n_sysno = 0;
2069
2070 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2071 {
2072 /* Not supported. */
2073 return 1;
2074 }
2075
2076 if (needed && !any_count)
2077 {
2078 int i;
2079
2080 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2081 for (i = 0; i < table_size; i++)
2082 {
2083 if (table[i] != 0)
2084 n_sysno++;
2085 }
2086 }
2087
2088 if (remote_debug)
2089 {
2090 fprintf_unfiltered (gdb_stdlog,
2091 "remote_set_syscall_catchpoint "
2092 "pid %d needed %d any_count %d n_sysno %d\n",
2093 pid, needed, any_count, n_sysno);
2094 }
2095
2096 if (needed)
2097 {
2098 /* Prepare a packet with the sysno list, assuming max 8+1
2099 characters for a sysno. If the resulting packet size is too
2100 big, fallback on the non-selective packet. */
2101 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2102
2103 catch_packet = (char *) xmalloc (maxpktsz);
2104 strcpy (catch_packet, "QCatchSyscalls:1");
2105 if (!any_count)
2106 {
2107 int i;
2108 char *p;
2109
2110 p = catch_packet;
2111 p += strlen (p);
2112
2113 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2114 for (i = 0; i < table_size; i++)
2115 {
2116 if (table[i] != 0)
2117 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2118 }
2119 }
2120 if (strlen (catch_packet) > get_remote_packet_size ())
2121 {
2122 /* catch_packet too big. Fallback to less efficient
2123 non selective mode, with GDB doing the filtering. */
2124 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2125 }
2126 }
2127 else
2128 catch_packet = xstrdup ("QCatchSyscalls:0");
2129
2130 {
2131 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2132 struct remote_state *rs = get_remote_state ();
2133
2134 putpkt (catch_packet);
2135 getpkt (&rs->buf, &rs->buf_size, 0);
2136 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2137 do_cleanups (old_chain);
2138 if (result == PACKET_OK)
2139 return 0;
2140 else
2141 return -1;
2142 }
2143 }
2144
2145 /* If 'QProgramSignals' is supported, tell the remote stub what
2146 signals it should pass through to the inferior when detaching. */
2147
2148 static void
2149 remote_program_signals (struct target_ops *self,
2150 int numsigs, unsigned char *signals)
2151 {
2152 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2153 {
2154 char *packet, *p;
2155 int count = 0, i;
2156 struct remote_state *rs = get_remote_state ();
2157
2158 gdb_assert (numsigs < 256);
2159 for (i = 0; i < numsigs; i++)
2160 {
2161 if (signals[i])
2162 count++;
2163 }
2164 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2165 strcpy (packet, "QProgramSignals:");
2166 p = packet + strlen (packet);
2167 for (i = 0; i < numsigs; i++)
2168 {
2169 if (signal_pass_state (i))
2170 {
2171 if (i >= 16)
2172 *p++ = tohex (i >> 4);
2173 *p++ = tohex (i & 15);
2174 if (count)
2175 *p++ = ';';
2176 else
2177 break;
2178 count--;
2179 }
2180 }
2181 *p = 0;
2182 if (!rs->last_program_signals_packet
2183 || strcmp (rs->last_program_signals_packet, packet) != 0)
2184 {
2185 putpkt (packet);
2186 getpkt (&rs->buf, &rs->buf_size, 0);
2187 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2188 xfree (rs->last_program_signals_packet);
2189 rs->last_program_signals_packet = packet;
2190 }
2191 else
2192 xfree (packet);
2193 }
2194 }
2195
2196 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2197 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2198 thread. If GEN is set, set the general thread, if not, then set
2199 the step/continue thread. */
2200 static void
2201 set_thread (ptid_t ptid, int gen)
2202 {
2203 struct remote_state *rs = get_remote_state ();
2204 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2205 char *buf = rs->buf;
2206 char *endbuf = rs->buf + get_remote_packet_size ();
2207
2208 if (ptid_equal (state, ptid))
2209 return;
2210
2211 *buf++ = 'H';
2212 *buf++ = gen ? 'g' : 'c';
2213 if (ptid_equal (ptid, magic_null_ptid))
2214 xsnprintf (buf, endbuf - buf, "0");
2215 else if (ptid_equal (ptid, any_thread_ptid))
2216 xsnprintf (buf, endbuf - buf, "0");
2217 else if (ptid_equal (ptid, minus_one_ptid))
2218 xsnprintf (buf, endbuf - buf, "-1");
2219 else
2220 write_ptid (buf, endbuf, ptid);
2221 putpkt (rs->buf);
2222 getpkt (&rs->buf, &rs->buf_size, 0);
2223 if (gen)
2224 rs->general_thread = ptid;
2225 else
2226 rs->continue_thread = ptid;
2227 }
2228
2229 static void
2230 set_general_thread (ptid_t ptid)
2231 {
2232 set_thread (ptid, 1);
2233 }
2234
2235 static void
2236 set_continue_thread (ptid_t ptid)
2237 {
2238 set_thread (ptid, 0);
2239 }
2240
2241 /* Change the remote current process. Which thread within the process
2242 ends up selected isn't important, as long as it is the same process
2243 as what INFERIOR_PTID points to.
2244
2245 This comes from that fact that there is no explicit notion of
2246 "selected process" in the protocol. The selected process for
2247 general operations is the process the selected general thread
2248 belongs to. */
2249
2250 static void
2251 set_general_process (void)
2252 {
2253 struct remote_state *rs = get_remote_state ();
2254
2255 /* If the remote can't handle multiple processes, don't bother. */
2256 if (!remote_multi_process_p (rs))
2257 return;
2258
2259 /* We only need to change the remote current thread if it's pointing
2260 at some other process. */
2261 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2262 set_general_thread (inferior_ptid);
2263 }
2264
2265 \f
2266 /* Return nonzero if this is the main thread that we made up ourselves
2267 to model non-threaded targets as single-threaded. */
2268
2269 static int
2270 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2271 {
2272 if (ptid_equal (ptid, magic_null_ptid))
2273 /* The main thread is always alive. */
2274 return 1;
2275
2276 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2277 /* The main thread is always alive. This can happen after a
2278 vAttach, if the remote side doesn't support
2279 multi-threading. */
2280 return 1;
2281
2282 return 0;
2283 }
2284
2285 /* Return nonzero if the thread PTID is still alive on the remote
2286 system. */
2287
2288 static int
2289 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2290 {
2291 struct remote_state *rs = get_remote_state ();
2292 char *p, *endp;
2293
2294 /* Check if this is a thread that we made up ourselves to model
2295 non-threaded targets as single-threaded. */
2296 if (remote_thread_always_alive (ops, ptid))
2297 return 1;
2298
2299 p = rs->buf;
2300 endp = rs->buf + get_remote_packet_size ();
2301
2302 *p++ = 'T';
2303 write_ptid (p, endp, ptid);
2304
2305 putpkt (rs->buf);
2306 getpkt (&rs->buf, &rs->buf_size, 0);
2307 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2308 }
2309
2310 /* Return a pointer to a thread name if we know it and NULL otherwise.
2311 The thread_info object owns the memory for the name. */
2312
2313 static const char *
2314 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2315 {
2316 if (info->priv != NULL)
2317 return info->priv->name;
2318
2319 return NULL;
2320 }
2321
2322 /* About these extended threadlist and threadinfo packets. They are
2323 variable length packets but, the fields within them are often fixed
2324 length. They are redundent enough to send over UDP as is the
2325 remote protocol in general. There is a matching unit test module
2326 in libstub. */
2327
2328 /* WARNING: This threadref data structure comes from the remote O.S.,
2329 libstub protocol encoding, and remote.c. It is not particularly
2330 changable. */
2331
2332 /* Right now, the internal structure is int. We want it to be bigger.
2333 Plan to fix this. */
2334
2335 typedef int gdb_threadref; /* Internal GDB thread reference. */
2336
2337 /* gdb_ext_thread_info is an internal GDB data structure which is
2338 equivalent to the reply of the remote threadinfo packet. */
2339
2340 struct gdb_ext_thread_info
2341 {
2342 threadref threadid; /* External form of thread reference. */
2343 int active; /* Has state interesting to GDB?
2344 regs, stack. */
2345 char display[256]; /* Brief state display, name,
2346 blocked/suspended. */
2347 char shortname[32]; /* To be used to name threads. */
2348 char more_display[256]; /* Long info, statistics, queue depth,
2349 whatever. */
2350 };
2351
2352 /* The volume of remote transfers can be limited by submitting
2353 a mask containing bits specifying the desired information.
2354 Use a union of these values as the 'selection' parameter to
2355 get_thread_info. FIXME: Make these TAG names more thread specific. */
2356
2357 #define TAG_THREADID 1
2358 #define TAG_EXISTS 2
2359 #define TAG_DISPLAY 4
2360 #define TAG_THREADNAME 8
2361 #define TAG_MOREDISPLAY 16
2362
2363 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2364
2365 static char *unpack_nibble (char *buf, int *val);
2366
2367 static char *unpack_byte (char *buf, int *value);
2368
2369 static char *pack_int (char *buf, int value);
2370
2371 static char *unpack_int (char *buf, int *value);
2372
2373 static char *unpack_string (char *src, char *dest, int length);
2374
2375 static char *pack_threadid (char *pkt, threadref *id);
2376
2377 static char *unpack_threadid (char *inbuf, threadref *id);
2378
2379 void int_to_threadref (threadref *id, int value);
2380
2381 static int threadref_to_int (threadref *ref);
2382
2383 static void copy_threadref (threadref *dest, threadref *src);
2384
2385 static int threadmatch (threadref *dest, threadref *src);
2386
2387 static char *pack_threadinfo_request (char *pkt, int mode,
2388 threadref *id);
2389
2390 static int remote_unpack_thread_info_response (char *pkt,
2391 threadref *expectedref,
2392 struct gdb_ext_thread_info
2393 *info);
2394
2395
2396 static int remote_get_threadinfo (threadref *threadid,
2397 int fieldset, /*TAG mask */
2398 struct gdb_ext_thread_info *info);
2399
2400 static char *pack_threadlist_request (char *pkt, int startflag,
2401 int threadcount,
2402 threadref *nextthread);
2403
2404 static int parse_threadlist_response (char *pkt,
2405 int result_limit,
2406 threadref *original_echo,
2407 threadref *resultlist,
2408 int *doneflag);
2409
2410 static int remote_get_threadlist (int startflag,
2411 threadref *nextthread,
2412 int result_limit,
2413 int *done,
2414 int *result_count,
2415 threadref *threadlist);
2416
2417 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2418
2419 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2420 void *context, int looplimit);
2421
2422 static int remote_newthread_step (threadref *ref, void *context);
2423
2424
2425 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2426 buffer we're allowed to write to. Returns
2427 BUF+CHARACTERS_WRITTEN. */
2428
2429 static char *
2430 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2431 {
2432 int pid, tid;
2433 struct remote_state *rs = get_remote_state ();
2434
2435 if (remote_multi_process_p (rs))
2436 {
2437 pid = ptid_get_pid (ptid);
2438 if (pid < 0)
2439 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2440 else
2441 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2442 }
2443 tid = ptid_get_lwp (ptid);
2444 if (tid < 0)
2445 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2446 else
2447 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2448
2449 return buf;
2450 }
2451
2452 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2453 passed the last parsed char. Returns null_ptid on error. */
2454
2455 static ptid_t
2456 read_ptid (char *buf, char **obuf)
2457 {
2458 char *p = buf;
2459 char *pp;
2460 ULONGEST pid = 0, tid = 0;
2461
2462 if (*p == 'p')
2463 {
2464 /* Multi-process ptid. */
2465 pp = unpack_varlen_hex (p + 1, &pid);
2466 if (*pp != '.')
2467 error (_("invalid remote ptid: %s"), p);
2468
2469 p = pp;
2470 pp = unpack_varlen_hex (p + 1, &tid);
2471 if (obuf)
2472 *obuf = pp;
2473 return ptid_build (pid, tid, 0);
2474 }
2475
2476 /* No multi-process. Just a tid. */
2477 pp = unpack_varlen_hex (p, &tid);
2478
2479 /* Return null_ptid when no thread id is found. */
2480 if (p == pp)
2481 {
2482 if (obuf)
2483 *obuf = pp;
2484 return null_ptid;
2485 }
2486
2487 /* Since the stub is not sending a process id, then default to
2488 what's in inferior_ptid, unless it's null at this point. If so,
2489 then since there's no way to know the pid of the reported
2490 threads, use the magic number. */
2491 if (ptid_equal (inferior_ptid, null_ptid))
2492 pid = ptid_get_pid (magic_null_ptid);
2493 else
2494 pid = ptid_get_pid (inferior_ptid);
2495
2496 if (obuf)
2497 *obuf = pp;
2498 return ptid_build (pid, tid, 0);
2499 }
2500
2501 static int
2502 stubhex (int ch)
2503 {
2504 if (ch >= 'a' && ch <= 'f')
2505 return ch - 'a' + 10;
2506 if (ch >= '0' && ch <= '9')
2507 return ch - '0';
2508 if (ch >= 'A' && ch <= 'F')
2509 return ch - 'A' + 10;
2510 return -1;
2511 }
2512
2513 static int
2514 stub_unpack_int (char *buff, int fieldlength)
2515 {
2516 int nibble;
2517 int retval = 0;
2518
2519 while (fieldlength)
2520 {
2521 nibble = stubhex (*buff++);
2522 retval |= nibble;
2523 fieldlength--;
2524 if (fieldlength)
2525 retval = retval << 4;
2526 }
2527 return retval;
2528 }
2529
2530 static char *
2531 unpack_nibble (char *buf, int *val)
2532 {
2533 *val = fromhex (*buf++);
2534 return buf;
2535 }
2536
2537 static char *
2538 unpack_byte (char *buf, int *value)
2539 {
2540 *value = stub_unpack_int (buf, 2);
2541 return buf + 2;
2542 }
2543
2544 static char *
2545 pack_int (char *buf, int value)
2546 {
2547 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2548 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2549 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2550 buf = pack_hex_byte (buf, (value & 0xff));
2551 return buf;
2552 }
2553
2554 static char *
2555 unpack_int (char *buf, int *value)
2556 {
2557 *value = stub_unpack_int (buf, 8);
2558 return buf + 8;
2559 }
2560
2561 #if 0 /* Currently unused, uncomment when needed. */
2562 static char *pack_string (char *pkt, char *string);
2563
2564 static char *
2565 pack_string (char *pkt, char *string)
2566 {
2567 char ch;
2568 int len;
2569
2570 len = strlen (string);
2571 if (len > 200)
2572 len = 200; /* Bigger than most GDB packets, junk??? */
2573 pkt = pack_hex_byte (pkt, len);
2574 while (len-- > 0)
2575 {
2576 ch = *string++;
2577 if ((ch == '\0') || (ch == '#'))
2578 ch = '*'; /* Protect encapsulation. */
2579 *pkt++ = ch;
2580 }
2581 return pkt;
2582 }
2583 #endif /* 0 (unused) */
2584
2585 static char *
2586 unpack_string (char *src, char *dest, int length)
2587 {
2588 while (length--)
2589 *dest++ = *src++;
2590 *dest = '\0';
2591 return src;
2592 }
2593
2594 static char *
2595 pack_threadid (char *pkt, threadref *id)
2596 {
2597 char *limit;
2598 unsigned char *altid;
2599
2600 altid = (unsigned char *) id;
2601 limit = pkt + BUF_THREAD_ID_SIZE;
2602 while (pkt < limit)
2603 pkt = pack_hex_byte (pkt, *altid++);
2604 return pkt;
2605 }
2606
2607
2608 static char *
2609 unpack_threadid (char *inbuf, threadref *id)
2610 {
2611 char *altref;
2612 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2613 int x, y;
2614
2615 altref = (char *) id;
2616
2617 while (inbuf < limit)
2618 {
2619 x = stubhex (*inbuf++);
2620 y = stubhex (*inbuf++);
2621 *altref++ = (x << 4) | y;
2622 }
2623 return inbuf;
2624 }
2625
2626 /* Externally, threadrefs are 64 bits but internally, they are still
2627 ints. This is due to a mismatch of specifications. We would like
2628 to use 64bit thread references internally. This is an adapter
2629 function. */
2630
2631 void
2632 int_to_threadref (threadref *id, int value)
2633 {
2634 unsigned char *scan;
2635
2636 scan = (unsigned char *) id;
2637 {
2638 int i = 4;
2639 while (i--)
2640 *scan++ = 0;
2641 }
2642 *scan++ = (value >> 24) & 0xff;
2643 *scan++ = (value >> 16) & 0xff;
2644 *scan++ = (value >> 8) & 0xff;
2645 *scan++ = (value & 0xff);
2646 }
2647
2648 static int
2649 threadref_to_int (threadref *ref)
2650 {
2651 int i, value = 0;
2652 unsigned char *scan;
2653
2654 scan = *ref;
2655 scan += 4;
2656 i = 4;
2657 while (i-- > 0)
2658 value = (value << 8) | ((*scan++) & 0xff);
2659 return value;
2660 }
2661
2662 static void
2663 copy_threadref (threadref *dest, threadref *src)
2664 {
2665 int i;
2666 unsigned char *csrc, *cdest;
2667
2668 csrc = (unsigned char *) src;
2669 cdest = (unsigned char *) dest;
2670 i = 8;
2671 while (i--)
2672 *cdest++ = *csrc++;
2673 }
2674
2675 static int
2676 threadmatch (threadref *dest, threadref *src)
2677 {
2678 /* Things are broken right now, so just assume we got a match. */
2679 #if 0
2680 unsigned char *srcp, *destp;
2681 int i, result;
2682 srcp = (char *) src;
2683 destp = (char *) dest;
2684
2685 result = 1;
2686 while (i-- > 0)
2687 result &= (*srcp++ == *destp++) ? 1 : 0;
2688 return result;
2689 #endif
2690 return 1;
2691 }
2692
2693 /*
2694 threadid:1, # always request threadid
2695 context_exists:2,
2696 display:4,
2697 unique_name:8,
2698 more_display:16
2699 */
2700
2701 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2702
2703 static char *
2704 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2705 {
2706 *pkt++ = 'q'; /* Info Query */
2707 *pkt++ = 'P'; /* process or thread info */
2708 pkt = pack_int (pkt, mode); /* mode */
2709 pkt = pack_threadid (pkt, id); /* threadid */
2710 *pkt = '\0'; /* terminate */
2711 return pkt;
2712 }
2713
2714 /* These values tag the fields in a thread info response packet. */
2715 /* Tagging the fields allows us to request specific fields and to
2716 add more fields as time goes by. */
2717
2718 #define TAG_THREADID 1 /* Echo the thread identifier. */
2719 #define TAG_EXISTS 2 /* Is this process defined enough to
2720 fetch registers and its stack? */
2721 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2722 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2723 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2724 the process. */
2725
2726 static int
2727 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2728 struct gdb_ext_thread_info *info)
2729 {
2730 struct remote_state *rs = get_remote_state ();
2731 int mask, length;
2732 int tag;
2733 threadref ref;
2734 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2735 int retval = 1;
2736
2737 /* info->threadid = 0; FIXME: implement zero_threadref. */
2738 info->active = 0;
2739 info->display[0] = '\0';
2740 info->shortname[0] = '\0';
2741 info->more_display[0] = '\0';
2742
2743 /* Assume the characters indicating the packet type have been
2744 stripped. */
2745 pkt = unpack_int (pkt, &mask); /* arg mask */
2746 pkt = unpack_threadid (pkt, &ref);
2747
2748 if (mask == 0)
2749 warning (_("Incomplete response to threadinfo request."));
2750 if (!threadmatch (&ref, expectedref))
2751 { /* This is an answer to a different request. */
2752 warning (_("ERROR RMT Thread info mismatch."));
2753 return 0;
2754 }
2755 copy_threadref (&info->threadid, &ref);
2756
2757 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2758
2759 /* Packets are terminated with nulls. */
2760 while ((pkt < limit) && mask && *pkt)
2761 {
2762 pkt = unpack_int (pkt, &tag); /* tag */
2763 pkt = unpack_byte (pkt, &length); /* length */
2764 if (!(tag & mask)) /* Tags out of synch with mask. */
2765 {
2766 warning (_("ERROR RMT: threadinfo tag mismatch."));
2767 retval = 0;
2768 break;
2769 }
2770 if (tag == TAG_THREADID)
2771 {
2772 if (length != 16)
2773 {
2774 warning (_("ERROR RMT: length of threadid is not 16."));
2775 retval = 0;
2776 break;
2777 }
2778 pkt = unpack_threadid (pkt, &ref);
2779 mask = mask & ~TAG_THREADID;
2780 continue;
2781 }
2782 if (tag == TAG_EXISTS)
2783 {
2784 info->active = stub_unpack_int (pkt, length);
2785 pkt += length;
2786 mask = mask & ~(TAG_EXISTS);
2787 if (length > 8)
2788 {
2789 warning (_("ERROR RMT: 'exists' length too long."));
2790 retval = 0;
2791 break;
2792 }
2793 continue;
2794 }
2795 if (tag == TAG_THREADNAME)
2796 {
2797 pkt = unpack_string (pkt, &info->shortname[0], length);
2798 mask = mask & ~TAG_THREADNAME;
2799 continue;
2800 }
2801 if (tag == TAG_DISPLAY)
2802 {
2803 pkt = unpack_string (pkt, &info->display[0], length);
2804 mask = mask & ~TAG_DISPLAY;
2805 continue;
2806 }
2807 if (tag == TAG_MOREDISPLAY)
2808 {
2809 pkt = unpack_string (pkt, &info->more_display[0], length);
2810 mask = mask & ~TAG_MOREDISPLAY;
2811 continue;
2812 }
2813 warning (_("ERROR RMT: unknown thread info tag."));
2814 break; /* Not a tag we know about. */
2815 }
2816 return retval;
2817 }
2818
2819 static int
2820 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2821 struct gdb_ext_thread_info *info)
2822 {
2823 struct remote_state *rs = get_remote_state ();
2824 int result;
2825
2826 pack_threadinfo_request (rs->buf, fieldset, threadid);
2827 putpkt (rs->buf);
2828 getpkt (&rs->buf, &rs->buf_size, 0);
2829
2830 if (rs->buf[0] == '\0')
2831 return 0;
2832
2833 result = remote_unpack_thread_info_response (rs->buf + 2,
2834 threadid, info);
2835 return result;
2836 }
2837
2838 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2839
2840 static char *
2841 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2842 threadref *nextthread)
2843 {
2844 *pkt++ = 'q'; /* info query packet */
2845 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2846 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2847 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2848 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2849 *pkt = '\0';
2850 return pkt;
2851 }
2852
2853 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2854
2855 static int
2856 parse_threadlist_response (char *pkt, int result_limit,
2857 threadref *original_echo, threadref *resultlist,
2858 int *doneflag)
2859 {
2860 struct remote_state *rs = get_remote_state ();
2861 char *limit;
2862 int count, resultcount, done;
2863
2864 resultcount = 0;
2865 /* Assume the 'q' and 'M chars have been stripped. */
2866 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2867 /* done parse past here */
2868 pkt = unpack_byte (pkt, &count); /* count field */
2869 pkt = unpack_nibble (pkt, &done);
2870 /* The first threadid is the argument threadid. */
2871 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2872 while ((count-- > 0) && (pkt < limit))
2873 {
2874 pkt = unpack_threadid (pkt, resultlist++);
2875 if (resultcount++ >= result_limit)
2876 break;
2877 }
2878 if (doneflag)
2879 *doneflag = done;
2880 return resultcount;
2881 }
2882
2883 /* Fetch the next batch of threads from the remote. Returns -1 if the
2884 qL packet is not supported, 0 on error and 1 on success. */
2885
2886 static int
2887 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2888 int *done, int *result_count, threadref *threadlist)
2889 {
2890 struct remote_state *rs = get_remote_state ();
2891 int result = 1;
2892
2893 /* Trancate result limit to be smaller than the packet size. */
2894 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2895 >= get_remote_packet_size ())
2896 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2897
2898 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2899 putpkt (rs->buf);
2900 getpkt (&rs->buf, &rs->buf_size, 0);
2901 if (*rs->buf == '\0')
2902 {
2903 /* Packet not supported. */
2904 return -1;
2905 }
2906
2907 *result_count =
2908 parse_threadlist_response (rs->buf + 2, result_limit,
2909 &rs->echo_nextthread, threadlist, done);
2910
2911 if (!threadmatch (&rs->echo_nextthread, nextthread))
2912 {
2913 /* FIXME: This is a good reason to drop the packet. */
2914 /* Possably, there is a duplicate response. */
2915 /* Possabilities :
2916 retransmit immediatly - race conditions
2917 retransmit after timeout - yes
2918 exit
2919 wait for packet, then exit
2920 */
2921 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2922 return 0; /* I choose simply exiting. */
2923 }
2924 if (*result_count <= 0)
2925 {
2926 if (*done != 1)
2927 {
2928 warning (_("RMT ERROR : failed to get remote thread list."));
2929 result = 0;
2930 }
2931 return result; /* break; */
2932 }
2933 if (*result_count > result_limit)
2934 {
2935 *result_count = 0;
2936 warning (_("RMT ERROR: threadlist response longer than requested."));
2937 return 0;
2938 }
2939 return result;
2940 }
2941
2942 /* Fetch the list of remote threads, with the qL packet, and call
2943 STEPFUNCTION for each thread found. Stops iterating and returns 1
2944 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2945 STEPFUNCTION returns false. If the packet is not supported,
2946 returns -1. */
2947
2948 static int
2949 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2950 int looplimit)
2951 {
2952 struct remote_state *rs = get_remote_state ();
2953 int done, i, result_count;
2954 int startflag = 1;
2955 int result = 1;
2956 int loopcount = 0;
2957
2958 done = 0;
2959 while (!done)
2960 {
2961 if (loopcount++ > looplimit)
2962 {
2963 result = 0;
2964 warning (_("Remote fetch threadlist -infinite loop-."));
2965 break;
2966 }
2967 result = remote_get_threadlist (startflag, &rs->nextthread,
2968 MAXTHREADLISTRESULTS,
2969 &done, &result_count,
2970 rs->resultthreadlist);
2971 if (result <= 0)
2972 break;
2973 /* Clear for later iterations. */
2974 startflag = 0;
2975 /* Setup to resume next batch of thread references, set nextthread. */
2976 if (result_count >= 1)
2977 copy_threadref (&rs->nextthread,
2978 &rs->resultthreadlist[result_count - 1]);
2979 i = 0;
2980 while (result_count--)
2981 {
2982 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2983 {
2984 result = 0;
2985 break;
2986 }
2987 }
2988 }
2989 return result;
2990 }
2991
2992 /* A thread found on the remote target. */
2993
2994 typedef struct thread_item
2995 {
2996 /* The thread's PTID. */
2997 ptid_t ptid;
2998
2999 /* The thread's extra info. May be NULL. */
3000 char *extra;
3001
3002 /* The thread's name. May be NULL. */
3003 char *name;
3004
3005 /* The core the thread was running on. -1 if not known. */
3006 int core;
3007
3008 /* The thread handle associated with the thread. */
3009 gdb::byte_vector *thread_handle;
3010
3011 } thread_item_t;
3012 DEF_VEC_O(thread_item_t);
3013
3014 /* Context passed around to the various methods listing remote
3015 threads. As new threads are found, they're added to the ITEMS
3016 vector. */
3017
3018 struct threads_listing_context
3019 {
3020 /* The threads found on the remote target. */
3021 VEC (thread_item_t) *items;
3022 };
3023
3024 /* Discard the contents of the constructed thread listing context. */
3025
3026 static void
3027 clear_threads_listing_context (void *p)
3028 {
3029 struct threads_listing_context *context
3030 = (struct threads_listing_context *) p;
3031 int i;
3032 struct thread_item *item;
3033
3034 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3035 {
3036 xfree (item->extra);
3037 xfree (item->name);
3038 delete item->thread_handle;
3039 }
3040
3041 VEC_free (thread_item_t, context->items);
3042 }
3043
3044 /* Remove the thread specified as the related_pid field of WS
3045 from the CONTEXT list. */
3046
3047 static void
3048 threads_listing_context_remove (struct target_waitstatus *ws,
3049 struct threads_listing_context *context)
3050 {
3051 struct thread_item *item;
3052 int i;
3053 ptid_t child_ptid = ws->value.related_pid;
3054
3055 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3056 {
3057 if (ptid_equal (item->ptid, child_ptid))
3058 {
3059 VEC_ordered_remove (thread_item_t, context->items, i);
3060 break;
3061 }
3062 }
3063 }
3064
3065 static int
3066 remote_newthread_step (threadref *ref, void *data)
3067 {
3068 struct threads_listing_context *context
3069 = (struct threads_listing_context *) data;
3070 struct thread_item item;
3071 int pid = ptid_get_pid (inferior_ptid);
3072
3073 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3074 item.core = -1;
3075 item.name = NULL;
3076 item.extra = NULL;
3077 item.thread_handle = nullptr;
3078
3079 VEC_safe_push (thread_item_t, context->items, &item);
3080
3081 return 1; /* continue iterator */
3082 }
3083
3084 #define CRAZY_MAX_THREADS 1000
3085
3086 static ptid_t
3087 remote_current_thread (ptid_t oldpid)
3088 {
3089 struct remote_state *rs = get_remote_state ();
3090
3091 putpkt ("qC");
3092 getpkt (&rs->buf, &rs->buf_size, 0);
3093 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3094 {
3095 char *obuf;
3096 ptid_t result;
3097
3098 result = read_ptid (&rs->buf[2], &obuf);
3099 if (*obuf != '\0' && remote_debug)
3100 fprintf_unfiltered (gdb_stdlog,
3101 "warning: garbage in qC reply\n");
3102
3103 return result;
3104 }
3105 else
3106 return oldpid;
3107 }
3108
3109 /* List remote threads using the deprecated qL packet. */
3110
3111 static int
3112 remote_get_threads_with_ql (struct target_ops *ops,
3113 struct threads_listing_context *context)
3114 {
3115 if (remote_threadlist_iterator (remote_newthread_step, context,
3116 CRAZY_MAX_THREADS) >= 0)
3117 return 1;
3118
3119 return 0;
3120 }
3121
3122 #if defined(HAVE_LIBEXPAT)
3123
3124 static void
3125 start_thread (struct gdb_xml_parser *parser,
3126 const struct gdb_xml_element *element,
3127 void *user_data, VEC(gdb_xml_value_s) *attributes)
3128 {
3129 struct threads_listing_context *data
3130 = (struct threads_listing_context *) user_data;
3131
3132 struct thread_item item;
3133 char *id;
3134 struct gdb_xml_value *attr;
3135
3136 id = (char *) xml_find_attribute (attributes, "id")->value;
3137 item.ptid = read_ptid (id, NULL);
3138
3139 attr = xml_find_attribute (attributes, "core");
3140 if (attr != NULL)
3141 item.core = *(ULONGEST *) attr->value;
3142 else
3143 item.core = -1;
3144
3145 attr = xml_find_attribute (attributes, "name");
3146 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3147
3148 attr = xml_find_attribute (attributes, "handle");
3149 if (attr != NULL)
3150 {
3151 item.thread_handle = new gdb::byte_vector
3152 (strlen ((const char *) attr->value) / 2);
3153 hex2bin ((const char *) attr->value, item.thread_handle->data (),
3154 item.thread_handle->size ());
3155 }
3156 else
3157 item.thread_handle = nullptr;
3158
3159 item.extra = 0;
3160
3161 VEC_safe_push (thread_item_t, data->items, &item);
3162 }
3163
3164 static void
3165 end_thread (struct gdb_xml_parser *parser,
3166 const struct gdb_xml_element *element,
3167 void *user_data, const char *body_text)
3168 {
3169 struct threads_listing_context *data
3170 = (struct threads_listing_context *) user_data;
3171
3172 if (body_text && *body_text)
3173 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3174 }
3175
3176 const struct gdb_xml_attribute thread_attributes[] = {
3177 { "id", GDB_XML_AF_NONE, NULL, NULL },
3178 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3179 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3180 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3181 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3182 };
3183
3184 const struct gdb_xml_element thread_children[] = {
3185 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3186 };
3187
3188 const struct gdb_xml_element threads_children[] = {
3189 { "thread", thread_attributes, thread_children,
3190 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3191 start_thread, end_thread },
3192 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3193 };
3194
3195 const struct gdb_xml_element threads_elements[] = {
3196 { "threads", NULL, threads_children,
3197 GDB_XML_EF_NONE, NULL, NULL },
3198 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3199 };
3200
3201 #endif
3202
3203 /* List remote threads using qXfer:threads:read. */
3204
3205 static int
3206 remote_get_threads_with_qxfer (struct target_ops *ops,
3207 struct threads_listing_context *context)
3208 {
3209 #if defined(HAVE_LIBEXPAT)
3210 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3211 {
3212 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3213 struct cleanup *back_to = make_cleanup (xfree, xml);
3214
3215 if (xml != NULL && *xml != '\0')
3216 {
3217 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3218 threads_elements, xml, context);
3219 }
3220
3221 do_cleanups (back_to);
3222 return 1;
3223 }
3224 #endif
3225
3226 return 0;
3227 }
3228
3229 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3230
3231 static int
3232 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3233 struct threads_listing_context *context)
3234 {
3235 struct remote_state *rs = get_remote_state ();
3236
3237 if (rs->use_threadinfo_query)
3238 {
3239 char *bufp;
3240
3241 putpkt ("qfThreadInfo");
3242 getpkt (&rs->buf, &rs->buf_size, 0);
3243 bufp = rs->buf;
3244 if (bufp[0] != '\0') /* q packet recognized */
3245 {
3246 while (*bufp++ == 'm') /* reply contains one or more TID */
3247 {
3248 do
3249 {
3250 struct thread_item item;
3251
3252 item.ptid = read_ptid (bufp, &bufp);
3253 item.core = -1;
3254 item.name = NULL;
3255 item.extra = NULL;
3256 item.thread_handle = nullptr;
3257
3258 VEC_safe_push (thread_item_t, context->items, &item);
3259 }
3260 while (*bufp++ == ','); /* comma-separated list */
3261 putpkt ("qsThreadInfo");
3262 getpkt (&rs->buf, &rs->buf_size, 0);
3263 bufp = rs->buf;
3264 }
3265 return 1;
3266 }
3267 else
3268 {
3269 /* Packet not recognized. */
3270 rs->use_threadinfo_query = 0;
3271 }
3272 }
3273
3274 return 0;
3275 }
3276
3277 /* Implement the to_update_thread_list function for the remote
3278 targets. */
3279
3280 static void
3281 remote_update_thread_list (struct target_ops *ops)
3282 {
3283 struct threads_listing_context context;
3284 struct cleanup *old_chain;
3285 int got_list = 0;
3286
3287 context.items = NULL;
3288 old_chain = make_cleanup (clear_threads_listing_context, &context);
3289
3290 /* We have a few different mechanisms to fetch the thread list. Try
3291 them all, starting with the most preferred one first, falling
3292 back to older methods. */
3293 if (remote_get_threads_with_qxfer (ops, &context)
3294 || remote_get_threads_with_qthreadinfo (ops, &context)
3295 || remote_get_threads_with_ql (ops, &context))
3296 {
3297 int i;
3298 struct thread_item *item;
3299 struct thread_info *tp, *tmp;
3300
3301 got_list = 1;
3302
3303 if (VEC_empty (thread_item_t, context.items)
3304 && remote_thread_always_alive (ops, inferior_ptid))
3305 {
3306 /* Some targets don't really support threads, but still
3307 reply an (empty) thread list in response to the thread
3308 listing packets, instead of replying "packet not
3309 supported". Exit early so we don't delete the main
3310 thread. */
3311 do_cleanups (old_chain);
3312 return;
3313 }
3314
3315 /* CONTEXT now holds the current thread list on the remote
3316 target end. Delete GDB-side threads no longer found on the
3317 target. */
3318 ALL_THREADS_SAFE (tp, tmp)
3319 {
3320 for (i = 0;
3321 VEC_iterate (thread_item_t, context.items, i, item);
3322 ++i)
3323 {
3324 if (ptid_equal (item->ptid, tp->ptid))
3325 break;
3326 }
3327
3328 if (i == VEC_length (thread_item_t, context.items))
3329 {
3330 /* Not found. */
3331 delete_thread (tp->ptid);
3332 }
3333 }
3334
3335 /* Remove any unreported fork child threads from CONTEXT so
3336 that we don't interfere with follow fork, which is where
3337 creation of such threads is handled. */
3338 remove_new_fork_children (&context);
3339
3340 /* And now add threads we don't know about yet to our list. */
3341 for (i = 0;
3342 VEC_iterate (thread_item_t, context.items, i, item);
3343 ++i)
3344 {
3345 if (!ptid_equal (item->ptid, null_ptid))
3346 {
3347 struct private_thread_info *info;
3348 /* In non-stop mode, we assume new found threads are
3349 executing until proven otherwise with a stop reply.
3350 In all-stop, we can only get here if all threads are
3351 stopped. */
3352 int executing = target_is_non_stop_p () ? 1 : 0;
3353
3354 remote_notice_new_inferior (item->ptid, executing);
3355
3356 info = get_private_info_ptid (item->ptid);
3357 info->core = item->core;
3358 info->extra = item->extra;
3359 item->extra = NULL;
3360 info->name = item->name;
3361 item->name = NULL;
3362 info->thread_handle = item->thread_handle;
3363 item->thread_handle = nullptr;
3364 }
3365 }
3366 }
3367
3368 if (!got_list)
3369 {
3370 /* If no thread listing method is supported, then query whether
3371 each known thread is alive, one by one, with the T packet.
3372 If the target doesn't support threads at all, then this is a
3373 no-op. See remote_thread_alive. */
3374 prune_threads ();
3375 }
3376
3377 do_cleanups (old_chain);
3378 }
3379
3380 /*
3381 * Collect a descriptive string about the given thread.
3382 * The target may say anything it wants to about the thread
3383 * (typically info about its blocked / runnable state, name, etc.).
3384 * This string will appear in the info threads display.
3385 *
3386 * Optional: targets are not required to implement this function.
3387 */
3388
3389 static const char *
3390 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3391 {
3392 struct remote_state *rs = get_remote_state ();
3393 int result;
3394 int set;
3395 threadref id;
3396 struct gdb_ext_thread_info threadinfo;
3397 static char display_buf[100]; /* arbitrary... */
3398 int n = 0; /* position in display_buf */
3399
3400 if (rs->remote_desc == 0) /* paranoia */
3401 internal_error (__FILE__, __LINE__,
3402 _("remote_threads_extra_info"));
3403
3404 if (ptid_equal (tp->ptid, magic_null_ptid)
3405 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3406 /* This is the main thread which was added by GDB. The remote
3407 server doesn't know about it. */
3408 return NULL;
3409
3410 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3411 {
3412 struct thread_info *info = find_thread_ptid (tp->ptid);
3413
3414 if (info && info->priv)
3415 return info->priv->extra;
3416 else
3417 return NULL;
3418 }
3419
3420 if (rs->use_threadextra_query)
3421 {
3422 char *b = rs->buf;
3423 char *endb = rs->buf + get_remote_packet_size ();
3424
3425 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3426 b += strlen (b);
3427 write_ptid (b, endb, tp->ptid);
3428
3429 putpkt (rs->buf);
3430 getpkt (&rs->buf, &rs->buf_size, 0);
3431 if (rs->buf[0] != 0)
3432 {
3433 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3434 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3435 display_buf [result] = '\0';
3436 return display_buf;
3437 }
3438 }
3439
3440 /* If the above query fails, fall back to the old method. */
3441 rs->use_threadextra_query = 0;
3442 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3443 | TAG_MOREDISPLAY | TAG_DISPLAY;
3444 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3445 if (remote_get_threadinfo (&id, set, &threadinfo))
3446 if (threadinfo.active)
3447 {
3448 if (*threadinfo.shortname)
3449 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3450 " Name: %s,", threadinfo.shortname);
3451 if (*threadinfo.display)
3452 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3453 " State: %s,", threadinfo.display);
3454 if (*threadinfo.more_display)
3455 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3456 " Priority: %s", threadinfo.more_display);
3457
3458 if (n > 0)
3459 {
3460 /* For purely cosmetic reasons, clear up trailing commas. */
3461 if (',' == display_buf[n-1])
3462 display_buf[n-1] = ' ';
3463 return display_buf;
3464 }
3465 }
3466 return NULL;
3467 }
3468 \f
3469
3470 static int
3471 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3472 struct static_tracepoint_marker *marker)
3473 {
3474 struct remote_state *rs = get_remote_state ();
3475 char *p = rs->buf;
3476
3477 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3478 p += strlen (p);
3479 p += hexnumstr (p, addr);
3480 putpkt (rs->buf);
3481 getpkt (&rs->buf, &rs->buf_size, 0);
3482 p = rs->buf;
3483
3484 if (*p == 'E')
3485 error (_("Remote failure reply: %s"), p);
3486
3487 if (*p++ == 'm')
3488 {
3489 parse_static_tracepoint_marker_definition (p, &p, marker);
3490 return 1;
3491 }
3492
3493 return 0;
3494 }
3495
3496 static VEC(static_tracepoint_marker_p) *
3497 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3498 const char *strid)
3499 {
3500 struct remote_state *rs = get_remote_state ();
3501 VEC(static_tracepoint_marker_p) *markers = NULL;
3502 struct static_tracepoint_marker *marker = NULL;
3503 struct cleanup *old_chain;
3504 char *p;
3505
3506 /* Ask for a first packet of static tracepoint marker
3507 definition. */
3508 putpkt ("qTfSTM");
3509 getpkt (&rs->buf, &rs->buf_size, 0);
3510 p = rs->buf;
3511 if (*p == 'E')
3512 error (_("Remote failure reply: %s"), p);
3513
3514 old_chain = make_cleanup (free_current_marker, &marker);
3515
3516 while (*p++ == 'm')
3517 {
3518 if (marker == NULL)
3519 marker = XCNEW (struct static_tracepoint_marker);
3520
3521 do
3522 {
3523 parse_static_tracepoint_marker_definition (p, &p, marker);
3524
3525 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3526 {
3527 VEC_safe_push (static_tracepoint_marker_p,
3528 markers, marker);
3529 marker = NULL;
3530 }
3531 else
3532 {
3533 release_static_tracepoint_marker (marker);
3534 memset (marker, 0, sizeof (*marker));
3535 }
3536 }
3537 while (*p++ == ','); /* comma-separated list */
3538 /* Ask for another packet of static tracepoint definition. */
3539 putpkt ("qTsSTM");
3540 getpkt (&rs->buf, &rs->buf_size, 0);
3541 p = rs->buf;
3542 }
3543
3544 do_cleanups (old_chain);
3545 return markers;
3546 }
3547
3548 \f
3549 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3550
3551 static ptid_t
3552 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3553 {
3554 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3555 }
3556 \f
3557
3558 /* Restart the remote side; this is an extended protocol operation. */
3559
3560 static void
3561 extended_remote_restart (void)
3562 {
3563 struct remote_state *rs = get_remote_state ();
3564
3565 /* Send the restart command; for reasons I don't understand the
3566 remote side really expects a number after the "R". */
3567 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3568 putpkt (rs->buf);
3569
3570 remote_fileio_reset ();
3571 }
3572 \f
3573 /* Clean up connection to a remote debugger. */
3574
3575 static void
3576 remote_close (struct target_ops *self)
3577 {
3578 struct remote_state *rs = get_remote_state ();
3579
3580 if (rs->remote_desc == NULL)
3581 return; /* already closed */
3582
3583 /* Make sure we leave stdin registered in the event loop. */
3584 remote_terminal_ours (self);
3585
3586 serial_close (rs->remote_desc);
3587 rs->remote_desc = NULL;
3588
3589 /* We don't have a connection to the remote stub anymore. Get rid
3590 of all the inferiors and their threads we were controlling.
3591 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3592 will be unable to find the thread corresponding to (pid, 0, 0). */
3593 inferior_ptid = null_ptid;
3594 discard_all_inferiors ();
3595
3596 /* We are closing the remote target, so we should discard
3597 everything of this target. */
3598 discard_pending_stop_replies_in_queue (rs);
3599
3600 if (remote_async_inferior_event_token)
3601 delete_async_event_handler (&remote_async_inferior_event_token);
3602
3603 remote_notif_state_xfree (rs->notif_state);
3604
3605 trace_reset_local_state ();
3606 }
3607
3608 /* Query the remote side for the text, data and bss offsets. */
3609
3610 static void
3611 get_offsets (void)
3612 {
3613 struct remote_state *rs = get_remote_state ();
3614 char *buf;
3615 char *ptr;
3616 int lose, num_segments = 0, do_sections, do_segments;
3617 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3618 struct section_offsets *offs;
3619 struct symfile_segment_data *data;
3620
3621 if (symfile_objfile == NULL)
3622 return;
3623
3624 putpkt ("qOffsets");
3625 getpkt (&rs->buf, &rs->buf_size, 0);
3626 buf = rs->buf;
3627
3628 if (buf[0] == '\000')
3629 return; /* Return silently. Stub doesn't support
3630 this command. */
3631 if (buf[0] == 'E')
3632 {
3633 warning (_("Remote failure reply: %s"), buf);
3634 return;
3635 }
3636
3637 /* Pick up each field in turn. This used to be done with scanf, but
3638 scanf will make trouble if CORE_ADDR size doesn't match
3639 conversion directives correctly. The following code will work
3640 with any size of CORE_ADDR. */
3641 text_addr = data_addr = bss_addr = 0;
3642 ptr = buf;
3643 lose = 0;
3644
3645 if (startswith (ptr, "Text="))
3646 {
3647 ptr += 5;
3648 /* Don't use strtol, could lose on big values. */
3649 while (*ptr && *ptr != ';')
3650 text_addr = (text_addr << 4) + fromhex (*ptr++);
3651
3652 if (startswith (ptr, ";Data="))
3653 {
3654 ptr += 6;
3655 while (*ptr && *ptr != ';')
3656 data_addr = (data_addr << 4) + fromhex (*ptr++);
3657 }
3658 else
3659 lose = 1;
3660
3661 if (!lose && startswith (ptr, ";Bss="))
3662 {
3663 ptr += 5;
3664 while (*ptr && *ptr != ';')
3665 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3666
3667 if (bss_addr != data_addr)
3668 warning (_("Target reported unsupported offsets: %s"), buf);
3669 }
3670 else
3671 lose = 1;
3672 }
3673 else if (startswith (ptr, "TextSeg="))
3674 {
3675 ptr += 8;
3676 /* Don't use strtol, could lose on big values. */
3677 while (*ptr && *ptr != ';')
3678 text_addr = (text_addr << 4) + fromhex (*ptr++);
3679 num_segments = 1;
3680
3681 if (startswith (ptr, ";DataSeg="))
3682 {
3683 ptr += 9;
3684 while (*ptr && *ptr != ';')
3685 data_addr = (data_addr << 4) + fromhex (*ptr++);
3686 num_segments++;
3687 }
3688 }
3689 else
3690 lose = 1;
3691
3692 if (lose)
3693 error (_("Malformed response to offset query, %s"), buf);
3694 else if (*ptr != '\0')
3695 warning (_("Target reported unsupported offsets: %s"), buf);
3696
3697 offs = ((struct section_offsets *)
3698 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3699 memcpy (offs, symfile_objfile->section_offsets,
3700 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3701
3702 data = get_symfile_segment_data (symfile_objfile->obfd);
3703 do_segments = (data != NULL);
3704 do_sections = num_segments == 0;
3705
3706 if (num_segments > 0)
3707 {
3708 segments[0] = text_addr;
3709 segments[1] = data_addr;
3710 }
3711 /* If we have two segments, we can still try to relocate everything
3712 by assuming that the .text and .data offsets apply to the whole
3713 text and data segments. Convert the offsets given in the packet
3714 to base addresses for symfile_map_offsets_to_segments. */
3715 else if (data && data->num_segments == 2)
3716 {
3717 segments[0] = data->segment_bases[0] + text_addr;
3718 segments[1] = data->segment_bases[1] + data_addr;
3719 num_segments = 2;
3720 }
3721 /* If the object file has only one segment, assume that it is text
3722 rather than data; main programs with no writable data are rare,
3723 but programs with no code are useless. Of course the code might
3724 have ended up in the data segment... to detect that we would need
3725 the permissions here. */
3726 else if (data && data->num_segments == 1)
3727 {
3728 segments[0] = data->segment_bases[0] + text_addr;
3729 num_segments = 1;
3730 }
3731 /* There's no way to relocate by segment. */
3732 else
3733 do_segments = 0;
3734
3735 if (do_segments)
3736 {
3737 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3738 offs, num_segments, segments);
3739
3740 if (ret == 0 && !do_sections)
3741 error (_("Can not handle qOffsets TextSeg "
3742 "response with this symbol file"));
3743
3744 if (ret > 0)
3745 do_sections = 0;
3746 }
3747
3748 if (data)
3749 free_symfile_segment_data (data);
3750
3751 if (do_sections)
3752 {
3753 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3754
3755 /* This is a temporary kludge to force data and bss to use the
3756 same offsets because that's what nlmconv does now. The real
3757 solution requires changes to the stub and remote.c that I
3758 don't have time to do right now. */
3759
3760 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3761 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3762 }
3763
3764 objfile_relocate (symfile_objfile, offs);
3765 }
3766
3767 /* Send interrupt_sequence to remote target. */
3768 static void
3769 send_interrupt_sequence (void)
3770 {
3771 struct remote_state *rs = get_remote_state ();
3772
3773 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3774 remote_serial_write ("\x03", 1);
3775 else if (interrupt_sequence_mode == interrupt_sequence_break)
3776 serial_send_break (rs->remote_desc);
3777 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3778 {
3779 serial_send_break (rs->remote_desc);
3780 remote_serial_write ("g", 1);
3781 }
3782 else
3783 internal_error (__FILE__, __LINE__,
3784 _("Invalid value for interrupt_sequence_mode: %s."),
3785 interrupt_sequence_mode);
3786 }
3787
3788
3789 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3790 and extract the PTID. Returns NULL_PTID if not found. */
3791
3792 static ptid_t
3793 stop_reply_extract_thread (char *stop_reply)
3794 {
3795 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3796 {
3797 char *p;
3798
3799 /* Txx r:val ; r:val (...) */
3800 p = &stop_reply[3];
3801
3802 /* Look for "register" named "thread". */
3803 while (*p != '\0')
3804 {
3805 char *p1;
3806
3807 p1 = strchr (p, ':');
3808 if (p1 == NULL)
3809 return null_ptid;
3810
3811 if (strncmp (p, "thread", p1 - p) == 0)
3812 return read_ptid (++p1, &p);
3813
3814 p1 = strchr (p, ';');
3815 if (p1 == NULL)
3816 return null_ptid;
3817 p1++;
3818
3819 p = p1;
3820 }
3821 }
3822
3823 return null_ptid;
3824 }
3825
3826 /* Determine the remote side's current thread. If we have a stop
3827 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3828 "thread" register we can extract the current thread from. If not,
3829 ask the remote which is the current thread with qC. The former
3830 method avoids a roundtrip. */
3831
3832 static ptid_t
3833 get_current_thread (char *wait_status)
3834 {
3835 ptid_t ptid = null_ptid;
3836
3837 /* Note we don't use remote_parse_stop_reply as that makes use of
3838 the target architecture, which we haven't yet fully determined at
3839 this point. */
3840 if (wait_status != NULL)
3841 ptid = stop_reply_extract_thread (wait_status);
3842 if (ptid_equal (ptid, null_ptid))
3843 ptid = remote_current_thread (inferior_ptid);
3844
3845 return ptid;
3846 }
3847
3848 /* Query the remote target for which is the current thread/process,
3849 add it to our tables, and update INFERIOR_PTID. The caller is
3850 responsible for setting the state such that the remote end is ready
3851 to return the current thread.
3852
3853 This function is called after handling the '?' or 'vRun' packets,
3854 whose response is a stop reply from which we can also try
3855 extracting the thread. If the target doesn't support the explicit
3856 qC query, we infer the current thread from that stop reply, passed
3857 in in WAIT_STATUS, which may be NULL. */
3858
3859 static void
3860 add_current_inferior_and_thread (char *wait_status)
3861 {
3862 struct remote_state *rs = get_remote_state ();
3863 int fake_pid_p = 0;
3864
3865 inferior_ptid = null_ptid;
3866
3867 /* Now, if we have thread information, update inferior_ptid. */
3868 ptid_t curr_ptid = get_current_thread (wait_status);
3869
3870 if (curr_ptid != null_ptid)
3871 {
3872 if (!remote_multi_process_p (rs))
3873 fake_pid_p = 1;
3874 }
3875 else
3876 {
3877 /* Without this, some commands which require an active target
3878 (such as kill) won't work. This variable serves (at least)
3879 double duty as both the pid of the target process (if it has
3880 such), and as a flag indicating that a target is active. */
3881 curr_ptid = magic_null_ptid;
3882 fake_pid_p = 1;
3883 }
3884
3885 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
3886
3887 /* Add the main thread and switch to it. Don't try reading
3888 registers yet, since we haven't fetched the target description
3889 yet. */
3890 thread_info *tp = add_thread_silent (curr_ptid);
3891 switch_to_thread_no_regs (tp);
3892 }
3893
3894 /* Print info about a thread that was found already stopped on
3895 connection. */
3896
3897 static void
3898 print_one_stopped_thread (struct thread_info *thread)
3899 {
3900 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3901
3902 switch_to_thread (thread->ptid);
3903 stop_pc = get_frame_pc (get_current_frame ());
3904 set_current_sal_from_frame (get_current_frame ());
3905
3906 thread->suspend.waitstatus_pending_p = 0;
3907
3908 if (ws->kind == TARGET_WAITKIND_STOPPED)
3909 {
3910 enum gdb_signal sig = ws->value.sig;
3911
3912 if (signal_print_state (sig))
3913 observer_notify_signal_received (sig);
3914 }
3915 observer_notify_normal_stop (NULL, 1);
3916 }
3917
3918 /* Process all initial stop replies the remote side sent in response
3919 to the ? packet. These indicate threads that were already stopped
3920 on initial connection. We mark these threads as stopped and print
3921 their current frame before giving the user the prompt. */
3922
3923 static void
3924 process_initial_stop_replies (int from_tty)
3925 {
3926 int pending_stop_replies = stop_reply_queue_length ();
3927 struct inferior *inf;
3928 struct thread_info *thread;
3929 struct thread_info *selected = NULL;
3930 struct thread_info *lowest_stopped = NULL;
3931 struct thread_info *first = NULL;
3932
3933 /* Consume the initial pending events. */
3934 while (pending_stop_replies-- > 0)
3935 {
3936 ptid_t waiton_ptid = minus_one_ptid;
3937 ptid_t event_ptid;
3938 struct target_waitstatus ws;
3939 int ignore_event = 0;
3940 struct thread_info *thread;
3941
3942 memset (&ws, 0, sizeof (ws));
3943 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3944 if (remote_debug)
3945 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3946
3947 switch (ws.kind)
3948 {
3949 case TARGET_WAITKIND_IGNORE:
3950 case TARGET_WAITKIND_NO_RESUMED:
3951 case TARGET_WAITKIND_SIGNALLED:
3952 case TARGET_WAITKIND_EXITED:
3953 /* We shouldn't see these, but if we do, just ignore. */
3954 if (remote_debug)
3955 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3956 ignore_event = 1;
3957 break;
3958
3959 case TARGET_WAITKIND_EXECD:
3960 xfree (ws.value.execd_pathname);
3961 break;
3962 default:
3963 break;
3964 }
3965
3966 if (ignore_event)
3967 continue;
3968
3969 thread = find_thread_ptid (event_ptid);
3970
3971 if (ws.kind == TARGET_WAITKIND_STOPPED)
3972 {
3973 enum gdb_signal sig = ws.value.sig;
3974
3975 /* Stubs traditionally report SIGTRAP as initial signal,
3976 instead of signal 0. Suppress it. */
3977 if (sig == GDB_SIGNAL_TRAP)
3978 sig = GDB_SIGNAL_0;
3979 thread->suspend.stop_signal = sig;
3980 ws.value.sig = sig;
3981 }
3982
3983 thread->suspend.waitstatus = ws;
3984
3985 if (ws.kind != TARGET_WAITKIND_STOPPED
3986 || ws.value.sig != GDB_SIGNAL_0)
3987 thread->suspend.waitstatus_pending_p = 1;
3988
3989 set_executing (event_ptid, 0);
3990 set_running (event_ptid, 0);
3991 thread->priv->vcont_resumed = 0;
3992 }
3993
3994 /* "Notice" the new inferiors before anything related to
3995 registers/memory. */
3996 ALL_INFERIORS (inf)
3997 {
3998 if (inf->pid == 0)
3999 continue;
4000
4001 inf->needs_setup = 1;
4002
4003 if (non_stop)
4004 {
4005 thread = any_live_thread_of_process (inf->pid);
4006 notice_new_inferior (thread->ptid,
4007 thread->state == THREAD_RUNNING,
4008 from_tty);
4009 }
4010 }
4011
4012 /* If all-stop on top of non-stop, pause all threads. Note this
4013 records the threads' stop pc, so must be done after "noticing"
4014 the inferiors. */
4015 if (!non_stop)
4016 {
4017 stop_all_threads ();
4018
4019 /* If all threads of an inferior were already stopped, we
4020 haven't setup the inferior yet. */
4021 ALL_INFERIORS (inf)
4022 {
4023 if (inf->pid == 0)
4024 continue;
4025
4026 if (inf->needs_setup)
4027 {
4028 thread = any_live_thread_of_process (inf->pid);
4029 switch_to_thread_no_regs (thread);
4030 setup_inferior (0);
4031 }
4032 }
4033 }
4034
4035 /* Now go over all threads that are stopped, and print their current
4036 frame. If all-stop, then if there's a signalled thread, pick
4037 that as current. */
4038 ALL_NON_EXITED_THREADS (thread)
4039 {
4040 if (first == NULL)
4041 first = thread;
4042
4043 if (!non_stop)
4044 set_running (thread->ptid, 0);
4045 else if (thread->state != THREAD_STOPPED)
4046 continue;
4047
4048 if (selected == NULL
4049 && thread->suspend.waitstatus_pending_p)
4050 selected = thread;
4051
4052 if (lowest_stopped == NULL
4053 || thread->inf->num < lowest_stopped->inf->num
4054 || thread->per_inf_num < lowest_stopped->per_inf_num)
4055 lowest_stopped = thread;
4056
4057 if (non_stop)
4058 print_one_stopped_thread (thread);
4059 }
4060
4061 /* In all-stop, we only print the status of one thread, and leave
4062 others with their status pending. */
4063 if (!non_stop)
4064 {
4065 thread = selected;
4066 if (thread == NULL)
4067 thread = lowest_stopped;
4068 if (thread == NULL)
4069 thread = first;
4070
4071 print_one_stopped_thread (thread);
4072 }
4073
4074 /* For "info program". */
4075 thread = inferior_thread ();
4076 if (thread->state == THREAD_STOPPED)
4077 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4078 }
4079
4080 /* Start the remote connection and sync state. */
4081
4082 static void
4083 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4084 {
4085 struct remote_state *rs = get_remote_state ();
4086 struct packet_config *noack_config;
4087 char *wait_status = NULL;
4088
4089 /* Signal other parts that we're going through the initial setup,
4090 and so things may not be stable yet. E.g., we don't try to
4091 install tracepoints until we've relocated symbols. Also, a
4092 Ctrl-C before we're connected and synced up can't interrupt the
4093 target. Instead, it offers to drop the (potentially wedged)
4094 connection. */
4095 rs->starting_up = 1;
4096
4097 QUIT;
4098
4099 if (interrupt_on_connect)
4100 send_interrupt_sequence ();
4101
4102 /* Ack any packet which the remote side has already sent. */
4103 remote_serial_write ("+", 1);
4104
4105 /* The first packet we send to the target is the optional "supported
4106 packets" request. If the target can answer this, it will tell us
4107 which later probes to skip. */
4108 remote_query_supported ();
4109
4110 /* If the stub wants to get a QAllow, compose one and send it. */
4111 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4112 remote_set_permissions (target);
4113
4114 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4115 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4116 as a reply to known packet. For packet "vFile:setfs:" it is an
4117 invalid reply and GDB would return error in
4118 remote_hostio_set_filesystem, making remote files access impossible.
4119 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4120 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4121 {
4122 const char v_mustreplyempty[] = "vMustReplyEmpty";
4123
4124 putpkt (v_mustreplyempty);
4125 getpkt (&rs->buf, &rs->buf_size, 0);
4126 if (strcmp (rs->buf, "OK") == 0)
4127 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4128 else if (strcmp (rs->buf, "") != 0)
4129 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4130 rs->buf);
4131 }
4132
4133 /* Next, we possibly activate noack mode.
4134
4135 If the QStartNoAckMode packet configuration is set to AUTO,
4136 enable noack mode if the stub reported a wish for it with
4137 qSupported.
4138
4139 If set to TRUE, then enable noack mode even if the stub didn't
4140 report it in qSupported. If the stub doesn't reply OK, the
4141 session ends with an error.
4142
4143 If FALSE, then don't activate noack mode, regardless of what the
4144 stub claimed should be the default with qSupported. */
4145
4146 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4147 if (packet_config_support (noack_config) != PACKET_DISABLE)
4148 {
4149 putpkt ("QStartNoAckMode");
4150 getpkt (&rs->buf, &rs->buf_size, 0);
4151 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4152 rs->noack_mode = 1;
4153 }
4154
4155 if (extended_p)
4156 {
4157 /* Tell the remote that we are using the extended protocol. */
4158 putpkt ("!");
4159 getpkt (&rs->buf, &rs->buf_size, 0);
4160 }
4161
4162 /* Let the target know which signals it is allowed to pass down to
4163 the program. */
4164 update_signals_program_target ();
4165
4166 /* Next, if the target can specify a description, read it. We do
4167 this before anything involving memory or registers. */
4168 target_find_description ();
4169
4170 /* Next, now that we know something about the target, update the
4171 address spaces in the program spaces. */
4172 update_address_spaces ();
4173
4174 /* On OSs where the list of libraries is global to all
4175 processes, we fetch them early. */
4176 if (gdbarch_has_global_solist (target_gdbarch ()))
4177 solib_add (NULL, from_tty, auto_solib_add);
4178
4179 if (target_is_non_stop_p ())
4180 {
4181 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4182 error (_("Non-stop mode requested, but remote "
4183 "does not support non-stop"));
4184
4185 putpkt ("QNonStop:1");
4186 getpkt (&rs->buf, &rs->buf_size, 0);
4187
4188 if (strcmp (rs->buf, "OK") != 0)
4189 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4190
4191 /* Find about threads and processes the stub is already
4192 controlling. We default to adding them in the running state.
4193 The '?' query below will then tell us about which threads are
4194 stopped. */
4195 remote_update_thread_list (target);
4196 }
4197 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4198 {
4199 /* Don't assume that the stub can operate in all-stop mode.
4200 Request it explicitly. */
4201 putpkt ("QNonStop:0");
4202 getpkt (&rs->buf, &rs->buf_size, 0);
4203
4204 if (strcmp (rs->buf, "OK") != 0)
4205 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4206 }
4207
4208 /* Upload TSVs regardless of whether the target is running or not. The
4209 remote stub, such as GDBserver, may have some predefined or builtin
4210 TSVs, even if the target is not running. */
4211 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4212 {
4213 struct uploaded_tsv *uploaded_tsvs = NULL;
4214
4215 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4216 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4217 }
4218
4219 /* Check whether the target is running now. */
4220 putpkt ("?");
4221 getpkt (&rs->buf, &rs->buf_size, 0);
4222
4223 if (!target_is_non_stop_p ())
4224 {
4225 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4226 {
4227 if (!extended_p)
4228 error (_("The target is not running (try extended-remote?)"));
4229
4230 /* We're connected, but not running. Drop out before we
4231 call start_remote. */
4232 rs->starting_up = 0;
4233 return;
4234 }
4235 else
4236 {
4237 /* Save the reply for later. */
4238 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4239 strcpy (wait_status, rs->buf);
4240 }
4241
4242 /* Fetch thread list. */
4243 target_update_thread_list ();
4244
4245 /* Let the stub know that we want it to return the thread. */
4246 set_continue_thread (minus_one_ptid);
4247
4248 if (thread_count () == 0)
4249 {
4250 /* Target has no concept of threads at all. GDB treats
4251 non-threaded target as single-threaded; add a main
4252 thread. */
4253 add_current_inferior_and_thread (wait_status);
4254 }
4255 else
4256 {
4257 /* We have thread information; select the thread the target
4258 says should be current. If we're reconnecting to a
4259 multi-threaded program, this will ideally be the thread
4260 that last reported an event before GDB disconnected. */
4261 inferior_ptid = get_current_thread (wait_status);
4262 if (ptid_equal (inferior_ptid, null_ptid))
4263 {
4264 /* Odd... The target was able to list threads, but not
4265 tell us which thread was current (no "thread"
4266 register in T stop reply?). Just pick the first
4267 thread in the thread list then. */
4268
4269 if (remote_debug)
4270 fprintf_unfiltered (gdb_stdlog,
4271 "warning: couldn't determine remote "
4272 "current thread; picking first in list.\n");
4273
4274 inferior_ptid = thread_list->ptid;
4275 }
4276 }
4277
4278 /* init_wait_for_inferior should be called before get_offsets in order
4279 to manage `inserted' flag in bp loc in a correct state.
4280 breakpoint_init_inferior, called from init_wait_for_inferior, set
4281 `inserted' flag to 0, while before breakpoint_re_set, called from
4282 start_remote, set `inserted' flag to 1. In the initialization of
4283 inferior, breakpoint_init_inferior should be called first, and then
4284 breakpoint_re_set can be called. If this order is broken, state of
4285 `inserted' flag is wrong, and cause some problems on breakpoint
4286 manipulation. */
4287 init_wait_for_inferior ();
4288
4289 get_offsets (); /* Get text, data & bss offsets. */
4290
4291 /* If we could not find a description using qXfer, and we know
4292 how to do it some other way, try again. This is not
4293 supported for non-stop; it could be, but it is tricky if
4294 there are no stopped threads when we connect. */
4295 if (remote_read_description_p (target)
4296 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4297 {
4298 target_clear_description ();
4299 target_find_description ();
4300 }
4301
4302 /* Use the previously fetched status. */
4303 gdb_assert (wait_status != NULL);
4304 strcpy (rs->buf, wait_status);
4305 rs->cached_wait_status = 1;
4306
4307 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4308 }
4309 else
4310 {
4311 /* Clear WFI global state. Do this before finding about new
4312 threads and inferiors, and setting the current inferior.
4313 Otherwise we would clear the proceed status of the current
4314 inferior when we want its stop_soon state to be preserved
4315 (see notice_new_inferior). */
4316 init_wait_for_inferior ();
4317
4318 /* In non-stop, we will either get an "OK", meaning that there
4319 are no stopped threads at this time; or, a regular stop
4320 reply. In the latter case, there may be more than one thread
4321 stopped --- we pull them all out using the vStopped
4322 mechanism. */
4323 if (strcmp (rs->buf, "OK") != 0)
4324 {
4325 struct notif_client *notif = &notif_client_stop;
4326
4327 /* remote_notif_get_pending_replies acks this one, and gets
4328 the rest out. */
4329 rs->notif_state->pending_event[notif_client_stop.id]
4330 = remote_notif_parse (notif, rs->buf);
4331 remote_notif_get_pending_events (notif);
4332 }
4333
4334 if (thread_count () == 0)
4335 {
4336 if (!extended_p)
4337 error (_("The target is not running (try extended-remote?)"));
4338
4339 /* We're connected, but not running. Drop out before we
4340 call start_remote. */
4341 rs->starting_up = 0;
4342 return;
4343 }
4344
4345 /* In non-stop mode, any cached wait status will be stored in
4346 the stop reply queue. */
4347 gdb_assert (wait_status == NULL);
4348
4349 /* Report all signals during attach/startup. */
4350 remote_pass_signals (target, 0, NULL);
4351
4352 /* If there are already stopped threads, mark them stopped and
4353 report their stops before giving the prompt to the user. */
4354 process_initial_stop_replies (from_tty);
4355
4356 if (target_can_async_p ())
4357 target_async (1);
4358 }
4359
4360 /* If we connected to a live target, do some additional setup. */
4361 if (target_has_execution)
4362 {
4363 if (symfile_objfile) /* No use without a symbol-file. */
4364 remote_check_symbols ();
4365 }
4366
4367 /* Possibly the target has been engaged in a trace run started
4368 previously; find out where things are at. */
4369 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4370 {
4371 struct uploaded_tp *uploaded_tps = NULL;
4372
4373 if (current_trace_status ()->running)
4374 printf_filtered (_("Trace is already running on the target.\n"));
4375
4376 remote_upload_tracepoints (target, &uploaded_tps);
4377
4378 merge_uploaded_tracepoints (&uploaded_tps);
4379 }
4380
4381 /* Possibly the target has been engaged in a btrace record started
4382 previously; find out where things are at. */
4383 remote_btrace_maybe_reopen ();
4384
4385 /* The thread and inferior lists are now synchronized with the
4386 target, our symbols have been relocated, and we're merged the
4387 target's tracepoints with ours. We're done with basic start
4388 up. */
4389 rs->starting_up = 0;
4390
4391 /* Maybe breakpoints are global and need to be inserted now. */
4392 if (breakpoints_should_be_inserted_now ())
4393 insert_breakpoints ();
4394 }
4395
4396 /* Open a connection to a remote debugger.
4397 NAME is the filename used for communication. */
4398
4399 static void
4400 remote_open (const char *name, int from_tty)
4401 {
4402 remote_open_1 (name, from_tty, &remote_ops, 0);
4403 }
4404
4405 /* Open a connection to a remote debugger using the extended
4406 remote gdb protocol. NAME is the filename used for communication. */
4407
4408 static void
4409 extended_remote_open (const char *name, int from_tty)
4410 {
4411 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4412 }
4413
4414 /* Reset all packets back to "unknown support". Called when opening a
4415 new connection to a remote target. */
4416
4417 static void
4418 reset_all_packet_configs_support (void)
4419 {
4420 int i;
4421
4422 for (i = 0; i < PACKET_MAX; i++)
4423 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4424 }
4425
4426 /* Initialize all packet configs. */
4427
4428 static void
4429 init_all_packet_configs (void)
4430 {
4431 int i;
4432
4433 for (i = 0; i < PACKET_MAX; i++)
4434 {
4435 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4436 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4437 }
4438 }
4439
4440 /* Symbol look-up. */
4441
4442 static void
4443 remote_check_symbols (void)
4444 {
4445 struct remote_state *rs = get_remote_state ();
4446 char *msg, *reply, *tmp;
4447 int end;
4448 long reply_size;
4449 struct cleanup *old_chain;
4450
4451 /* The remote side has no concept of inferiors that aren't running
4452 yet, it only knows about running processes. If we're connected
4453 but our current inferior is not running, we should not invite the
4454 remote target to request symbol lookups related to its
4455 (unrelated) current process. */
4456 if (!target_has_execution)
4457 return;
4458
4459 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4460 return;
4461
4462 /* Make sure the remote is pointing at the right process. Note
4463 there's no way to select "no process". */
4464 set_general_process ();
4465
4466 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4467 because we need both at the same time. */
4468 msg = (char *) xmalloc (get_remote_packet_size ());
4469 old_chain = make_cleanup (xfree, msg);
4470 reply = (char *) xmalloc (get_remote_packet_size ());
4471 make_cleanup (free_current_contents, &reply);
4472 reply_size = get_remote_packet_size ();
4473
4474 /* Invite target to request symbol lookups. */
4475
4476 putpkt ("qSymbol::");
4477 getpkt (&reply, &reply_size, 0);
4478 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4479
4480 while (startswith (reply, "qSymbol:"))
4481 {
4482 struct bound_minimal_symbol sym;
4483
4484 tmp = &reply[8];
4485 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4486 msg[end] = '\0';
4487 sym = lookup_minimal_symbol (msg, NULL, NULL);
4488 if (sym.minsym == NULL)
4489 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4490 else
4491 {
4492 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4493 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4494
4495 /* If this is a function address, return the start of code
4496 instead of any data function descriptor. */
4497 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4498 sym_addr,
4499 &current_target);
4500
4501 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4502 phex_nz (sym_addr, addr_size), &reply[8]);
4503 }
4504
4505 putpkt (msg);
4506 getpkt (&reply, &reply_size, 0);
4507 }
4508
4509 do_cleanups (old_chain);
4510 }
4511
4512 static struct serial *
4513 remote_serial_open (const char *name)
4514 {
4515 static int udp_warning = 0;
4516
4517 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4518 of in ser-tcp.c, because it is the remote protocol assuming that the
4519 serial connection is reliable and not the serial connection promising
4520 to be. */
4521 if (!udp_warning && startswith (name, "udp:"))
4522 {
4523 warning (_("The remote protocol may be unreliable over UDP.\n"
4524 "Some events may be lost, rendering further debugging "
4525 "impossible."));
4526 udp_warning = 1;
4527 }
4528
4529 return serial_open (name);
4530 }
4531
4532 /* Inform the target of our permission settings. The permission flags
4533 work without this, but if the target knows the settings, it can do
4534 a couple things. First, it can add its own check, to catch cases
4535 that somehow manage to get by the permissions checks in target
4536 methods. Second, if the target is wired to disallow particular
4537 settings (for instance, a system in the field that is not set up to
4538 be able to stop at a breakpoint), it can object to any unavailable
4539 permissions. */
4540
4541 void
4542 remote_set_permissions (struct target_ops *self)
4543 {
4544 struct remote_state *rs = get_remote_state ();
4545
4546 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4547 "WriteReg:%x;WriteMem:%x;"
4548 "InsertBreak:%x;InsertTrace:%x;"
4549 "InsertFastTrace:%x;Stop:%x",
4550 may_write_registers, may_write_memory,
4551 may_insert_breakpoints, may_insert_tracepoints,
4552 may_insert_fast_tracepoints, may_stop);
4553 putpkt (rs->buf);
4554 getpkt (&rs->buf, &rs->buf_size, 0);
4555
4556 /* If the target didn't like the packet, warn the user. Do not try
4557 to undo the user's settings, that would just be maddening. */
4558 if (strcmp (rs->buf, "OK") != 0)
4559 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4560 }
4561
4562 /* This type describes each known response to the qSupported
4563 packet. */
4564 struct protocol_feature
4565 {
4566 /* The name of this protocol feature. */
4567 const char *name;
4568
4569 /* The default for this protocol feature. */
4570 enum packet_support default_support;
4571
4572 /* The function to call when this feature is reported, or after
4573 qSupported processing if the feature is not supported.
4574 The first argument points to this structure. The second
4575 argument indicates whether the packet requested support be
4576 enabled, disabled, or probed (or the default, if this function
4577 is being called at the end of processing and this feature was
4578 not reported). The third argument may be NULL; if not NULL, it
4579 is a NUL-terminated string taken from the packet following
4580 this feature's name and an equals sign. */
4581 void (*func) (const struct protocol_feature *, enum packet_support,
4582 const char *);
4583
4584 /* The corresponding packet for this feature. Only used if
4585 FUNC is remote_supported_packet. */
4586 int packet;
4587 };
4588
4589 static void
4590 remote_supported_packet (const struct protocol_feature *feature,
4591 enum packet_support support,
4592 const char *argument)
4593 {
4594 if (argument)
4595 {
4596 warning (_("Remote qSupported response supplied an unexpected value for"
4597 " \"%s\"."), feature->name);
4598 return;
4599 }
4600
4601 remote_protocol_packets[feature->packet].support = support;
4602 }
4603
4604 static void
4605 remote_packet_size (const struct protocol_feature *feature,
4606 enum packet_support support, const char *value)
4607 {
4608 struct remote_state *rs = get_remote_state ();
4609
4610 int packet_size;
4611 char *value_end;
4612
4613 if (support != PACKET_ENABLE)
4614 return;
4615
4616 if (value == NULL || *value == '\0')
4617 {
4618 warning (_("Remote target reported \"%s\" without a size."),
4619 feature->name);
4620 return;
4621 }
4622
4623 errno = 0;
4624 packet_size = strtol (value, &value_end, 16);
4625 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4626 {
4627 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4628 feature->name, value);
4629 return;
4630 }
4631
4632 /* Record the new maximum packet size. */
4633 rs->explicit_packet_size = packet_size;
4634 }
4635
4636 static const struct protocol_feature remote_protocol_features[] = {
4637 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4638 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4639 PACKET_qXfer_auxv },
4640 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4641 PACKET_qXfer_exec_file },
4642 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4643 PACKET_qXfer_features },
4644 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4645 PACKET_qXfer_libraries },
4646 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4647 PACKET_qXfer_libraries_svr4 },
4648 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4649 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4650 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4651 PACKET_qXfer_memory_map },
4652 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4653 PACKET_qXfer_spu_read },
4654 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4655 PACKET_qXfer_spu_write },
4656 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4657 PACKET_qXfer_osdata },
4658 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4659 PACKET_qXfer_threads },
4660 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4661 PACKET_qXfer_traceframe_info },
4662 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4663 PACKET_QPassSignals },
4664 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4665 PACKET_QCatchSyscalls },
4666 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4667 PACKET_QProgramSignals },
4668 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4669 PACKET_QStartupWithShell },
4670 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4671 PACKET_QEnvironmentHexEncoded },
4672 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4673 PACKET_QEnvironmentReset },
4674 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4675 PACKET_QEnvironmentUnset },
4676 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4677 PACKET_QStartNoAckMode },
4678 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4679 PACKET_multiprocess_feature },
4680 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4681 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4682 PACKET_qXfer_siginfo_read },
4683 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4684 PACKET_qXfer_siginfo_write },
4685 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4686 PACKET_ConditionalTracepoints },
4687 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4688 PACKET_ConditionalBreakpoints },
4689 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4690 PACKET_BreakpointCommands },
4691 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4692 PACKET_FastTracepoints },
4693 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4694 PACKET_StaticTracepoints },
4695 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4696 PACKET_InstallInTrace},
4697 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4698 PACKET_DisconnectedTracing_feature },
4699 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4700 PACKET_bc },
4701 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4702 PACKET_bs },
4703 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4704 PACKET_TracepointSource },
4705 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4706 PACKET_QAllow },
4707 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4708 PACKET_EnableDisableTracepoints_feature },
4709 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4710 PACKET_qXfer_fdpic },
4711 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4712 PACKET_qXfer_uib },
4713 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4714 PACKET_QDisableRandomization },
4715 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4716 { "QTBuffer:size", PACKET_DISABLE,
4717 remote_supported_packet, PACKET_QTBuffer_size},
4718 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4719 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4720 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4721 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4722 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4723 PACKET_qXfer_btrace },
4724 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4725 PACKET_qXfer_btrace_conf },
4726 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4727 PACKET_Qbtrace_conf_bts_size },
4728 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4729 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4730 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4731 PACKET_fork_event_feature },
4732 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4733 PACKET_vfork_event_feature },
4734 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4735 PACKET_exec_event_feature },
4736 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4737 PACKET_Qbtrace_conf_pt_size },
4738 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4739 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4740 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4741 };
4742
4743 static char *remote_support_xml;
4744
4745 /* Register string appended to "xmlRegisters=" in qSupported query. */
4746
4747 void
4748 register_remote_support_xml (const char *xml)
4749 {
4750 #if defined(HAVE_LIBEXPAT)
4751 if (remote_support_xml == NULL)
4752 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4753 else
4754 {
4755 char *copy = xstrdup (remote_support_xml + 13);
4756 char *p = strtok (copy, ",");
4757
4758 do
4759 {
4760 if (strcmp (p, xml) == 0)
4761 {
4762 /* already there */
4763 xfree (copy);
4764 return;
4765 }
4766 }
4767 while ((p = strtok (NULL, ",")) != NULL);
4768 xfree (copy);
4769
4770 remote_support_xml = reconcat (remote_support_xml,
4771 remote_support_xml, ",", xml,
4772 (char *) NULL);
4773 }
4774 #endif
4775 }
4776
4777 static char *
4778 remote_query_supported_append (char *msg, const char *append)
4779 {
4780 if (msg)
4781 return reconcat (msg, msg, ";", append, (char *) NULL);
4782 else
4783 return xstrdup (append);
4784 }
4785
4786 static void
4787 remote_query_supported (void)
4788 {
4789 struct remote_state *rs = get_remote_state ();
4790 char *next;
4791 int i;
4792 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4793
4794 /* The packet support flags are handled differently for this packet
4795 than for most others. We treat an error, a disabled packet, and
4796 an empty response identically: any features which must be reported
4797 to be used will be automatically disabled. An empty buffer
4798 accomplishes this, since that is also the representation for a list
4799 containing no features. */
4800
4801 rs->buf[0] = 0;
4802 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4803 {
4804 char *q = NULL;
4805 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4806
4807 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4808 q = remote_query_supported_append (q, "multiprocess+");
4809
4810 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4811 q = remote_query_supported_append (q, "swbreak+");
4812 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4813 q = remote_query_supported_append (q, "hwbreak+");
4814
4815 q = remote_query_supported_append (q, "qRelocInsn+");
4816
4817 if (packet_set_cmd_state (PACKET_fork_event_feature)
4818 != AUTO_BOOLEAN_FALSE)
4819 q = remote_query_supported_append (q, "fork-events+");
4820 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4821 != AUTO_BOOLEAN_FALSE)
4822 q = remote_query_supported_append (q, "vfork-events+");
4823 if (packet_set_cmd_state (PACKET_exec_event_feature)
4824 != AUTO_BOOLEAN_FALSE)
4825 q = remote_query_supported_append (q, "exec-events+");
4826
4827 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4828 q = remote_query_supported_append (q, "vContSupported+");
4829
4830 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4831 q = remote_query_supported_append (q, "QThreadEvents+");
4832
4833 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4834 q = remote_query_supported_append (q, "no-resumed+");
4835
4836 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4837 the qSupported:xmlRegisters=i386 handling. */
4838 if (remote_support_xml != NULL)
4839 q = remote_query_supported_append (q, remote_support_xml);
4840
4841 q = reconcat (q, "qSupported:", q, (char *) NULL);
4842 putpkt (q);
4843
4844 do_cleanups (old_chain);
4845
4846 getpkt (&rs->buf, &rs->buf_size, 0);
4847
4848 /* If an error occured, warn, but do not return - just reset the
4849 buffer to empty and go on to disable features. */
4850 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4851 == PACKET_ERROR)
4852 {
4853 warning (_("Remote failure reply: %s"), rs->buf);
4854 rs->buf[0] = 0;
4855 }
4856 }
4857
4858 memset (seen, 0, sizeof (seen));
4859
4860 next = rs->buf;
4861 while (*next)
4862 {
4863 enum packet_support is_supported;
4864 char *p, *end, *name_end, *value;
4865
4866 /* First separate out this item from the rest of the packet. If
4867 there's another item after this, we overwrite the separator
4868 (terminated strings are much easier to work with). */
4869 p = next;
4870 end = strchr (p, ';');
4871 if (end == NULL)
4872 {
4873 end = p + strlen (p);
4874 next = end;
4875 }
4876 else
4877 {
4878 *end = '\0';
4879 next = end + 1;
4880
4881 if (end == p)
4882 {
4883 warning (_("empty item in \"qSupported\" response"));
4884 continue;
4885 }
4886 }
4887
4888 name_end = strchr (p, '=');
4889 if (name_end)
4890 {
4891 /* This is a name=value entry. */
4892 is_supported = PACKET_ENABLE;
4893 value = name_end + 1;
4894 *name_end = '\0';
4895 }
4896 else
4897 {
4898 value = NULL;
4899 switch (end[-1])
4900 {
4901 case '+':
4902 is_supported = PACKET_ENABLE;
4903 break;
4904
4905 case '-':
4906 is_supported = PACKET_DISABLE;
4907 break;
4908
4909 case '?':
4910 is_supported = PACKET_SUPPORT_UNKNOWN;
4911 break;
4912
4913 default:
4914 warning (_("unrecognized item \"%s\" "
4915 "in \"qSupported\" response"), p);
4916 continue;
4917 }
4918 end[-1] = '\0';
4919 }
4920
4921 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4922 if (strcmp (remote_protocol_features[i].name, p) == 0)
4923 {
4924 const struct protocol_feature *feature;
4925
4926 seen[i] = 1;
4927 feature = &remote_protocol_features[i];
4928 feature->func (feature, is_supported, value);
4929 break;
4930 }
4931 }
4932
4933 /* If we increased the packet size, make sure to increase the global
4934 buffer size also. We delay this until after parsing the entire
4935 qSupported packet, because this is the same buffer we were
4936 parsing. */
4937 if (rs->buf_size < rs->explicit_packet_size)
4938 {
4939 rs->buf_size = rs->explicit_packet_size;
4940 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4941 }
4942
4943 /* Handle the defaults for unmentioned features. */
4944 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4945 if (!seen[i])
4946 {
4947 const struct protocol_feature *feature;
4948
4949 feature = &remote_protocol_features[i];
4950 feature->func (feature, feature->default_support, NULL);
4951 }
4952 }
4953
4954 /* Serial QUIT handler for the remote serial descriptor.
4955
4956 Defers handling a Ctrl-C until we're done with the current
4957 command/response packet sequence, unless:
4958
4959 - We're setting up the connection. Don't send a remote interrupt
4960 request, as we're not fully synced yet. Quit immediately
4961 instead.
4962
4963 - The target has been resumed in the foreground
4964 (target_terminal::is_ours is false) with a synchronous resume
4965 packet, and we're blocked waiting for the stop reply, thus a
4966 Ctrl-C should be immediately sent to the target.
4967
4968 - We get a second Ctrl-C while still within the same serial read or
4969 write. In that case the serial is seemingly wedged --- offer to
4970 quit/disconnect.
4971
4972 - We see a second Ctrl-C without target response, after having
4973 previously interrupted the target. In that case the target/stub
4974 is probably wedged --- offer to quit/disconnect.
4975 */
4976
4977 static void
4978 remote_serial_quit_handler (void)
4979 {
4980 struct remote_state *rs = get_remote_state ();
4981
4982 if (check_quit_flag ())
4983 {
4984 /* If we're starting up, we're not fully synced yet. Quit
4985 immediately. */
4986 if (rs->starting_up)
4987 quit ();
4988 else if (rs->got_ctrlc_during_io)
4989 {
4990 if (query (_("The target is not responding to GDB commands.\n"
4991 "Stop debugging it? ")))
4992 remote_unpush_and_throw ();
4993 }
4994 /* If ^C has already been sent once, offer to disconnect. */
4995 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
4996 interrupt_query ();
4997 /* All-stop protocol, and blocked waiting for stop reply. Send
4998 an interrupt request. */
4999 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5000 target_interrupt (inferior_ptid);
5001 else
5002 rs->got_ctrlc_during_io = 1;
5003 }
5004 }
5005
5006 /* Remove any of the remote.c targets from target stack. Upper targets depend
5007 on it so remove them first. */
5008
5009 static void
5010 remote_unpush_target (void)
5011 {
5012 pop_all_targets_at_and_above (process_stratum);
5013 }
5014
5015 static void
5016 remote_unpush_and_throw (void)
5017 {
5018 remote_unpush_target ();
5019 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5020 }
5021
5022 static void
5023 remote_open_1 (const char *name, int from_tty,
5024 struct target_ops *target, int extended_p)
5025 {
5026 struct remote_state *rs = get_remote_state ();
5027
5028 if (name == 0)
5029 error (_("To open a remote debug connection, you need to specify what\n"
5030 "serial device is attached to the remote system\n"
5031 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5032
5033 /* See FIXME above. */
5034 if (!target_async_permitted)
5035 wait_forever_enabled_p = 1;
5036
5037 /* If we're connected to a running target, target_preopen will kill it.
5038 Ask this question first, before target_preopen has a chance to kill
5039 anything. */
5040 if (rs->remote_desc != NULL && !have_inferiors ())
5041 {
5042 if (from_tty
5043 && !query (_("Already connected to a remote target. Disconnect? ")))
5044 error (_("Still connected."));
5045 }
5046
5047 /* Here the possibly existing remote target gets unpushed. */
5048 target_preopen (from_tty);
5049
5050 /* Make sure we send the passed signals list the next time we resume. */
5051 xfree (rs->last_pass_packet);
5052 rs->last_pass_packet = NULL;
5053
5054 /* Make sure we send the program signals list the next time we
5055 resume. */
5056 xfree (rs->last_program_signals_packet);
5057 rs->last_program_signals_packet = NULL;
5058
5059 remote_fileio_reset ();
5060 reopen_exec_file ();
5061 reread_symbols ();
5062
5063 rs->remote_desc = remote_serial_open (name);
5064 if (!rs->remote_desc)
5065 perror_with_name (name);
5066
5067 if (baud_rate != -1)
5068 {
5069 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5070 {
5071 /* The requested speed could not be set. Error out to
5072 top level after closing remote_desc. Take care to
5073 set remote_desc to NULL to avoid closing remote_desc
5074 more than once. */
5075 serial_close (rs->remote_desc);
5076 rs->remote_desc = NULL;
5077 perror_with_name (name);
5078 }
5079 }
5080
5081 serial_setparity (rs->remote_desc, serial_parity);
5082 serial_raw (rs->remote_desc);
5083
5084 /* If there is something sitting in the buffer we might take it as a
5085 response to a command, which would be bad. */
5086 serial_flush_input (rs->remote_desc);
5087
5088 if (from_tty)
5089 {
5090 puts_filtered ("Remote debugging using ");
5091 puts_filtered (name);
5092 puts_filtered ("\n");
5093 }
5094 push_target (target); /* Switch to using remote target now. */
5095
5096 /* Register extra event sources in the event loop. */
5097 remote_async_inferior_event_token
5098 = create_async_event_handler (remote_async_inferior_event_handler,
5099 NULL);
5100 rs->notif_state = remote_notif_state_allocate ();
5101
5102 /* Reset the target state; these things will be queried either by
5103 remote_query_supported or as they are needed. */
5104 reset_all_packet_configs_support ();
5105 rs->cached_wait_status = 0;
5106 rs->explicit_packet_size = 0;
5107 rs->noack_mode = 0;
5108 rs->extended = extended_p;
5109 rs->waiting_for_stop_reply = 0;
5110 rs->ctrlc_pending_p = 0;
5111 rs->got_ctrlc_during_io = 0;
5112
5113 rs->general_thread = not_sent_ptid;
5114 rs->continue_thread = not_sent_ptid;
5115 rs->remote_traceframe_number = -1;
5116
5117 rs->last_resume_exec_dir = EXEC_FORWARD;
5118
5119 /* Probe for ability to use "ThreadInfo" query, as required. */
5120 rs->use_threadinfo_query = 1;
5121 rs->use_threadextra_query = 1;
5122
5123 readahead_cache_invalidate ();
5124
5125 /* Start out by owning the terminal. */
5126 remote_async_terminal_ours_p = 1;
5127
5128 if (target_async_permitted)
5129 {
5130 /* FIXME: cagney/1999-09-23: During the initial connection it is
5131 assumed that the target is already ready and able to respond to
5132 requests. Unfortunately remote_start_remote() eventually calls
5133 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5134 around this. Eventually a mechanism that allows
5135 wait_for_inferior() to expect/get timeouts will be
5136 implemented. */
5137 wait_forever_enabled_p = 0;
5138 }
5139
5140 /* First delete any symbols previously loaded from shared libraries. */
5141 no_shared_libraries (NULL, 0);
5142
5143 /* Start afresh. */
5144 init_thread_list ();
5145
5146 /* Start the remote connection. If error() or QUIT, discard this
5147 target (we'd otherwise be in an inconsistent state) and then
5148 propogate the error on up the exception chain. This ensures that
5149 the caller doesn't stumble along blindly assuming that the
5150 function succeeded. The CLI doesn't have this problem but other
5151 UI's, such as MI do.
5152
5153 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5154 this function should return an error indication letting the
5155 caller restore the previous state. Unfortunately the command
5156 ``target remote'' is directly wired to this function making that
5157 impossible. On a positive note, the CLI side of this problem has
5158 been fixed - the function set_cmd_context() makes it possible for
5159 all the ``target ....'' commands to share a common callback
5160 function. See cli-dump.c. */
5161 {
5162
5163 TRY
5164 {
5165 remote_start_remote (from_tty, target, extended_p);
5166 }
5167 CATCH (ex, RETURN_MASK_ALL)
5168 {
5169 /* Pop the partially set up target - unless something else did
5170 already before throwing the exception. */
5171 if (rs->remote_desc != NULL)
5172 remote_unpush_target ();
5173 if (target_async_permitted)
5174 wait_forever_enabled_p = 1;
5175 throw_exception (ex);
5176 }
5177 END_CATCH
5178 }
5179
5180 remote_btrace_reset ();
5181
5182 if (target_async_permitted)
5183 wait_forever_enabled_p = 1;
5184 }
5185
5186 /* Detach the specified process. */
5187
5188 static void
5189 remote_detach_pid (int pid)
5190 {
5191 struct remote_state *rs = get_remote_state ();
5192
5193 if (remote_multi_process_p (rs))
5194 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5195 else
5196 strcpy (rs->buf, "D");
5197
5198 putpkt (rs->buf);
5199 getpkt (&rs->buf, &rs->buf_size, 0);
5200
5201 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5202 ;
5203 else if (rs->buf[0] == '\0')
5204 error (_("Remote doesn't know how to detach"));
5205 else
5206 error (_("Can't detach process."));
5207 }
5208
5209 /* This detaches a program to which we previously attached, using
5210 inferior_ptid to identify the process. After this is done, GDB
5211 can be used to debug some other program. We better not have left
5212 any breakpoints in the target program or it'll die when it hits
5213 one. */
5214
5215 static void
5216 remote_detach_1 (const char *args, int from_tty)
5217 {
5218 int pid = ptid_get_pid (inferior_ptid);
5219 struct remote_state *rs = get_remote_state ();
5220 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5221 int is_fork_parent;
5222
5223 if (args)
5224 error (_("Argument given to \"detach\" when remotely debugging."));
5225
5226 if (!target_has_execution)
5227 error (_("No process to detach from."));
5228
5229 target_announce_detach (from_tty);
5230
5231 /* Tell the remote target to detach. */
5232 remote_detach_pid (pid);
5233
5234 /* Exit only if this is the only active inferior. */
5235 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5236 puts_filtered (_("Ending remote debugging.\n"));
5237
5238 /* Check to see if we are detaching a fork parent. Note that if we
5239 are detaching a fork child, tp == NULL. */
5240 is_fork_parent = (tp != NULL
5241 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5242
5243 /* If doing detach-on-fork, we don't mourn, because that will delete
5244 breakpoints that should be available for the followed inferior. */
5245 if (!is_fork_parent)
5246 target_mourn_inferior (inferior_ptid);
5247 else
5248 {
5249 inferior_ptid = null_ptid;
5250 detach_inferior (pid);
5251 }
5252 }
5253
5254 static void
5255 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5256 {
5257 remote_detach_1 (args, from_tty);
5258 }
5259
5260 static void
5261 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5262 {
5263 remote_detach_1 (args, from_tty);
5264 }
5265
5266 /* Target follow-fork function for remote targets. On entry, and
5267 at return, the current inferior is the fork parent.
5268
5269 Note that although this is currently only used for extended-remote,
5270 it is named remote_follow_fork in anticipation of using it for the
5271 remote target as well. */
5272
5273 static int
5274 remote_follow_fork (struct target_ops *ops, int follow_child,
5275 int detach_fork)
5276 {
5277 struct remote_state *rs = get_remote_state ();
5278 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5279
5280 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5281 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5282 {
5283 /* When following the parent and detaching the child, we detach
5284 the child here. For the case of following the child and
5285 detaching the parent, the detach is done in the target-
5286 independent follow fork code in infrun.c. We can't use
5287 target_detach when detaching an unfollowed child because
5288 the client side doesn't know anything about the child. */
5289 if (detach_fork && !follow_child)
5290 {
5291 /* Detach the fork child. */
5292 ptid_t child_ptid;
5293 pid_t child_pid;
5294
5295 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5296 child_pid = ptid_get_pid (child_ptid);
5297
5298 remote_detach_pid (child_pid);
5299 detach_inferior (child_pid);
5300 }
5301 }
5302 return 0;
5303 }
5304
5305 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5306 in the program space of the new inferior. On entry and at return the
5307 current inferior is the exec'ing inferior. INF is the new exec'd
5308 inferior, which may be the same as the exec'ing inferior unless
5309 follow-exec-mode is "new". */
5310
5311 static void
5312 remote_follow_exec (struct target_ops *ops,
5313 struct inferior *inf, char *execd_pathname)
5314 {
5315 /* We know that this is a target file name, so if it has the "target:"
5316 prefix we strip it off before saving it in the program space. */
5317 if (is_target_filename (execd_pathname))
5318 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5319
5320 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5321 }
5322
5323 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5324
5325 static void
5326 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5327 {
5328 if (args)
5329 error (_("Argument given to \"disconnect\" when remotely debugging."));
5330
5331 /* Make sure we unpush even the extended remote targets. Calling
5332 target_mourn_inferior won't unpush, and remote_mourn won't
5333 unpush if there is more than one inferior left. */
5334 unpush_target (target);
5335 generic_mourn_inferior ();
5336
5337 if (from_tty)
5338 puts_filtered ("Ending remote debugging.\n");
5339 }
5340
5341 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5342 be chatty about it. */
5343
5344 static void
5345 extended_remote_attach (struct target_ops *target, const char *args,
5346 int from_tty)
5347 {
5348 struct remote_state *rs = get_remote_state ();
5349 int pid;
5350 char *wait_status = NULL;
5351
5352 pid = parse_pid_to_attach (args);
5353
5354 /* Remote PID can be freely equal to getpid, do not check it here the same
5355 way as in other targets. */
5356
5357 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5358 error (_("This target does not support attaching to a process"));
5359
5360 if (from_tty)
5361 {
5362 char *exec_file = get_exec_file (0);
5363
5364 if (exec_file)
5365 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5366 target_pid_to_str (pid_to_ptid (pid)));
5367 else
5368 printf_unfiltered (_("Attaching to %s\n"),
5369 target_pid_to_str (pid_to_ptid (pid)));
5370
5371 gdb_flush (gdb_stdout);
5372 }
5373
5374 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5375 putpkt (rs->buf);
5376 getpkt (&rs->buf, &rs->buf_size, 0);
5377
5378 switch (packet_ok (rs->buf,
5379 &remote_protocol_packets[PACKET_vAttach]))
5380 {
5381 case PACKET_OK:
5382 if (!target_is_non_stop_p ())
5383 {
5384 /* Save the reply for later. */
5385 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5386 strcpy (wait_status, rs->buf);
5387 }
5388 else if (strcmp (rs->buf, "OK") != 0)
5389 error (_("Attaching to %s failed with: %s"),
5390 target_pid_to_str (pid_to_ptid (pid)),
5391 rs->buf);
5392 break;
5393 case PACKET_UNKNOWN:
5394 error (_("This target does not support attaching to a process"));
5395 default:
5396 error (_("Attaching to %s failed"),
5397 target_pid_to_str (pid_to_ptid (pid)));
5398 }
5399
5400 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5401
5402 inferior_ptid = pid_to_ptid (pid);
5403
5404 if (target_is_non_stop_p ())
5405 {
5406 struct thread_info *thread;
5407
5408 /* Get list of threads. */
5409 remote_update_thread_list (target);
5410
5411 thread = first_thread_of_process (pid);
5412 if (thread)
5413 inferior_ptid = thread->ptid;
5414 else
5415 inferior_ptid = pid_to_ptid (pid);
5416
5417 /* Invalidate our notion of the remote current thread. */
5418 record_currthread (rs, minus_one_ptid);
5419 }
5420 else
5421 {
5422 /* Now, if we have thread information, update inferior_ptid. */
5423 inferior_ptid = remote_current_thread (inferior_ptid);
5424
5425 /* Add the main thread to the thread list. */
5426 add_thread_silent (inferior_ptid);
5427 }
5428
5429 /* Next, if the target can specify a description, read it. We do
5430 this before anything involving memory or registers. */
5431 target_find_description ();
5432
5433 if (!target_is_non_stop_p ())
5434 {
5435 /* Use the previously fetched status. */
5436 gdb_assert (wait_status != NULL);
5437
5438 if (target_can_async_p ())
5439 {
5440 struct notif_event *reply
5441 = remote_notif_parse (&notif_client_stop, wait_status);
5442
5443 push_stop_reply ((struct stop_reply *) reply);
5444
5445 target_async (1);
5446 }
5447 else
5448 {
5449 gdb_assert (wait_status != NULL);
5450 strcpy (rs->buf, wait_status);
5451 rs->cached_wait_status = 1;
5452 }
5453 }
5454 else
5455 gdb_assert (wait_status == NULL);
5456 }
5457
5458 /* Implementation of the to_post_attach method. */
5459
5460 static void
5461 extended_remote_post_attach (struct target_ops *ops, int pid)
5462 {
5463 /* Get text, data & bss offsets. */
5464 get_offsets ();
5465
5466 /* In certain cases GDB might not have had the chance to start
5467 symbol lookup up until now. This could happen if the debugged
5468 binary is not using shared libraries, the vsyscall page is not
5469 present (on Linux) and the binary itself hadn't changed since the
5470 debugging process was started. */
5471 if (symfile_objfile != NULL)
5472 remote_check_symbols();
5473 }
5474
5475 \f
5476 /* Check for the availability of vCont. This function should also check
5477 the response. */
5478
5479 static void
5480 remote_vcont_probe (struct remote_state *rs)
5481 {
5482 char *buf;
5483
5484 strcpy (rs->buf, "vCont?");
5485 putpkt (rs->buf);
5486 getpkt (&rs->buf, &rs->buf_size, 0);
5487 buf = rs->buf;
5488
5489 /* Make sure that the features we assume are supported. */
5490 if (startswith (buf, "vCont"))
5491 {
5492 char *p = &buf[5];
5493 int support_c, support_C;
5494
5495 rs->supports_vCont.s = 0;
5496 rs->supports_vCont.S = 0;
5497 support_c = 0;
5498 support_C = 0;
5499 rs->supports_vCont.t = 0;
5500 rs->supports_vCont.r = 0;
5501 while (p && *p == ';')
5502 {
5503 p++;
5504 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5505 rs->supports_vCont.s = 1;
5506 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5507 rs->supports_vCont.S = 1;
5508 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5509 support_c = 1;
5510 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5511 support_C = 1;
5512 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5513 rs->supports_vCont.t = 1;
5514 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5515 rs->supports_vCont.r = 1;
5516
5517 p = strchr (p, ';');
5518 }
5519
5520 /* If c, and C are not all supported, we can't use vCont. Clearing
5521 BUF will make packet_ok disable the packet. */
5522 if (!support_c || !support_C)
5523 buf[0] = 0;
5524 }
5525
5526 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5527 }
5528
5529 /* Helper function for building "vCont" resumptions. Write a
5530 resumption to P. ENDP points to one-passed-the-end of the buffer
5531 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5532 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5533 resumed thread should be single-stepped and/or signalled. If PTID
5534 equals minus_one_ptid, then all threads are resumed; if PTID
5535 represents a process, then all threads of the process are resumed;
5536 the thread to be stepped and/or signalled is given in the global
5537 INFERIOR_PTID. */
5538
5539 static char *
5540 append_resumption (char *p, char *endp,
5541 ptid_t ptid, int step, enum gdb_signal siggnal)
5542 {
5543 struct remote_state *rs = get_remote_state ();
5544
5545 if (step && siggnal != GDB_SIGNAL_0)
5546 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5547 else if (step
5548 /* GDB is willing to range step. */
5549 && use_range_stepping
5550 /* Target supports range stepping. */
5551 && rs->supports_vCont.r
5552 /* We don't currently support range stepping multiple
5553 threads with a wildcard (though the protocol allows it,
5554 so stubs shouldn't make an active effort to forbid
5555 it). */
5556 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5557 {
5558 struct thread_info *tp;
5559
5560 if (ptid_equal (ptid, minus_one_ptid))
5561 {
5562 /* If we don't know about the target thread's tid, then
5563 we're resuming magic_null_ptid (see caller). */
5564 tp = find_thread_ptid (magic_null_ptid);
5565 }
5566 else
5567 tp = find_thread_ptid (ptid);
5568 gdb_assert (tp != NULL);
5569
5570 if (tp->control.may_range_step)
5571 {
5572 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5573
5574 p += xsnprintf (p, endp - p, ";r%s,%s",
5575 phex_nz (tp->control.step_range_start,
5576 addr_size),
5577 phex_nz (tp->control.step_range_end,
5578 addr_size));
5579 }
5580 else
5581 p += xsnprintf (p, endp - p, ";s");
5582 }
5583 else if (step)
5584 p += xsnprintf (p, endp - p, ";s");
5585 else if (siggnal != GDB_SIGNAL_0)
5586 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5587 else
5588 p += xsnprintf (p, endp - p, ";c");
5589
5590 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5591 {
5592 ptid_t nptid;
5593
5594 /* All (-1) threads of process. */
5595 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5596
5597 p += xsnprintf (p, endp - p, ":");
5598 p = write_ptid (p, endp, nptid);
5599 }
5600 else if (!ptid_equal (ptid, minus_one_ptid))
5601 {
5602 p += xsnprintf (p, endp - p, ":");
5603 p = write_ptid (p, endp, ptid);
5604 }
5605
5606 return p;
5607 }
5608
5609 /* Clear the thread's private info on resume. */
5610
5611 static void
5612 resume_clear_thread_private_info (struct thread_info *thread)
5613 {
5614 if (thread->priv != NULL)
5615 {
5616 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5617 thread->priv->watch_data_address = 0;
5618 }
5619 }
5620
5621 /* Append a vCont continue-with-signal action for threads that have a
5622 non-zero stop signal. */
5623
5624 static char *
5625 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5626 {
5627 struct thread_info *thread;
5628
5629 ALL_NON_EXITED_THREADS (thread)
5630 if (ptid_match (thread->ptid, ptid)
5631 && !ptid_equal (inferior_ptid, thread->ptid)
5632 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5633 {
5634 p = append_resumption (p, endp, thread->ptid,
5635 0, thread->suspend.stop_signal);
5636 thread->suspend.stop_signal = GDB_SIGNAL_0;
5637 resume_clear_thread_private_info (thread);
5638 }
5639
5640 return p;
5641 }
5642
5643 /* Set the target running, using the packets that use Hc
5644 (c/s/C/S). */
5645
5646 static void
5647 remote_resume_with_hc (struct target_ops *ops,
5648 ptid_t ptid, int step, enum gdb_signal siggnal)
5649 {
5650 struct remote_state *rs = get_remote_state ();
5651 struct thread_info *thread;
5652 char *buf;
5653
5654 rs->last_sent_signal = siggnal;
5655 rs->last_sent_step = step;
5656
5657 /* The c/s/C/S resume packets use Hc, so set the continue
5658 thread. */
5659 if (ptid_equal (ptid, minus_one_ptid))
5660 set_continue_thread (any_thread_ptid);
5661 else
5662 set_continue_thread (ptid);
5663
5664 ALL_NON_EXITED_THREADS (thread)
5665 resume_clear_thread_private_info (thread);
5666
5667 buf = rs->buf;
5668 if (execution_direction == EXEC_REVERSE)
5669 {
5670 /* We don't pass signals to the target in reverse exec mode. */
5671 if (info_verbose && siggnal != GDB_SIGNAL_0)
5672 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5673 siggnal);
5674
5675 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5676 error (_("Remote reverse-step not supported."));
5677 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5678 error (_("Remote reverse-continue not supported."));
5679
5680 strcpy (buf, step ? "bs" : "bc");
5681 }
5682 else if (siggnal != GDB_SIGNAL_0)
5683 {
5684 buf[0] = step ? 'S' : 'C';
5685 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5686 buf[2] = tohex (((int) siggnal) & 0xf);
5687 buf[3] = '\0';
5688 }
5689 else
5690 strcpy (buf, step ? "s" : "c");
5691
5692 putpkt (buf);
5693 }
5694
5695 /* Resume the remote inferior by using a "vCont" packet. The thread
5696 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5697 resumed thread should be single-stepped and/or signalled. If PTID
5698 equals minus_one_ptid, then all threads are resumed; the thread to
5699 be stepped and/or signalled is given in the global INFERIOR_PTID.
5700 This function returns non-zero iff it resumes the inferior.
5701
5702 This function issues a strict subset of all possible vCont commands
5703 at the moment. */
5704
5705 static int
5706 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5707 {
5708 struct remote_state *rs = get_remote_state ();
5709 char *p;
5710 char *endp;
5711
5712 /* No reverse execution actions defined for vCont. */
5713 if (execution_direction == EXEC_REVERSE)
5714 return 0;
5715
5716 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5717 remote_vcont_probe (rs);
5718
5719 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5720 return 0;
5721
5722 p = rs->buf;
5723 endp = rs->buf + get_remote_packet_size ();
5724
5725 /* If we could generate a wider range of packets, we'd have to worry
5726 about overflowing BUF. Should there be a generic
5727 "multi-part-packet" packet? */
5728
5729 p += xsnprintf (p, endp - p, "vCont");
5730
5731 if (ptid_equal (ptid, magic_null_ptid))
5732 {
5733 /* MAGIC_NULL_PTID means that we don't have any active threads,
5734 so we don't have any TID numbers the inferior will
5735 understand. Make sure to only send forms that do not specify
5736 a TID. */
5737 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5738 }
5739 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5740 {
5741 /* Resume all threads (of all processes, or of a single
5742 process), with preference for INFERIOR_PTID. This assumes
5743 inferior_ptid belongs to the set of all threads we are about
5744 to resume. */
5745 if (step || siggnal != GDB_SIGNAL_0)
5746 {
5747 /* Step inferior_ptid, with or without signal. */
5748 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5749 }
5750
5751 /* Also pass down any pending signaled resumption for other
5752 threads not the current. */
5753 p = append_pending_thread_resumptions (p, endp, ptid);
5754
5755 /* And continue others without a signal. */
5756 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5757 }
5758 else
5759 {
5760 /* Scheduler locking; resume only PTID. */
5761 append_resumption (p, endp, ptid, step, siggnal);
5762 }
5763
5764 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5765 putpkt (rs->buf);
5766
5767 if (target_is_non_stop_p ())
5768 {
5769 /* In non-stop, the stub replies to vCont with "OK". The stop
5770 reply will be reported asynchronously by means of a `%Stop'
5771 notification. */
5772 getpkt (&rs->buf, &rs->buf_size, 0);
5773 if (strcmp (rs->buf, "OK") != 0)
5774 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5775 }
5776
5777 return 1;
5778 }
5779
5780 /* Tell the remote machine to resume. */
5781
5782 static void
5783 remote_resume (struct target_ops *ops,
5784 ptid_t ptid, int step, enum gdb_signal siggnal)
5785 {
5786 struct remote_state *rs = get_remote_state ();
5787
5788 /* When connected in non-stop mode, the core resumes threads
5789 individually. Resuming remote threads directly in target_resume
5790 would thus result in sending one packet per thread. Instead, to
5791 minimize roundtrip latency, here we just store the resume
5792 request; the actual remote resumption will be done in
5793 target_commit_resume / remote_commit_resume, where we'll be able
5794 to do vCont action coalescing. */
5795 if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5796 {
5797 struct private_thread_info *remote_thr;
5798
5799 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5800 remote_thr = get_private_info_ptid (inferior_ptid);
5801 else
5802 remote_thr = get_private_info_ptid (ptid);
5803 remote_thr->last_resume_step = step;
5804 remote_thr->last_resume_sig = siggnal;
5805 return;
5806 }
5807
5808 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5809 (explained in remote-notif.c:handle_notification) so
5810 remote_notif_process is not called. We need find a place where
5811 it is safe to start a 'vNotif' sequence. It is good to do it
5812 before resuming inferior, because inferior was stopped and no RSP
5813 traffic at that moment. */
5814 if (!target_is_non_stop_p ())
5815 remote_notif_process (rs->notif_state, &notif_client_stop);
5816
5817 rs->last_resume_exec_dir = execution_direction;
5818
5819 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
5820 if (!remote_resume_with_vcont (ptid, step, siggnal))
5821 remote_resume_with_hc (ops, ptid, step, siggnal);
5822
5823 /* We are about to start executing the inferior, let's register it
5824 with the event loop. NOTE: this is the one place where all the
5825 execution commands end up. We could alternatively do this in each
5826 of the execution commands in infcmd.c. */
5827 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5828 into infcmd.c in order to allow inferior function calls to work
5829 NOT asynchronously. */
5830 if (target_can_async_p ())
5831 target_async (1);
5832
5833 /* We've just told the target to resume. The remote server will
5834 wait for the inferior to stop, and then send a stop reply. In
5835 the mean time, we can't start another command/query ourselves
5836 because the stub wouldn't be ready to process it. This applies
5837 only to the base all-stop protocol, however. In non-stop (which
5838 only supports vCont), the stub replies with an "OK", and is
5839 immediate able to process further serial input. */
5840 if (!target_is_non_stop_p ())
5841 rs->waiting_for_stop_reply = 1;
5842 }
5843
5844 static void check_pending_events_prevent_wildcard_vcont
5845 (int *may_global_wildcard_vcont);
5846 static int is_pending_fork_parent_thread (struct thread_info *thread);
5847
5848 /* Private per-inferior info for target remote processes. */
5849
5850 struct private_inferior
5851 {
5852 /* Whether we can send a wildcard vCont for this process. */
5853 int may_wildcard_vcont;
5854 };
5855
5856 /* Structure used to track the construction of a vCont packet in the
5857 outgoing packet buffer. This is used to send multiple vCont
5858 packets if we have more actions than would fit a single packet. */
5859
5860 struct vcont_builder
5861 {
5862 /* Pointer to the first action. P points here if no action has been
5863 appended yet. */
5864 char *first_action;
5865
5866 /* Where the next action will be appended. */
5867 char *p;
5868
5869 /* The end of the buffer. Must never write past this. */
5870 char *endp;
5871 };
5872
5873 /* Prepare the outgoing buffer for a new vCont packet. */
5874
5875 static void
5876 vcont_builder_restart (struct vcont_builder *builder)
5877 {
5878 struct remote_state *rs = get_remote_state ();
5879
5880 builder->p = rs->buf;
5881 builder->endp = rs->buf + get_remote_packet_size ();
5882 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5883 builder->first_action = builder->p;
5884 }
5885
5886 /* If the vCont packet being built has any action, send it to the
5887 remote end. */
5888
5889 static void
5890 vcont_builder_flush (struct vcont_builder *builder)
5891 {
5892 struct remote_state *rs;
5893
5894 if (builder->p == builder->first_action)
5895 return;
5896
5897 rs = get_remote_state ();
5898 putpkt (rs->buf);
5899 getpkt (&rs->buf, &rs->buf_size, 0);
5900 if (strcmp (rs->buf, "OK") != 0)
5901 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5902 }
5903
5904 /* The largest action is range-stepping, with its two addresses. This
5905 is more than sufficient. If a new, bigger action is created, it'll
5906 quickly trigger a failed assertion in append_resumption (and we'll
5907 just bump this). */
5908 #define MAX_ACTION_SIZE 200
5909
5910 /* Append a new vCont action in the outgoing packet being built. If
5911 the action doesn't fit the packet along with previous actions, push
5912 what we've got so far to the remote end and start over a new vCont
5913 packet (with the new action). */
5914
5915 static void
5916 vcont_builder_push_action (struct vcont_builder *builder,
5917 ptid_t ptid, int step, enum gdb_signal siggnal)
5918 {
5919 char buf[MAX_ACTION_SIZE + 1];
5920 char *endp;
5921 size_t rsize;
5922
5923 endp = append_resumption (buf, buf + sizeof (buf),
5924 ptid, step, siggnal);
5925
5926 /* Check whether this new action would fit in the vCont packet along
5927 with previous actions. If not, send what we've got so far and
5928 start a new vCont packet. */
5929 rsize = endp - buf;
5930 if (rsize > builder->endp - builder->p)
5931 {
5932 vcont_builder_flush (builder);
5933 vcont_builder_restart (builder);
5934
5935 /* Should now fit. */
5936 gdb_assert (rsize <= builder->endp - builder->p);
5937 }
5938
5939 memcpy (builder->p, buf, rsize);
5940 builder->p += rsize;
5941 *builder->p = '\0';
5942 }
5943
5944 /* to_commit_resume implementation. */
5945
5946 static void
5947 remote_commit_resume (struct target_ops *ops)
5948 {
5949 struct remote_state *rs = get_remote_state ();
5950 struct inferior *inf;
5951 struct thread_info *tp;
5952 int any_process_wildcard;
5953 int may_global_wildcard_vcont;
5954 struct vcont_builder vcont_builder;
5955
5956 /* If connected in all-stop mode, we'd send the remote resume
5957 request directly from remote_resume. Likewise if
5958 reverse-debugging, as there are no defined vCont actions for
5959 reverse execution. */
5960 if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5961 return;
5962
5963 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5964 instead of resuming all threads of each process individually.
5965 However, if any thread of a process must remain halted, we can't
5966 send wildcard resumes and must send one action per thread.
5967
5968 Care must be taken to not resume threads/processes the server
5969 side already told us are stopped, but the core doesn't know about
5970 yet, because the events are still in the vStopped notification
5971 queue. For example:
5972
5973 #1 => vCont s:p1.1;c
5974 #2 <= OK
5975 #3 <= %Stopped T05 p1.1
5976 #4 => vStopped
5977 #5 <= T05 p1.2
5978 #6 => vStopped
5979 #7 <= OK
5980 #8 (infrun handles the stop for p1.1 and continues stepping)
5981 #9 => vCont s:p1.1;c
5982
5983 The last vCont above would resume thread p1.2 by mistake, because
5984 the server has no idea that the event for p1.2 had not been
5985 handled yet.
5986
5987 The server side must similarly ignore resume actions for the
5988 thread that has a pending %Stopped notification (and any other
5989 threads with events pending), until GDB acks the notification
5990 with vStopped. Otherwise, e.g., the following case is
5991 mishandled:
5992
5993 #1 => g (or any other packet)
5994 #2 <= [registers]
5995 #3 <= %Stopped T05 p1.2
5996 #4 => vCont s:p1.1;c
5997 #5 <= OK
5998
5999 Above, the server must not resume thread p1.2. GDB can't know
6000 that p1.2 stopped until it acks the %Stopped notification, and
6001 since from GDB's perspective all threads should be running, it
6002 sends a "c" action.
6003
6004 Finally, special care must also be given to handling fork/vfork
6005 events. A (v)fork event actually tells us that two processes
6006 stopped -- the parent and the child. Until we follow the fork,
6007 we must not resume the child. Therefore, if we have a pending
6008 fork follow, we must not send a global wildcard resume action
6009 (vCont;c). We can still send process-wide wildcards though. */
6010
6011 /* Start by assuming a global wildcard (vCont;c) is possible. */
6012 may_global_wildcard_vcont = 1;
6013
6014 /* And assume every process is individually wildcard-able too. */
6015 ALL_NON_EXITED_INFERIORS (inf)
6016 {
6017 if (inf->priv == NULL)
6018 inf->priv = XNEW (struct private_inferior);
6019 inf->priv->may_wildcard_vcont = 1;
6020 }
6021
6022 /* Check for any pending events (not reported or processed yet) and
6023 disable process and global wildcard resumes appropriately. */
6024 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6025
6026 ALL_NON_EXITED_THREADS (tp)
6027 {
6028 /* If a thread of a process is not meant to be resumed, then we
6029 can't wildcard that process. */
6030 if (!tp->executing)
6031 {
6032 tp->inf->priv->may_wildcard_vcont = 0;
6033
6034 /* And if we can't wildcard a process, we can't wildcard
6035 everything either. */
6036 may_global_wildcard_vcont = 0;
6037 continue;
6038 }
6039
6040 /* If a thread is the parent of an unfollowed fork, then we
6041 can't do a global wildcard, as that would resume the fork
6042 child. */
6043 if (is_pending_fork_parent_thread (tp))
6044 may_global_wildcard_vcont = 0;
6045 }
6046
6047 /* Now let's build the vCont packet(s). Actions must be appended
6048 from narrower to wider scopes (thread -> process -> global). If
6049 we end up with too many actions for a single packet vcont_builder
6050 flushes the current vCont packet to the remote side and starts a
6051 new one. */
6052 vcont_builder_restart (&vcont_builder);
6053
6054 /* Threads first. */
6055 ALL_NON_EXITED_THREADS (tp)
6056 {
6057 struct private_thread_info *remote_thr = tp->priv;
6058
6059 if (!tp->executing || remote_thr->vcont_resumed)
6060 continue;
6061
6062 gdb_assert (!thread_is_in_step_over_chain (tp));
6063
6064 if (!remote_thr->last_resume_step
6065 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6066 && tp->inf->priv->may_wildcard_vcont)
6067 {
6068 /* We'll send a wildcard resume instead. */
6069 remote_thr->vcont_resumed = 1;
6070 continue;
6071 }
6072
6073 vcont_builder_push_action (&vcont_builder, tp->ptid,
6074 remote_thr->last_resume_step,
6075 remote_thr->last_resume_sig);
6076 remote_thr->vcont_resumed = 1;
6077 }
6078
6079 /* Now check whether we can send any process-wide wildcard. This is
6080 to avoid sending a global wildcard in the case nothing is
6081 supposed to be resumed. */
6082 any_process_wildcard = 0;
6083
6084 ALL_NON_EXITED_INFERIORS (inf)
6085 {
6086 if (inf->priv->may_wildcard_vcont)
6087 {
6088 any_process_wildcard = 1;
6089 break;
6090 }
6091 }
6092
6093 if (any_process_wildcard)
6094 {
6095 /* If all processes are wildcard-able, then send a single "c"
6096 action, otherwise, send an "all (-1) threads of process"
6097 continue action for each running process, if any. */
6098 if (may_global_wildcard_vcont)
6099 {
6100 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6101 0, GDB_SIGNAL_0);
6102 }
6103 else
6104 {
6105 ALL_NON_EXITED_INFERIORS (inf)
6106 {
6107 if (inf->priv->may_wildcard_vcont)
6108 {
6109 vcont_builder_push_action (&vcont_builder,
6110 pid_to_ptid (inf->pid),
6111 0, GDB_SIGNAL_0);
6112 }
6113 }
6114 }
6115 }
6116
6117 vcont_builder_flush (&vcont_builder);
6118 }
6119
6120 \f
6121
6122 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6123 thread, all threads of a remote process, or all threads of all
6124 processes. */
6125
6126 static void
6127 remote_stop_ns (ptid_t ptid)
6128 {
6129 struct remote_state *rs = get_remote_state ();
6130 char *p = rs->buf;
6131 char *endp = rs->buf + get_remote_packet_size ();
6132
6133 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6134 remote_vcont_probe (rs);
6135
6136 if (!rs->supports_vCont.t)
6137 error (_("Remote server does not support stopping threads"));
6138
6139 if (ptid_equal (ptid, minus_one_ptid)
6140 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6141 p += xsnprintf (p, endp - p, "vCont;t");
6142 else
6143 {
6144 ptid_t nptid;
6145
6146 p += xsnprintf (p, endp - p, "vCont;t:");
6147
6148 if (ptid_is_pid (ptid))
6149 /* All (-1) threads of process. */
6150 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6151 else
6152 {
6153 /* Small optimization: if we already have a stop reply for
6154 this thread, no use in telling the stub we want this
6155 stopped. */
6156 if (peek_stop_reply (ptid))
6157 return;
6158
6159 nptid = ptid;
6160 }
6161
6162 write_ptid (p, endp, nptid);
6163 }
6164
6165 /* In non-stop, we get an immediate OK reply. The stop reply will
6166 come in asynchronously by notification. */
6167 putpkt (rs->buf);
6168 getpkt (&rs->buf, &rs->buf_size, 0);
6169 if (strcmp (rs->buf, "OK") != 0)
6170 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6171 }
6172
6173 /* All-stop version of target_interrupt. Sends a break or a ^C to
6174 interrupt the remote target. It is undefined which thread of which
6175 process reports the interrupt. */
6176
6177 static void
6178 remote_interrupt_as (void)
6179 {
6180 struct remote_state *rs = get_remote_state ();
6181
6182 rs->ctrlc_pending_p = 1;
6183
6184 /* If the inferior is stopped already, but the core didn't know
6185 about it yet, just ignore the request. The cached wait status
6186 will be collected in remote_wait. */
6187 if (rs->cached_wait_status)
6188 return;
6189
6190 /* Send interrupt_sequence to remote target. */
6191 send_interrupt_sequence ();
6192 }
6193
6194 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6195 the remote target. It is undefined which thread of which process
6196 reports the interrupt. Throws an error if the packet is not
6197 supported by the server. */
6198
6199 static void
6200 remote_interrupt_ns (void)
6201 {
6202 struct remote_state *rs = get_remote_state ();
6203 char *p = rs->buf;
6204 char *endp = rs->buf + get_remote_packet_size ();
6205
6206 xsnprintf (p, endp - p, "vCtrlC");
6207
6208 /* In non-stop, we get an immediate OK reply. The stop reply will
6209 come in asynchronously by notification. */
6210 putpkt (rs->buf);
6211 getpkt (&rs->buf, &rs->buf_size, 0);
6212
6213 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6214 {
6215 case PACKET_OK:
6216 break;
6217 case PACKET_UNKNOWN:
6218 error (_("No support for interrupting the remote target."));
6219 case PACKET_ERROR:
6220 error (_("Interrupting target failed: %s"), rs->buf);
6221 }
6222 }
6223
6224 /* Implement the to_stop function for the remote targets. */
6225
6226 static void
6227 remote_stop (struct target_ops *self, ptid_t ptid)
6228 {
6229 if (remote_debug)
6230 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6231
6232 if (target_is_non_stop_p ())
6233 remote_stop_ns (ptid);
6234 else
6235 {
6236 /* We don't currently have a way to transparently pause the
6237 remote target in all-stop mode. Interrupt it instead. */
6238 remote_interrupt_as ();
6239 }
6240 }
6241
6242 /* Implement the to_interrupt function for the remote targets. */
6243
6244 static void
6245 remote_interrupt (struct target_ops *self, ptid_t ptid)
6246 {
6247 struct remote_state *rs = get_remote_state ();
6248
6249 if (remote_debug)
6250 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6251
6252 if (target_is_non_stop_p ())
6253 remote_interrupt_ns ();
6254 else
6255 remote_interrupt_as ();
6256 }
6257
6258 /* Implement the to_pass_ctrlc function for the remote targets. */
6259
6260 static void
6261 remote_pass_ctrlc (struct target_ops *self)
6262 {
6263 struct remote_state *rs = get_remote_state ();
6264
6265 if (remote_debug)
6266 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6267
6268 /* If we're starting up, we're not fully synced yet. Quit
6269 immediately. */
6270 if (rs->starting_up)
6271 quit ();
6272 /* If ^C has already been sent once, offer to disconnect. */
6273 else if (rs->ctrlc_pending_p)
6274 interrupt_query ();
6275 else
6276 target_interrupt (inferior_ptid);
6277 }
6278
6279 /* Ask the user what to do when an interrupt is received. */
6280
6281 static void
6282 interrupt_query (void)
6283 {
6284 struct remote_state *rs = get_remote_state ();
6285
6286 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6287 {
6288 if (query (_("The target is not responding to interrupt requests.\n"
6289 "Stop debugging it? ")))
6290 {
6291 remote_unpush_target ();
6292 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6293 }
6294 }
6295 else
6296 {
6297 if (query (_("Interrupted while waiting for the program.\n"
6298 "Give up waiting? ")))
6299 quit ();
6300 }
6301 }
6302
6303 /* Enable/disable target terminal ownership. Most targets can use
6304 terminal groups to control terminal ownership. Remote targets are
6305 different in that explicit transfer of ownership to/from GDB/target
6306 is required. */
6307
6308 static void
6309 remote_terminal_inferior (struct target_ops *self)
6310 {
6311 /* FIXME: cagney/1999-09-27: Make calls to target_terminal::*()
6312 idempotent. The event-loop GDB talking to an asynchronous target
6313 with a synchronous command calls this function from both
6314 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
6315 transfer the terminal to the target when it shouldn't this guard
6316 can go away. */
6317 if (!remote_async_terminal_ours_p)
6318 return;
6319 remote_async_terminal_ours_p = 0;
6320 /* NOTE: At this point we could also register our selves as the
6321 recipient of all input. Any characters typed could then be
6322 passed on down to the target. */
6323 }
6324
6325 static void
6326 remote_terminal_ours (struct target_ops *self)
6327 {
6328 /* See FIXME in remote_terminal_inferior. */
6329 if (remote_async_terminal_ours_p)
6330 return;
6331 remote_async_terminal_ours_p = 1;
6332 }
6333
6334 static void
6335 remote_console_output (char *msg)
6336 {
6337 char *p;
6338
6339 for (p = msg; p[0] && p[1]; p += 2)
6340 {
6341 char tb[2];
6342 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6343
6344 tb[0] = c;
6345 tb[1] = 0;
6346 fputs_unfiltered (tb, gdb_stdtarg);
6347 }
6348 gdb_flush (gdb_stdtarg);
6349 }
6350
6351 DEF_VEC_O(cached_reg_t);
6352
6353 typedef struct stop_reply
6354 {
6355 struct notif_event base;
6356
6357 /* The identifier of the thread about this event */
6358 ptid_t ptid;
6359
6360 /* The remote state this event is associated with. When the remote
6361 connection, represented by a remote_state object, is closed,
6362 all the associated stop_reply events should be released. */
6363 struct remote_state *rs;
6364
6365 struct target_waitstatus ws;
6366
6367 /* Expedited registers. This makes remote debugging a bit more
6368 efficient for those targets that provide critical registers as
6369 part of their normal status mechanism (as another roundtrip to
6370 fetch them is avoided). */
6371 VEC(cached_reg_t) *regcache;
6372
6373 enum target_stop_reason stop_reason;
6374
6375 CORE_ADDR watch_data_address;
6376
6377 int core;
6378 } *stop_reply_p;
6379
6380 DECLARE_QUEUE_P (stop_reply_p);
6381 DEFINE_QUEUE_P (stop_reply_p);
6382 /* The list of already fetched and acknowledged stop events. This
6383 queue is used for notification Stop, and other notifications
6384 don't need queue for their events, because the notification events
6385 of Stop can't be consumed immediately, so that events should be
6386 queued first, and be consumed by remote_wait_{ns,as} one per
6387 time. Other notifications can consume their events immediately,
6388 so queue is not needed for them. */
6389 static QUEUE (stop_reply_p) *stop_reply_queue;
6390
6391 static void
6392 stop_reply_xfree (struct stop_reply *r)
6393 {
6394 notif_event_xfree ((struct notif_event *) r);
6395 }
6396
6397 /* Return the length of the stop reply queue. */
6398
6399 static int
6400 stop_reply_queue_length (void)
6401 {
6402 return QUEUE_length (stop_reply_p, stop_reply_queue);
6403 }
6404
6405 static void
6406 remote_notif_stop_parse (struct notif_client *self, char *buf,
6407 struct notif_event *event)
6408 {
6409 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6410 }
6411
6412 static void
6413 remote_notif_stop_ack (struct notif_client *self, char *buf,
6414 struct notif_event *event)
6415 {
6416 struct stop_reply *stop_reply = (struct stop_reply *) event;
6417
6418 /* acknowledge */
6419 putpkt (self->ack_command);
6420
6421 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6422 /* We got an unknown stop reply. */
6423 error (_("Unknown stop reply"));
6424
6425 push_stop_reply (stop_reply);
6426 }
6427
6428 static int
6429 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6430 {
6431 /* We can't get pending events in remote_notif_process for
6432 notification stop, and we have to do this in remote_wait_ns
6433 instead. If we fetch all queued events from stub, remote stub
6434 may exit and we have no chance to process them back in
6435 remote_wait_ns. */
6436 mark_async_event_handler (remote_async_inferior_event_token);
6437 return 0;
6438 }
6439
6440 static void
6441 stop_reply_dtr (struct notif_event *event)
6442 {
6443 struct stop_reply *r = (struct stop_reply *) event;
6444 cached_reg_t *reg;
6445 int ix;
6446
6447 for (ix = 0;
6448 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6449 ix++)
6450 xfree (reg->data);
6451
6452 VEC_free (cached_reg_t, r->regcache);
6453 }
6454
6455 static struct notif_event *
6456 remote_notif_stop_alloc_reply (void)
6457 {
6458 /* We cast to a pointer to the "base class". */
6459 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6460
6461 r->dtr = stop_reply_dtr;
6462
6463 return r;
6464 }
6465
6466 /* A client of notification Stop. */
6467
6468 struct notif_client notif_client_stop =
6469 {
6470 "Stop",
6471 "vStopped",
6472 remote_notif_stop_parse,
6473 remote_notif_stop_ack,
6474 remote_notif_stop_can_get_pending_events,
6475 remote_notif_stop_alloc_reply,
6476 REMOTE_NOTIF_STOP,
6477 };
6478
6479 /* A parameter to pass data in and out. */
6480
6481 struct queue_iter_param
6482 {
6483 void *input;
6484 struct stop_reply *output;
6485 };
6486
6487 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6488 the pid of the process that owns the threads we want to check, or
6489 -1 if we want to check all threads. */
6490
6491 static int
6492 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6493 ptid_t thread_ptid)
6494 {
6495 if (ws->kind == TARGET_WAITKIND_FORKED
6496 || ws->kind == TARGET_WAITKIND_VFORKED)
6497 {
6498 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6499 return 1;
6500 }
6501
6502 return 0;
6503 }
6504
6505 /* Return the thread's pending status used to determine whether the
6506 thread is a fork parent stopped at a fork event. */
6507
6508 static struct target_waitstatus *
6509 thread_pending_fork_status (struct thread_info *thread)
6510 {
6511 if (thread->suspend.waitstatus_pending_p)
6512 return &thread->suspend.waitstatus;
6513 else
6514 return &thread->pending_follow;
6515 }
6516
6517 /* Determine if THREAD is a pending fork parent thread. */
6518
6519 static int
6520 is_pending_fork_parent_thread (struct thread_info *thread)
6521 {
6522 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6523 int pid = -1;
6524
6525 return is_pending_fork_parent (ws, pid, thread->ptid);
6526 }
6527
6528 /* Check whether EVENT is a fork event, and if it is, remove the
6529 fork child from the context list passed in DATA. */
6530
6531 static int
6532 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6533 QUEUE_ITER (stop_reply_p) *iter,
6534 stop_reply_p event,
6535 void *data)
6536 {
6537 struct queue_iter_param *param = (struct queue_iter_param *) data;
6538 struct threads_listing_context *context
6539 = (struct threads_listing_context *) param->input;
6540
6541 if (event->ws.kind == TARGET_WAITKIND_FORKED
6542 || event->ws.kind == TARGET_WAITKIND_VFORKED
6543 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6544 threads_listing_context_remove (&event->ws, context);
6545
6546 return 1;
6547 }
6548
6549 /* If CONTEXT contains any fork child threads that have not been
6550 reported yet, remove them from the CONTEXT list. If such a
6551 thread exists it is because we are stopped at a fork catchpoint
6552 and have not yet called follow_fork, which will set up the
6553 host-side data structures for the new process. */
6554
6555 static void
6556 remove_new_fork_children (struct threads_listing_context *context)
6557 {
6558 struct thread_info * thread;
6559 int pid = -1;
6560 struct notif_client *notif = &notif_client_stop;
6561 struct queue_iter_param param;
6562
6563 /* For any threads stopped at a fork event, remove the corresponding
6564 fork child threads from the CONTEXT list. */
6565 ALL_NON_EXITED_THREADS (thread)
6566 {
6567 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6568
6569 if (is_pending_fork_parent (ws, pid, thread->ptid))
6570 {
6571 threads_listing_context_remove (ws, context);
6572 }
6573 }
6574
6575 /* Check for any pending fork events (not reported or processed yet)
6576 in process PID and remove those fork child threads from the
6577 CONTEXT list as well. */
6578 remote_notif_get_pending_events (notif);
6579 param.input = context;
6580 param.output = NULL;
6581 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6582 remove_child_of_pending_fork, &param);
6583 }
6584
6585 /* Check whether EVENT would prevent a global or process wildcard
6586 vCont action. */
6587
6588 static int
6589 check_pending_event_prevents_wildcard_vcont_callback
6590 (QUEUE (stop_reply_p) *q,
6591 QUEUE_ITER (stop_reply_p) *iter,
6592 stop_reply_p event,
6593 void *data)
6594 {
6595 struct inferior *inf;
6596 int *may_global_wildcard_vcont = (int *) data;
6597
6598 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6599 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6600 return 1;
6601
6602 if (event->ws.kind == TARGET_WAITKIND_FORKED
6603 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6604 *may_global_wildcard_vcont = 0;
6605
6606 inf = find_inferior_ptid (event->ptid);
6607
6608 /* This may be the first time we heard about this process.
6609 Regardless, we must not do a global wildcard resume, otherwise
6610 we'd resume this process too. */
6611 *may_global_wildcard_vcont = 0;
6612 if (inf != NULL)
6613 inf->priv->may_wildcard_vcont = 0;
6614
6615 return 1;
6616 }
6617
6618 /* Check whether any event pending in the vStopped queue would prevent
6619 a global or process wildcard vCont action. Clear
6620 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6621 and clear the event inferior's may_wildcard_vcont flag if we can't
6622 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6623
6624 static void
6625 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6626 {
6627 struct notif_client *notif = &notif_client_stop;
6628
6629 remote_notif_get_pending_events (notif);
6630 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6631 check_pending_event_prevents_wildcard_vcont_callback,
6632 may_global_wildcard);
6633 }
6634
6635 /* Remove stop replies in the queue if its pid is equal to the given
6636 inferior's pid. */
6637
6638 static int
6639 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6640 QUEUE_ITER (stop_reply_p) *iter,
6641 stop_reply_p event,
6642 void *data)
6643 {
6644 struct queue_iter_param *param = (struct queue_iter_param *) data;
6645 struct inferior *inf = (struct inferior *) param->input;
6646
6647 if (ptid_get_pid (event->ptid) == inf->pid)
6648 {
6649 stop_reply_xfree (event);
6650 QUEUE_remove_elem (stop_reply_p, q, iter);
6651 }
6652
6653 return 1;
6654 }
6655
6656 /* Discard all pending stop replies of inferior INF. */
6657
6658 static void
6659 discard_pending_stop_replies (struct inferior *inf)
6660 {
6661 struct queue_iter_param param;
6662 struct stop_reply *reply;
6663 struct remote_state *rs = get_remote_state ();
6664 struct remote_notif_state *rns = rs->notif_state;
6665
6666 /* This function can be notified when an inferior exists. When the
6667 target is not remote, the notification state is NULL. */
6668 if (rs->remote_desc == NULL)
6669 return;
6670
6671 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6672
6673 /* Discard the in-flight notification. */
6674 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6675 {
6676 stop_reply_xfree (reply);
6677 rns->pending_event[notif_client_stop.id] = NULL;
6678 }
6679
6680 param.input = inf;
6681 param.output = NULL;
6682 /* Discard the stop replies we have already pulled with
6683 vStopped. */
6684 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6685 remove_stop_reply_for_inferior, &param);
6686 }
6687
6688 /* If its remote state is equal to the given remote state,
6689 remove EVENT from the stop reply queue. */
6690
6691 static int
6692 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6693 QUEUE_ITER (stop_reply_p) *iter,
6694 stop_reply_p event,
6695 void *data)
6696 {
6697 struct queue_iter_param *param = (struct queue_iter_param *) data;
6698 struct remote_state *rs = (struct remote_state *) param->input;
6699
6700 if (event->rs == rs)
6701 {
6702 stop_reply_xfree (event);
6703 QUEUE_remove_elem (stop_reply_p, q, iter);
6704 }
6705
6706 return 1;
6707 }
6708
6709 /* Discard the stop replies for RS in stop_reply_queue. */
6710
6711 static void
6712 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6713 {
6714 struct queue_iter_param param;
6715
6716 param.input = rs;
6717 param.output = NULL;
6718 /* Discard the stop replies we have already pulled with
6719 vStopped. */
6720 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6721 remove_stop_reply_of_remote_state, &param);
6722 }
6723
6724 /* A parameter to pass data in and out. */
6725
6726 static int
6727 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6728 QUEUE_ITER (stop_reply_p) *iter,
6729 stop_reply_p event,
6730 void *data)
6731 {
6732 struct queue_iter_param *param = (struct queue_iter_param *) data;
6733 ptid_t *ptid = (ptid_t *) param->input;
6734
6735 if (ptid_match (event->ptid, *ptid))
6736 {
6737 param->output = event;
6738 QUEUE_remove_elem (stop_reply_p, q, iter);
6739 return 0;
6740 }
6741
6742 return 1;
6743 }
6744
6745 /* Remove the first reply in 'stop_reply_queue' which matches
6746 PTID. */
6747
6748 static struct stop_reply *
6749 remote_notif_remove_queued_reply (ptid_t ptid)
6750 {
6751 struct queue_iter_param param;
6752
6753 param.input = &ptid;
6754 param.output = NULL;
6755
6756 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6757 remote_notif_remove_once_on_match, &param);
6758 if (notif_debug)
6759 fprintf_unfiltered (gdb_stdlog,
6760 "notif: discard queued event: 'Stop' in %s\n",
6761 target_pid_to_str (ptid));
6762
6763 return param.output;
6764 }
6765
6766 /* Look for a queued stop reply belonging to PTID. If one is found,
6767 remove it from the queue, and return it. Returns NULL if none is
6768 found. If there are still queued events left to process, tell the
6769 event loop to get back to target_wait soon. */
6770
6771 static struct stop_reply *
6772 queued_stop_reply (ptid_t ptid)
6773 {
6774 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6775
6776 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6777 /* There's still at least an event left. */
6778 mark_async_event_handler (remote_async_inferior_event_token);
6779
6780 return r;
6781 }
6782
6783 /* Push a fully parsed stop reply in the stop reply queue. Since we
6784 know that we now have at least one queued event left to pass to the
6785 core side, tell the event loop to get back to target_wait soon. */
6786
6787 static void
6788 push_stop_reply (struct stop_reply *new_event)
6789 {
6790 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6791
6792 if (notif_debug)
6793 fprintf_unfiltered (gdb_stdlog,
6794 "notif: push 'Stop' %s to queue %d\n",
6795 target_pid_to_str (new_event->ptid),
6796 QUEUE_length (stop_reply_p,
6797 stop_reply_queue));
6798
6799 mark_async_event_handler (remote_async_inferior_event_token);
6800 }
6801
6802 static int
6803 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6804 QUEUE_ITER (stop_reply_p) *iter,
6805 struct stop_reply *event,
6806 void *data)
6807 {
6808 ptid_t *ptid = (ptid_t *) data;
6809
6810 return !(ptid_equal (*ptid, event->ptid)
6811 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6812 }
6813
6814 /* Returns true if we have a stop reply for PTID. */
6815
6816 static int
6817 peek_stop_reply (ptid_t ptid)
6818 {
6819 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6820 stop_reply_match_ptid_and_ws, &ptid);
6821 }
6822
6823 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6824 starting with P and ending with PEND matches PREFIX. */
6825
6826 static int
6827 strprefix (const char *p, const char *pend, const char *prefix)
6828 {
6829 for ( ; p < pend; p++, prefix++)
6830 if (*p != *prefix)
6831 return 0;
6832 return *prefix == '\0';
6833 }
6834
6835 /* Parse the stop reply in BUF. Either the function succeeds, and the
6836 result is stored in EVENT, or throws an error. */
6837
6838 static void
6839 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6840 {
6841 struct remote_arch_state *rsa = get_remote_arch_state ();
6842 ULONGEST addr;
6843 char *p;
6844 int skipregs = 0;
6845
6846 event->ptid = null_ptid;
6847 event->rs = get_remote_state ();
6848 event->ws.kind = TARGET_WAITKIND_IGNORE;
6849 event->ws.value.integer = 0;
6850 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6851 event->regcache = NULL;
6852 event->core = -1;
6853
6854 switch (buf[0])
6855 {
6856 case 'T': /* Status with PC, SP, FP, ... */
6857 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6858 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6859 ss = signal number
6860 n... = register number
6861 r... = register contents
6862 */
6863
6864 p = &buf[3]; /* after Txx */
6865 while (*p)
6866 {
6867 char *p1;
6868 int fieldsize;
6869
6870 p1 = strchr (p, ':');
6871 if (p1 == NULL)
6872 error (_("Malformed packet(a) (missing colon): %s\n\
6873 Packet: '%s'\n"),
6874 p, buf);
6875 if (p == p1)
6876 error (_("Malformed packet(a) (missing register number): %s\n\
6877 Packet: '%s'\n"),
6878 p, buf);
6879
6880 /* Some "registers" are actually extended stop information.
6881 Note if you're adding a new entry here: GDB 7.9 and
6882 earlier assume that all register "numbers" that start
6883 with an hex digit are real register numbers. Make sure
6884 the server only sends such a packet if it knows the
6885 client understands it. */
6886
6887 if (strprefix (p, p1, "thread"))
6888 event->ptid = read_ptid (++p1, &p);
6889 else if (strprefix (p, p1, "syscall_entry"))
6890 {
6891 ULONGEST sysno;
6892
6893 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6894 p = unpack_varlen_hex (++p1, &sysno);
6895 event->ws.value.syscall_number = (int) sysno;
6896 }
6897 else if (strprefix (p, p1, "syscall_return"))
6898 {
6899 ULONGEST sysno;
6900
6901 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6902 p = unpack_varlen_hex (++p1, &sysno);
6903 event->ws.value.syscall_number = (int) sysno;
6904 }
6905 else if (strprefix (p, p1, "watch")
6906 || strprefix (p, p1, "rwatch")
6907 || strprefix (p, p1, "awatch"))
6908 {
6909 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6910 p = unpack_varlen_hex (++p1, &addr);
6911 event->watch_data_address = (CORE_ADDR) addr;
6912 }
6913 else if (strprefix (p, p1, "swbreak"))
6914 {
6915 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6916
6917 /* Make sure the stub doesn't forget to indicate support
6918 with qSupported. */
6919 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6920 error (_("Unexpected swbreak stop reason"));
6921
6922 /* The value part is documented as "must be empty",
6923 though we ignore it, in case we ever decide to make
6924 use of it in a backward compatible way. */
6925 p = strchrnul (p1 + 1, ';');
6926 }
6927 else if (strprefix (p, p1, "hwbreak"))
6928 {
6929 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6930
6931 /* Make sure the stub doesn't forget to indicate support
6932 with qSupported. */
6933 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6934 error (_("Unexpected hwbreak stop reason"));
6935
6936 /* See above. */
6937 p = strchrnul (p1 + 1, ';');
6938 }
6939 else if (strprefix (p, p1, "library"))
6940 {
6941 event->ws.kind = TARGET_WAITKIND_LOADED;
6942 p = strchrnul (p1 + 1, ';');
6943 }
6944 else if (strprefix (p, p1, "replaylog"))
6945 {
6946 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6947 /* p1 will indicate "begin" or "end", but it makes
6948 no difference for now, so ignore it. */
6949 p = strchrnul (p1 + 1, ';');
6950 }
6951 else if (strprefix (p, p1, "core"))
6952 {
6953 ULONGEST c;
6954
6955 p = unpack_varlen_hex (++p1, &c);
6956 event->core = c;
6957 }
6958 else if (strprefix (p, p1, "fork"))
6959 {
6960 event->ws.value.related_pid = read_ptid (++p1, &p);
6961 event->ws.kind = TARGET_WAITKIND_FORKED;
6962 }
6963 else if (strprefix (p, p1, "vfork"))
6964 {
6965 event->ws.value.related_pid = read_ptid (++p1, &p);
6966 event->ws.kind = TARGET_WAITKIND_VFORKED;
6967 }
6968 else if (strprefix (p, p1, "vforkdone"))
6969 {
6970 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6971 p = strchrnul (p1 + 1, ';');
6972 }
6973 else if (strprefix (p, p1, "exec"))
6974 {
6975 ULONGEST ignored;
6976 char pathname[PATH_MAX];
6977 int pathlen;
6978
6979 /* Determine the length of the execd pathname. */
6980 p = unpack_varlen_hex (++p1, &ignored);
6981 pathlen = (p - p1) / 2;
6982
6983 /* Save the pathname for event reporting and for
6984 the next run command. */
6985 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6986 pathname[pathlen] = '\0';
6987
6988 /* This is freed during event handling. */
6989 event->ws.value.execd_pathname = xstrdup (pathname);
6990 event->ws.kind = TARGET_WAITKIND_EXECD;
6991
6992 /* Skip the registers included in this packet, since
6993 they may be for an architecture different from the
6994 one used by the original program. */
6995 skipregs = 1;
6996 }
6997 else if (strprefix (p, p1, "create"))
6998 {
6999 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7000 p = strchrnul (p1 + 1, ';');
7001 }
7002 else
7003 {
7004 ULONGEST pnum;
7005 char *p_temp;
7006
7007 if (skipregs)
7008 {
7009 p = strchrnul (p1 + 1, ';');
7010 p++;
7011 continue;
7012 }
7013
7014 /* Maybe a real ``P'' register number. */
7015 p_temp = unpack_varlen_hex (p, &pnum);
7016 /* If the first invalid character is the colon, we got a
7017 register number. Otherwise, it's an unknown stop
7018 reason. */
7019 if (p_temp == p1)
7020 {
7021 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
7022 cached_reg_t cached_reg;
7023 struct gdbarch *gdbarch = target_gdbarch ();
7024
7025 if (reg == NULL)
7026 error (_("Remote sent bad register number %s: %s\n\
7027 Packet: '%s'\n"),
7028 hex_string (pnum), p, buf);
7029
7030 cached_reg.num = reg->regnum;
7031 cached_reg.data = (gdb_byte *)
7032 xmalloc (register_size (gdbarch, reg->regnum));
7033
7034 p = p1 + 1;
7035 fieldsize = hex2bin (p, cached_reg.data,
7036 register_size (gdbarch, reg->regnum));
7037 p += 2 * fieldsize;
7038 if (fieldsize < register_size (gdbarch, reg->regnum))
7039 warning (_("Remote reply is too short: %s"), buf);
7040
7041 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7042 }
7043 else
7044 {
7045 /* Not a number. Silently skip unknown optional
7046 info. */
7047 p = strchrnul (p1 + 1, ';');
7048 }
7049 }
7050
7051 if (*p != ';')
7052 error (_("Remote register badly formatted: %s\nhere: %s"),
7053 buf, p);
7054 ++p;
7055 }
7056
7057 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7058 break;
7059
7060 /* fall through */
7061 case 'S': /* Old style status, just signal only. */
7062 {
7063 int sig;
7064
7065 event->ws.kind = TARGET_WAITKIND_STOPPED;
7066 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7067 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7068 event->ws.value.sig = (enum gdb_signal) sig;
7069 else
7070 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7071 }
7072 break;
7073 case 'w': /* Thread exited. */
7074 {
7075 char *p;
7076 ULONGEST value;
7077
7078 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7079 p = unpack_varlen_hex (&buf[1], &value);
7080 event->ws.value.integer = value;
7081 if (*p != ';')
7082 error (_("stop reply packet badly formatted: %s"), buf);
7083 event->ptid = read_ptid (++p, NULL);
7084 break;
7085 }
7086 case 'W': /* Target exited. */
7087 case 'X':
7088 {
7089 char *p;
7090 int pid;
7091 ULONGEST value;
7092
7093 /* GDB used to accept only 2 hex chars here. Stubs should
7094 only send more if they detect GDB supports multi-process
7095 support. */
7096 p = unpack_varlen_hex (&buf[1], &value);
7097
7098 if (buf[0] == 'W')
7099 {
7100 /* The remote process exited. */
7101 event->ws.kind = TARGET_WAITKIND_EXITED;
7102 event->ws.value.integer = value;
7103 }
7104 else
7105 {
7106 /* The remote process exited with a signal. */
7107 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7108 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7109 event->ws.value.sig = (enum gdb_signal) value;
7110 else
7111 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7112 }
7113
7114 /* If no process is specified, assume inferior_ptid. */
7115 pid = ptid_get_pid (inferior_ptid);
7116 if (*p == '\0')
7117 ;
7118 else if (*p == ';')
7119 {
7120 p++;
7121
7122 if (*p == '\0')
7123 ;
7124 else if (startswith (p, "process:"))
7125 {
7126 ULONGEST upid;
7127
7128 p += sizeof ("process:") - 1;
7129 unpack_varlen_hex (p, &upid);
7130 pid = upid;
7131 }
7132 else
7133 error (_("unknown stop reply packet: %s"), buf);
7134 }
7135 else
7136 error (_("unknown stop reply packet: %s"), buf);
7137 event->ptid = pid_to_ptid (pid);
7138 }
7139 break;
7140 case 'N':
7141 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7142 event->ptid = minus_one_ptid;
7143 break;
7144 }
7145
7146 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7147 error (_("No process or thread specified in stop reply: %s"), buf);
7148 }
7149
7150 /* When the stub wants to tell GDB about a new notification reply, it
7151 sends a notification (%Stop, for example). Those can come it at
7152 any time, hence, we have to make sure that any pending
7153 putpkt/getpkt sequence we're making is finished, before querying
7154 the stub for more events with the corresponding ack command
7155 (vStopped, for example). E.g., if we started a vStopped sequence
7156 immediately upon receiving the notification, something like this
7157 could happen:
7158
7159 1.1) --> Hg 1
7160 1.2) <-- OK
7161 1.3) --> g
7162 1.4) <-- %Stop
7163 1.5) --> vStopped
7164 1.6) <-- (registers reply to step #1.3)
7165
7166 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7167 query.
7168
7169 To solve this, whenever we parse a %Stop notification successfully,
7170 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7171 doing whatever we were doing:
7172
7173 2.1) --> Hg 1
7174 2.2) <-- OK
7175 2.3) --> g
7176 2.4) <-- %Stop
7177 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7178 2.5) <-- (registers reply to step #2.3)
7179
7180 Eventualy after step #2.5, we return to the event loop, which
7181 notices there's an event on the
7182 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7183 associated callback --- the function below. At this point, we're
7184 always safe to start a vStopped sequence. :
7185
7186 2.6) --> vStopped
7187 2.7) <-- T05 thread:2
7188 2.8) --> vStopped
7189 2.9) --> OK
7190 */
7191
7192 void
7193 remote_notif_get_pending_events (struct notif_client *nc)
7194 {
7195 struct remote_state *rs = get_remote_state ();
7196
7197 if (rs->notif_state->pending_event[nc->id] != NULL)
7198 {
7199 if (notif_debug)
7200 fprintf_unfiltered (gdb_stdlog,
7201 "notif: process: '%s' ack pending event\n",
7202 nc->name);
7203
7204 /* acknowledge */
7205 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7206 rs->notif_state->pending_event[nc->id] = NULL;
7207
7208 while (1)
7209 {
7210 getpkt (&rs->buf, &rs->buf_size, 0);
7211 if (strcmp (rs->buf, "OK") == 0)
7212 break;
7213 else
7214 remote_notif_ack (nc, rs->buf);
7215 }
7216 }
7217 else
7218 {
7219 if (notif_debug)
7220 fprintf_unfiltered (gdb_stdlog,
7221 "notif: process: '%s' no pending reply\n",
7222 nc->name);
7223 }
7224 }
7225
7226 /* Called when it is decided that STOP_REPLY holds the info of the
7227 event that is to be returned to the core. This function always
7228 destroys STOP_REPLY. */
7229
7230 static ptid_t
7231 process_stop_reply (struct stop_reply *stop_reply,
7232 struct target_waitstatus *status)
7233 {
7234 ptid_t ptid;
7235
7236 *status = stop_reply->ws;
7237 ptid = stop_reply->ptid;
7238
7239 /* If no thread/process was reported by the stub, assume the current
7240 inferior. */
7241 if (ptid_equal (ptid, null_ptid))
7242 ptid = inferior_ptid;
7243
7244 if (status->kind != TARGET_WAITKIND_EXITED
7245 && status->kind != TARGET_WAITKIND_SIGNALLED
7246 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7247 {
7248 struct private_thread_info *remote_thr;
7249
7250 /* Expedited registers. */
7251 if (stop_reply->regcache)
7252 {
7253 struct regcache *regcache
7254 = get_thread_arch_regcache (ptid, target_gdbarch ());
7255 cached_reg_t *reg;
7256 int ix;
7257
7258 for (ix = 0;
7259 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7260 ix++)
7261 {
7262 regcache_raw_supply (regcache, reg->num, reg->data);
7263 xfree (reg->data);
7264 }
7265
7266 VEC_free (cached_reg_t, stop_reply->regcache);
7267 }
7268
7269 remote_notice_new_inferior (ptid, 0);
7270 remote_thr = get_private_info_ptid (ptid);
7271 remote_thr->core = stop_reply->core;
7272 remote_thr->stop_reason = stop_reply->stop_reason;
7273 remote_thr->watch_data_address = stop_reply->watch_data_address;
7274 remote_thr->vcont_resumed = 0;
7275 }
7276
7277 stop_reply_xfree (stop_reply);
7278 return ptid;
7279 }
7280
7281 /* The non-stop mode version of target_wait. */
7282
7283 static ptid_t
7284 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7285 {
7286 struct remote_state *rs = get_remote_state ();
7287 struct stop_reply *stop_reply;
7288 int ret;
7289 int is_notif = 0;
7290
7291 /* If in non-stop mode, get out of getpkt even if a
7292 notification is received. */
7293
7294 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7295 0 /* forever */, &is_notif);
7296 while (1)
7297 {
7298 if (ret != -1 && !is_notif)
7299 switch (rs->buf[0])
7300 {
7301 case 'E': /* Error of some sort. */
7302 /* We're out of sync with the target now. Did it continue
7303 or not? We can't tell which thread it was in non-stop,
7304 so just ignore this. */
7305 warning (_("Remote failure reply: %s"), rs->buf);
7306 break;
7307 case 'O': /* Console output. */
7308 remote_console_output (rs->buf + 1);
7309 break;
7310 default:
7311 warning (_("Invalid remote reply: %s"), rs->buf);
7312 break;
7313 }
7314
7315 /* Acknowledge a pending stop reply that may have arrived in the
7316 mean time. */
7317 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7318 remote_notif_get_pending_events (&notif_client_stop);
7319
7320 /* If indeed we noticed a stop reply, we're done. */
7321 stop_reply = queued_stop_reply (ptid);
7322 if (stop_reply != NULL)
7323 return process_stop_reply (stop_reply, status);
7324
7325 /* Still no event. If we're just polling for an event, then
7326 return to the event loop. */
7327 if (options & TARGET_WNOHANG)
7328 {
7329 status->kind = TARGET_WAITKIND_IGNORE;
7330 return minus_one_ptid;
7331 }
7332
7333 /* Otherwise do a blocking wait. */
7334 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7335 1 /* forever */, &is_notif);
7336 }
7337 }
7338
7339 /* Wait until the remote machine stops, then return, storing status in
7340 STATUS just as `wait' would. */
7341
7342 static ptid_t
7343 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7344 {
7345 struct remote_state *rs = get_remote_state ();
7346 ptid_t event_ptid = null_ptid;
7347 char *buf;
7348 struct stop_reply *stop_reply;
7349
7350 again:
7351
7352 status->kind = TARGET_WAITKIND_IGNORE;
7353 status->value.integer = 0;
7354
7355 stop_reply = queued_stop_reply (ptid);
7356 if (stop_reply != NULL)
7357 return process_stop_reply (stop_reply, status);
7358
7359 if (rs->cached_wait_status)
7360 /* Use the cached wait status, but only once. */
7361 rs->cached_wait_status = 0;
7362 else
7363 {
7364 int ret;
7365 int is_notif;
7366 int forever = ((options & TARGET_WNOHANG) == 0
7367 && wait_forever_enabled_p);
7368
7369 if (!rs->waiting_for_stop_reply)
7370 {
7371 status->kind = TARGET_WAITKIND_NO_RESUMED;
7372 return minus_one_ptid;
7373 }
7374
7375 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7376 _never_ wait for ever -> test on target_is_async_p().
7377 However, before we do that we need to ensure that the caller
7378 knows how to take the target into/out of async mode. */
7379 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7380 forever, &is_notif);
7381
7382 /* GDB gets a notification. Return to core as this event is
7383 not interesting. */
7384 if (ret != -1 && is_notif)
7385 return minus_one_ptid;
7386
7387 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7388 return minus_one_ptid;
7389 }
7390
7391 buf = rs->buf;
7392
7393 /* Assume that the target has acknowledged Ctrl-C unless we receive
7394 an 'F' or 'O' packet. */
7395 if (buf[0] != 'F' && buf[0] != 'O')
7396 rs->ctrlc_pending_p = 0;
7397
7398 switch (buf[0])
7399 {
7400 case 'E': /* Error of some sort. */
7401 /* We're out of sync with the target now. Did it continue or
7402 not? Not is more likely, so report a stop. */
7403 rs->waiting_for_stop_reply = 0;
7404
7405 warning (_("Remote failure reply: %s"), buf);
7406 status->kind = TARGET_WAITKIND_STOPPED;
7407 status->value.sig = GDB_SIGNAL_0;
7408 break;
7409 case 'F': /* File-I/O request. */
7410 /* GDB may access the inferior memory while handling the File-I/O
7411 request, but we don't want GDB accessing memory while waiting
7412 for a stop reply. See the comments in putpkt_binary. Set
7413 waiting_for_stop_reply to 0 temporarily. */
7414 rs->waiting_for_stop_reply = 0;
7415 remote_fileio_request (buf, rs->ctrlc_pending_p);
7416 rs->ctrlc_pending_p = 0;
7417 /* GDB handled the File-I/O request, and the target is running
7418 again. Keep waiting for events. */
7419 rs->waiting_for_stop_reply = 1;
7420 break;
7421 case 'N': case 'T': case 'S': case 'X': case 'W':
7422 {
7423 struct stop_reply *stop_reply;
7424
7425 /* There is a stop reply to handle. */
7426 rs->waiting_for_stop_reply = 0;
7427
7428 stop_reply
7429 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7430 rs->buf);
7431
7432 event_ptid = process_stop_reply (stop_reply, status);
7433 break;
7434 }
7435 case 'O': /* Console output. */
7436 remote_console_output (buf + 1);
7437 break;
7438 case '\0':
7439 if (rs->last_sent_signal != GDB_SIGNAL_0)
7440 {
7441 /* Zero length reply means that we tried 'S' or 'C' and the
7442 remote system doesn't support it. */
7443 target_terminal::ours_for_output ();
7444 printf_filtered
7445 ("Can't send signals to this remote system. %s not sent.\n",
7446 gdb_signal_to_name (rs->last_sent_signal));
7447 rs->last_sent_signal = GDB_SIGNAL_0;
7448 target_terminal::inferior ();
7449
7450 strcpy (buf, rs->last_sent_step ? "s" : "c");
7451 putpkt (buf);
7452 break;
7453 }
7454 /* else fallthrough */
7455 default:
7456 warning (_("Invalid remote reply: %s"), buf);
7457 break;
7458 }
7459
7460 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7461 return minus_one_ptid;
7462 else if (status->kind == TARGET_WAITKIND_IGNORE)
7463 {
7464 /* Nothing interesting happened. If we're doing a non-blocking
7465 poll, we're done. Otherwise, go back to waiting. */
7466 if (options & TARGET_WNOHANG)
7467 return minus_one_ptid;
7468 else
7469 goto again;
7470 }
7471 else if (status->kind != TARGET_WAITKIND_EXITED
7472 && status->kind != TARGET_WAITKIND_SIGNALLED)
7473 {
7474 if (!ptid_equal (event_ptid, null_ptid))
7475 record_currthread (rs, event_ptid);
7476 else
7477 event_ptid = inferior_ptid;
7478 }
7479 else
7480 /* A process exit. Invalidate our notion of current thread. */
7481 record_currthread (rs, minus_one_ptid);
7482
7483 return event_ptid;
7484 }
7485
7486 /* Wait until the remote machine stops, then return, storing status in
7487 STATUS just as `wait' would. */
7488
7489 static ptid_t
7490 remote_wait (struct target_ops *ops,
7491 ptid_t ptid, struct target_waitstatus *status, int options)
7492 {
7493 ptid_t event_ptid;
7494
7495 if (target_is_non_stop_p ())
7496 event_ptid = remote_wait_ns (ptid, status, options);
7497 else
7498 event_ptid = remote_wait_as (ptid, status, options);
7499
7500 if (target_is_async_p ())
7501 {
7502 /* If there are are events left in the queue tell the event loop
7503 to return here. */
7504 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7505 mark_async_event_handler (remote_async_inferior_event_token);
7506 }
7507
7508 return event_ptid;
7509 }
7510
7511 /* Fetch a single register using a 'p' packet. */
7512
7513 static int
7514 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7515 {
7516 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7517 struct remote_state *rs = get_remote_state ();
7518 char *buf, *p;
7519 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7520 int i;
7521
7522 if (packet_support (PACKET_p) == PACKET_DISABLE)
7523 return 0;
7524
7525 if (reg->pnum == -1)
7526 return 0;
7527
7528 p = rs->buf;
7529 *p++ = 'p';
7530 p += hexnumstr (p, reg->pnum);
7531 *p++ = '\0';
7532 putpkt (rs->buf);
7533 getpkt (&rs->buf, &rs->buf_size, 0);
7534
7535 buf = rs->buf;
7536
7537 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7538 {
7539 case PACKET_OK:
7540 break;
7541 case PACKET_UNKNOWN:
7542 return 0;
7543 case PACKET_ERROR:
7544 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7545 gdbarch_register_name (get_regcache_arch (regcache),
7546 reg->regnum),
7547 buf);
7548 }
7549
7550 /* If this register is unfetchable, tell the regcache. */
7551 if (buf[0] == 'x')
7552 {
7553 regcache_raw_supply (regcache, reg->regnum, NULL);
7554 return 1;
7555 }
7556
7557 /* Otherwise, parse and supply the value. */
7558 p = buf;
7559 i = 0;
7560 while (p[0] != 0)
7561 {
7562 if (p[1] == 0)
7563 error (_("fetch_register_using_p: early buf termination"));
7564
7565 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7566 p += 2;
7567 }
7568 regcache_raw_supply (regcache, reg->regnum, regp);
7569 return 1;
7570 }
7571
7572 /* Fetch the registers included in the target's 'g' packet. */
7573
7574 static int
7575 send_g_packet (void)
7576 {
7577 struct remote_state *rs = get_remote_state ();
7578 int buf_len;
7579
7580 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7581 remote_send (&rs->buf, &rs->buf_size);
7582
7583 /* We can get out of synch in various cases. If the first character
7584 in the buffer is not a hex character, assume that has happened
7585 and try to fetch another packet to read. */
7586 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7587 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7588 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7589 && rs->buf[0] != 'x') /* New: unavailable register value. */
7590 {
7591 if (remote_debug)
7592 fprintf_unfiltered (gdb_stdlog,
7593 "Bad register packet; fetching a new packet\n");
7594 getpkt (&rs->buf, &rs->buf_size, 0);
7595 }
7596
7597 buf_len = strlen (rs->buf);
7598
7599 /* Sanity check the received packet. */
7600 if (buf_len % 2 != 0)
7601 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7602
7603 return buf_len / 2;
7604 }
7605
7606 static void
7607 process_g_packet (struct regcache *regcache)
7608 {
7609 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7610 struct remote_state *rs = get_remote_state ();
7611 struct remote_arch_state *rsa = get_remote_arch_state ();
7612 int i, buf_len;
7613 char *p;
7614 char *regs;
7615
7616 buf_len = strlen (rs->buf);
7617
7618 /* Further sanity checks, with knowledge of the architecture. */
7619 if (buf_len > 2 * rsa->sizeof_g_packet)
7620 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7621 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7622
7623 /* Save the size of the packet sent to us by the target. It is used
7624 as a heuristic when determining the max size of packets that the
7625 target can safely receive. */
7626 if (rsa->actual_register_packet_size == 0)
7627 rsa->actual_register_packet_size = buf_len;
7628
7629 /* If this is smaller than we guessed the 'g' packet would be,
7630 update our records. A 'g' reply that doesn't include a register's
7631 value implies either that the register is not available, or that
7632 the 'p' packet must be used. */
7633 if (buf_len < 2 * rsa->sizeof_g_packet)
7634 {
7635 long sizeof_g_packet = buf_len / 2;
7636
7637 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7638 {
7639 long offset = rsa->regs[i].offset;
7640 long reg_size = register_size (gdbarch, i);
7641
7642 if (rsa->regs[i].pnum == -1)
7643 continue;
7644
7645 if (offset >= sizeof_g_packet)
7646 rsa->regs[i].in_g_packet = 0;
7647 else if (offset + reg_size > sizeof_g_packet)
7648 error (_("Truncated register %d in remote 'g' packet"), i);
7649 else
7650 rsa->regs[i].in_g_packet = 1;
7651 }
7652
7653 /* Looks valid enough, we can assume this is the correct length
7654 for a 'g' packet. It's important not to adjust
7655 rsa->sizeof_g_packet if we have truncated registers otherwise
7656 this "if" won't be run the next time the method is called
7657 with a packet of the same size and one of the internal errors
7658 below will trigger instead. */
7659 rsa->sizeof_g_packet = sizeof_g_packet;
7660 }
7661
7662 regs = (char *) alloca (rsa->sizeof_g_packet);
7663
7664 /* Unimplemented registers read as all bits zero. */
7665 memset (regs, 0, rsa->sizeof_g_packet);
7666
7667 /* Reply describes registers byte by byte, each byte encoded as two
7668 hex characters. Suck them all up, then supply them to the
7669 register cacheing/storage mechanism. */
7670
7671 p = rs->buf;
7672 for (i = 0; i < rsa->sizeof_g_packet; i++)
7673 {
7674 if (p[0] == 0 || p[1] == 0)
7675 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7676 internal_error (__FILE__, __LINE__,
7677 _("unexpected end of 'g' packet reply"));
7678
7679 if (p[0] == 'x' && p[1] == 'x')
7680 regs[i] = 0; /* 'x' */
7681 else
7682 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7683 p += 2;
7684 }
7685
7686 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7687 {
7688 struct packet_reg *r = &rsa->regs[i];
7689 long reg_size = register_size (gdbarch, i);
7690
7691 if (r->in_g_packet)
7692 {
7693 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7694 /* This shouldn't happen - we adjusted in_g_packet above. */
7695 internal_error (__FILE__, __LINE__,
7696 _("unexpected end of 'g' packet reply"));
7697 else if (rs->buf[r->offset * 2] == 'x')
7698 {
7699 gdb_assert (r->offset * 2 < strlen (rs->buf));
7700 /* The register isn't available, mark it as such (at
7701 the same time setting the value to zero). */
7702 regcache_raw_supply (regcache, r->regnum, NULL);
7703 }
7704 else
7705 regcache_raw_supply (regcache, r->regnum,
7706 regs + r->offset);
7707 }
7708 }
7709 }
7710
7711 static void
7712 fetch_registers_using_g (struct regcache *regcache)
7713 {
7714 send_g_packet ();
7715 process_g_packet (regcache);
7716 }
7717
7718 /* Make the remote selected traceframe match GDB's selected
7719 traceframe. */
7720
7721 static void
7722 set_remote_traceframe (void)
7723 {
7724 int newnum;
7725 struct remote_state *rs = get_remote_state ();
7726
7727 if (rs->remote_traceframe_number == get_traceframe_number ())
7728 return;
7729
7730 /* Avoid recursion, remote_trace_find calls us again. */
7731 rs->remote_traceframe_number = get_traceframe_number ();
7732
7733 newnum = target_trace_find (tfind_number,
7734 get_traceframe_number (), 0, 0, NULL);
7735
7736 /* Should not happen. If it does, all bets are off. */
7737 if (newnum != get_traceframe_number ())
7738 warning (_("could not set remote traceframe"));
7739 }
7740
7741 static void
7742 remote_fetch_registers (struct target_ops *ops,
7743 struct regcache *regcache, int regnum)
7744 {
7745 struct remote_arch_state *rsa = get_remote_arch_state ();
7746 int i;
7747
7748 set_remote_traceframe ();
7749 set_general_thread (regcache_get_ptid (regcache));
7750
7751 if (regnum >= 0)
7752 {
7753 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7754
7755 gdb_assert (reg != NULL);
7756
7757 /* If this register might be in the 'g' packet, try that first -
7758 we are likely to read more than one register. If this is the
7759 first 'g' packet, we might be overly optimistic about its
7760 contents, so fall back to 'p'. */
7761 if (reg->in_g_packet)
7762 {
7763 fetch_registers_using_g (regcache);
7764 if (reg->in_g_packet)
7765 return;
7766 }
7767
7768 if (fetch_register_using_p (regcache, reg))
7769 return;
7770
7771 /* This register is not available. */
7772 regcache_raw_supply (regcache, reg->regnum, NULL);
7773
7774 return;
7775 }
7776
7777 fetch_registers_using_g (regcache);
7778
7779 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7780 if (!rsa->regs[i].in_g_packet)
7781 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7782 {
7783 /* This register is not available. */
7784 regcache_raw_supply (regcache, i, NULL);
7785 }
7786 }
7787
7788 /* Prepare to store registers. Since we may send them all (using a
7789 'G' request), we have to read out the ones we don't want to change
7790 first. */
7791
7792 static void
7793 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7794 {
7795 struct remote_arch_state *rsa = get_remote_arch_state ();
7796 int i;
7797
7798 /* Make sure the entire registers array is valid. */
7799 switch (packet_support (PACKET_P))
7800 {
7801 case PACKET_DISABLE:
7802 case PACKET_SUPPORT_UNKNOWN:
7803 /* Make sure all the necessary registers are cached. */
7804 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7805 if (rsa->regs[i].in_g_packet)
7806 regcache_raw_update (regcache, rsa->regs[i].regnum);
7807 break;
7808 case PACKET_ENABLE:
7809 break;
7810 }
7811 }
7812
7813 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7814 packet was not recognized. */
7815
7816 static int
7817 store_register_using_P (const struct regcache *regcache,
7818 struct packet_reg *reg)
7819 {
7820 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7821 struct remote_state *rs = get_remote_state ();
7822 /* Try storing a single register. */
7823 char *buf = rs->buf;
7824 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7825 char *p;
7826
7827 if (packet_support (PACKET_P) == PACKET_DISABLE)
7828 return 0;
7829
7830 if (reg->pnum == -1)
7831 return 0;
7832
7833 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7834 p = buf + strlen (buf);
7835 regcache_raw_collect (regcache, reg->regnum, regp);
7836 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7837 putpkt (rs->buf);
7838 getpkt (&rs->buf, &rs->buf_size, 0);
7839
7840 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7841 {
7842 case PACKET_OK:
7843 return 1;
7844 case PACKET_ERROR:
7845 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7846 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7847 case PACKET_UNKNOWN:
7848 return 0;
7849 default:
7850 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7851 }
7852 }
7853
7854 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7855 contents of the register cache buffer. FIXME: ignores errors. */
7856
7857 static void
7858 store_registers_using_G (const struct regcache *regcache)
7859 {
7860 struct remote_state *rs = get_remote_state ();
7861 struct remote_arch_state *rsa = get_remote_arch_state ();
7862 gdb_byte *regs;
7863 char *p;
7864
7865 /* Extract all the registers in the regcache copying them into a
7866 local buffer. */
7867 {
7868 int i;
7869
7870 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7871 memset (regs, 0, rsa->sizeof_g_packet);
7872 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7873 {
7874 struct packet_reg *r = &rsa->regs[i];
7875
7876 if (r->in_g_packet)
7877 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7878 }
7879 }
7880
7881 /* Command describes registers byte by byte,
7882 each byte encoded as two hex characters. */
7883 p = rs->buf;
7884 *p++ = 'G';
7885 bin2hex (regs, p, rsa->sizeof_g_packet);
7886 putpkt (rs->buf);
7887 getpkt (&rs->buf, &rs->buf_size, 0);
7888 if (packet_check_result (rs->buf) == PACKET_ERROR)
7889 error (_("Could not write registers; remote failure reply '%s'"),
7890 rs->buf);
7891 }
7892
7893 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7894 of the register cache buffer. FIXME: ignores errors. */
7895
7896 static void
7897 remote_store_registers (struct target_ops *ops,
7898 struct regcache *regcache, int regnum)
7899 {
7900 struct remote_arch_state *rsa = get_remote_arch_state ();
7901 int i;
7902
7903 set_remote_traceframe ();
7904 set_general_thread (regcache_get_ptid (regcache));
7905
7906 if (regnum >= 0)
7907 {
7908 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7909
7910 gdb_assert (reg != NULL);
7911
7912 /* Always prefer to store registers using the 'P' packet if
7913 possible; we often change only a small number of registers.
7914 Sometimes we change a larger number; we'd need help from a
7915 higher layer to know to use 'G'. */
7916 if (store_register_using_P (regcache, reg))
7917 return;
7918
7919 /* For now, don't complain if we have no way to write the
7920 register. GDB loses track of unavailable registers too
7921 easily. Some day, this may be an error. We don't have
7922 any way to read the register, either... */
7923 if (!reg->in_g_packet)
7924 return;
7925
7926 store_registers_using_G (regcache);
7927 return;
7928 }
7929
7930 store_registers_using_G (regcache);
7931
7932 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7933 if (!rsa->regs[i].in_g_packet)
7934 if (!store_register_using_P (regcache, &rsa->regs[i]))
7935 /* See above for why we do not issue an error here. */
7936 continue;
7937 }
7938 \f
7939
7940 /* Return the number of hex digits in num. */
7941
7942 static int
7943 hexnumlen (ULONGEST num)
7944 {
7945 int i;
7946
7947 for (i = 0; num != 0; i++)
7948 num >>= 4;
7949
7950 return std::max (i, 1);
7951 }
7952
7953 /* Set BUF to the minimum number of hex digits representing NUM. */
7954
7955 static int
7956 hexnumstr (char *buf, ULONGEST num)
7957 {
7958 int len = hexnumlen (num);
7959
7960 return hexnumnstr (buf, num, len);
7961 }
7962
7963
7964 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7965
7966 static int
7967 hexnumnstr (char *buf, ULONGEST num, int width)
7968 {
7969 int i;
7970
7971 buf[width] = '\0';
7972
7973 for (i = width - 1; i >= 0; i--)
7974 {
7975 buf[i] = "0123456789abcdef"[(num & 0xf)];
7976 num >>= 4;
7977 }
7978
7979 return width;
7980 }
7981
7982 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7983
7984 static CORE_ADDR
7985 remote_address_masked (CORE_ADDR addr)
7986 {
7987 unsigned int address_size = remote_address_size;
7988
7989 /* If "remoteaddresssize" was not set, default to target address size. */
7990 if (!address_size)
7991 address_size = gdbarch_addr_bit (target_gdbarch ());
7992
7993 if (address_size > 0
7994 && address_size < (sizeof (ULONGEST) * 8))
7995 {
7996 /* Only create a mask when that mask can safely be constructed
7997 in a ULONGEST variable. */
7998 ULONGEST mask = 1;
7999
8000 mask = (mask << address_size) - 1;
8001 addr &= mask;
8002 }
8003 return addr;
8004 }
8005
8006 /* Determine whether the remote target supports binary downloading.
8007 This is accomplished by sending a no-op memory write of zero length
8008 to the target at the specified address. It does not suffice to send
8009 the whole packet, since many stubs strip the eighth bit and
8010 subsequently compute a wrong checksum, which causes real havoc with
8011 remote_write_bytes.
8012
8013 NOTE: This can still lose if the serial line is not eight-bit
8014 clean. In cases like this, the user should clear "remote
8015 X-packet". */
8016
8017 static void
8018 check_binary_download (CORE_ADDR addr)
8019 {
8020 struct remote_state *rs = get_remote_state ();
8021
8022 switch (packet_support (PACKET_X))
8023 {
8024 case PACKET_DISABLE:
8025 break;
8026 case PACKET_ENABLE:
8027 break;
8028 case PACKET_SUPPORT_UNKNOWN:
8029 {
8030 char *p;
8031
8032 p = rs->buf;
8033 *p++ = 'X';
8034 p += hexnumstr (p, (ULONGEST) addr);
8035 *p++ = ',';
8036 p += hexnumstr (p, (ULONGEST) 0);
8037 *p++ = ':';
8038 *p = '\0';
8039
8040 putpkt_binary (rs->buf, (int) (p - rs->buf));
8041 getpkt (&rs->buf, &rs->buf_size, 0);
8042
8043 if (rs->buf[0] == '\0')
8044 {
8045 if (remote_debug)
8046 fprintf_unfiltered (gdb_stdlog,
8047 "binary downloading NOT "
8048 "supported by target\n");
8049 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8050 }
8051 else
8052 {
8053 if (remote_debug)
8054 fprintf_unfiltered (gdb_stdlog,
8055 "binary downloading supported by target\n");
8056 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8057 }
8058 break;
8059 }
8060 }
8061 }
8062
8063 /* Helper function to resize the payload in order to try to get a good
8064 alignment. We try to write an amount of data such that the next write will
8065 start on an address aligned on REMOTE_ALIGN_WRITES. */
8066
8067 static int
8068 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8069 {
8070 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8071 }
8072
8073 /* Write memory data directly to the remote machine.
8074 This does not inform the data cache; the data cache uses this.
8075 HEADER is the starting part of the packet.
8076 MEMADDR is the address in the remote memory space.
8077 MYADDR is the address of the buffer in our space.
8078 LEN_UNITS is the number of addressable units to write.
8079 UNIT_SIZE is the length in bytes of an addressable unit.
8080 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8081 should send data as binary ('X'), or hex-encoded ('M').
8082
8083 The function creates packet of the form
8084 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8085
8086 where encoding of <DATA> is terminated by PACKET_FORMAT.
8087
8088 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8089 are omitted.
8090
8091 Return the transferred status, error or OK (an
8092 'enum target_xfer_status' value). Save the number of addressable units
8093 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8094
8095 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8096 exchange between gdb and the stub could look like (?? in place of the
8097 checksum):
8098
8099 -> $m1000,4#??
8100 <- aaaabbbbccccdddd
8101
8102 -> $M1000,3:eeeeffffeeee#??
8103 <- OK
8104
8105 -> $m1000,4#??
8106 <- eeeeffffeeeedddd */
8107
8108 static enum target_xfer_status
8109 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8110 const gdb_byte *myaddr, ULONGEST len_units,
8111 int unit_size, ULONGEST *xfered_len_units,
8112 char packet_format, int use_length)
8113 {
8114 struct remote_state *rs = get_remote_state ();
8115 char *p;
8116 char *plen = NULL;
8117 int plenlen = 0;
8118 int todo_units;
8119 int units_written;
8120 int payload_capacity_bytes;
8121 int payload_length_bytes;
8122
8123 if (packet_format != 'X' && packet_format != 'M')
8124 internal_error (__FILE__, __LINE__,
8125 _("remote_write_bytes_aux: bad packet format"));
8126
8127 if (len_units == 0)
8128 return TARGET_XFER_EOF;
8129
8130 payload_capacity_bytes = get_memory_write_packet_size ();
8131
8132 /* The packet buffer will be large enough for the payload;
8133 get_memory_packet_size ensures this. */
8134 rs->buf[0] = '\0';
8135
8136 /* Compute the size of the actual payload by subtracting out the
8137 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8138
8139 payload_capacity_bytes -= strlen ("$,:#NN");
8140 if (!use_length)
8141 /* The comma won't be used. */
8142 payload_capacity_bytes += 1;
8143 payload_capacity_bytes -= strlen (header);
8144 payload_capacity_bytes -= hexnumlen (memaddr);
8145
8146 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8147
8148 strcat (rs->buf, header);
8149 p = rs->buf + strlen (header);
8150
8151 /* Compute a best guess of the number of bytes actually transfered. */
8152 if (packet_format == 'X')
8153 {
8154 /* Best guess at number of bytes that will fit. */
8155 todo_units = std::min (len_units,
8156 (ULONGEST) payload_capacity_bytes / unit_size);
8157 if (use_length)
8158 payload_capacity_bytes -= hexnumlen (todo_units);
8159 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8160 }
8161 else
8162 {
8163 /* Number of bytes that will fit. */
8164 todo_units
8165 = std::min (len_units,
8166 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8167 if (use_length)
8168 payload_capacity_bytes -= hexnumlen (todo_units);
8169 todo_units = std::min (todo_units,
8170 (payload_capacity_bytes / unit_size) / 2);
8171 }
8172
8173 if (todo_units <= 0)
8174 internal_error (__FILE__, __LINE__,
8175 _("minimum packet size too small to write data"));
8176
8177 /* If we already need another packet, then try to align the end
8178 of this packet to a useful boundary. */
8179 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8180 todo_units = align_for_efficient_write (todo_units, memaddr);
8181
8182 /* Append "<memaddr>". */
8183 memaddr = remote_address_masked (memaddr);
8184 p += hexnumstr (p, (ULONGEST) memaddr);
8185
8186 if (use_length)
8187 {
8188 /* Append ",". */
8189 *p++ = ',';
8190
8191 /* Append the length and retain its location and size. It may need to be
8192 adjusted once the packet body has been created. */
8193 plen = p;
8194 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8195 p += plenlen;
8196 }
8197
8198 /* Append ":". */
8199 *p++ = ':';
8200 *p = '\0';
8201
8202 /* Append the packet body. */
8203 if (packet_format == 'X')
8204 {
8205 /* Binary mode. Send target system values byte by byte, in
8206 increasing byte addresses. Only escape certain critical
8207 characters. */
8208 payload_length_bytes =
8209 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8210 &units_written, payload_capacity_bytes);
8211
8212 /* If not all TODO units fit, then we'll need another packet. Make
8213 a second try to keep the end of the packet aligned. Don't do
8214 this if the packet is tiny. */
8215 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8216 {
8217 int new_todo_units;
8218
8219 new_todo_units = align_for_efficient_write (units_written, memaddr);
8220
8221 if (new_todo_units != units_written)
8222 payload_length_bytes =
8223 remote_escape_output (myaddr, new_todo_units, unit_size,
8224 (gdb_byte *) p, &units_written,
8225 payload_capacity_bytes);
8226 }
8227
8228 p += payload_length_bytes;
8229 if (use_length && units_written < todo_units)
8230 {
8231 /* Escape chars have filled up the buffer prematurely,
8232 and we have actually sent fewer units than planned.
8233 Fix-up the length field of the packet. Use the same
8234 number of characters as before. */
8235 plen += hexnumnstr (plen, (ULONGEST) units_written,
8236 plenlen);
8237 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8238 }
8239 }
8240 else
8241 {
8242 /* Normal mode: Send target system values byte by byte, in
8243 increasing byte addresses. Each byte is encoded as a two hex
8244 value. */
8245 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8246 units_written = todo_units;
8247 }
8248
8249 putpkt_binary (rs->buf, (int) (p - rs->buf));
8250 getpkt (&rs->buf, &rs->buf_size, 0);
8251
8252 if (rs->buf[0] == 'E')
8253 return TARGET_XFER_E_IO;
8254
8255 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8256 send fewer units than we'd planned. */
8257 *xfered_len_units = (ULONGEST) units_written;
8258 return TARGET_XFER_OK;
8259 }
8260
8261 /* Write memory data directly to the remote machine.
8262 This does not inform the data cache; the data cache uses this.
8263 MEMADDR is the address in the remote memory space.
8264 MYADDR is the address of the buffer in our space.
8265 LEN is the number of bytes.
8266
8267 Return the transferred status, error or OK (an
8268 'enum target_xfer_status' value). Save the number of bytes
8269 transferred in *XFERED_LEN. Only transfer a single packet. */
8270
8271 static enum target_xfer_status
8272 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8273 int unit_size, ULONGEST *xfered_len)
8274 {
8275 const char *packet_format = NULL;
8276
8277 /* Check whether the target supports binary download. */
8278 check_binary_download (memaddr);
8279
8280 switch (packet_support (PACKET_X))
8281 {
8282 case PACKET_ENABLE:
8283 packet_format = "X";
8284 break;
8285 case PACKET_DISABLE:
8286 packet_format = "M";
8287 break;
8288 case PACKET_SUPPORT_UNKNOWN:
8289 internal_error (__FILE__, __LINE__,
8290 _("remote_write_bytes: bad internal state"));
8291 default:
8292 internal_error (__FILE__, __LINE__, _("bad switch"));
8293 }
8294
8295 return remote_write_bytes_aux (packet_format,
8296 memaddr, myaddr, len, unit_size, xfered_len,
8297 packet_format[0], 1);
8298 }
8299
8300 /* Read memory data directly from the remote machine.
8301 This does not use the data cache; the data cache uses this.
8302 MEMADDR is the address in the remote memory space.
8303 MYADDR is the address of the buffer in our space.
8304 LEN_UNITS is the number of addressable memory units to read..
8305 UNIT_SIZE is the length in bytes of an addressable unit.
8306
8307 Return the transferred status, error or OK (an
8308 'enum target_xfer_status' value). Save the number of bytes
8309 transferred in *XFERED_LEN_UNITS.
8310
8311 See the comment of remote_write_bytes_aux for an example of
8312 memory read/write exchange between gdb and the stub. */
8313
8314 static enum target_xfer_status
8315 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8316 int unit_size, ULONGEST *xfered_len_units)
8317 {
8318 struct remote_state *rs = get_remote_state ();
8319 int buf_size_bytes; /* Max size of packet output buffer. */
8320 char *p;
8321 int todo_units;
8322 int decoded_bytes;
8323
8324 buf_size_bytes = get_memory_read_packet_size ();
8325 /* The packet buffer will be large enough for the payload;
8326 get_memory_packet_size ensures this. */
8327
8328 /* Number of units that will fit. */
8329 todo_units = std::min (len_units,
8330 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8331
8332 /* Construct "m"<memaddr>","<len>". */
8333 memaddr = remote_address_masked (memaddr);
8334 p = rs->buf;
8335 *p++ = 'm';
8336 p += hexnumstr (p, (ULONGEST) memaddr);
8337 *p++ = ',';
8338 p += hexnumstr (p, (ULONGEST) todo_units);
8339 *p = '\0';
8340 putpkt (rs->buf);
8341 getpkt (&rs->buf, &rs->buf_size, 0);
8342 if (rs->buf[0] == 'E'
8343 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8344 && rs->buf[3] == '\0')
8345 return TARGET_XFER_E_IO;
8346 /* Reply describes memory byte by byte, each byte encoded as two hex
8347 characters. */
8348 p = rs->buf;
8349 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8350 /* Return what we have. Let higher layers handle partial reads. */
8351 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8352 return TARGET_XFER_OK;
8353 }
8354
8355 /* Using the set of read-only target sections of remote, read live
8356 read-only memory.
8357
8358 For interface/parameters/return description see target.h,
8359 to_xfer_partial. */
8360
8361 static enum target_xfer_status
8362 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8363 ULONGEST memaddr, ULONGEST len,
8364 int unit_size, ULONGEST *xfered_len)
8365 {
8366 struct target_section *secp;
8367 struct target_section_table *table;
8368
8369 secp = target_section_by_addr (ops, memaddr);
8370 if (secp != NULL
8371 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8372 secp->the_bfd_section)
8373 & SEC_READONLY))
8374 {
8375 struct target_section *p;
8376 ULONGEST memend = memaddr + len;
8377
8378 table = target_get_section_table (ops);
8379
8380 for (p = table->sections; p < table->sections_end; p++)
8381 {
8382 if (memaddr >= p->addr)
8383 {
8384 if (memend <= p->endaddr)
8385 {
8386 /* Entire transfer is within this section. */
8387 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8388 xfered_len);
8389 }
8390 else if (memaddr >= p->endaddr)
8391 {
8392 /* This section ends before the transfer starts. */
8393 continue;
8394 }
8395 else
8396 {
8397 /* This section overlaps the transfer. Just do half. */
8398 len = p->endaddr - memaddr;
8399 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8400 xfered_len);
8401 }
8402 }
8403 }
8404 }
8405
8406 return TARGET_XFER_EOF;
8407 }
8408
8409 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8410 first if the requested memory is unavailable in traceframe.
8411 Otherwise, fall back to remote_read_bytes_1. */
8412
8413 static enum target_xfer_status
8414 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8415 gdb_byte *myaddr, ULONGEST len, int unit_size,
8416 ULONGEST *xfered_len)
8417 {
8418 if (len == 0)
8419 return TARGET_XFER_EOF;
8420
8421 if (get_traceframe_number () != -1)
8422 {
8423 VEC(mem_range_s) *available;
8424
8425 /* If we fail to get the set of available memory, then the
8426 target does not support querying traceframe info, and so we
8427 attempt reading from the traceframe anyway (assuming the
8428 target implements the old QTro packet then). */
8429 if (traceframe_available_memory (&available, memaddr, len))
8430 {
8431 struct cleanup *old_chain;
8432
8433 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8434
8435 if (VEC_empty (mem_range_s, available)
8436 || VEC_index (mem_range_s, available, 0)->start != memaddr)
8437 {
8438 enum target_xfer_status res;
8439
8440 /* Don't read into the traceframe's available
8441 memory. */
8442 if (!VEC_empty (mem_range_s, available))
8443 {
8444 LONGEST oldlen = len;
8445
8446 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8447 gdb_assert (len <= oldlen);
8448 }
8449
8450 do_cleanups (old_chain);
8451
8452 /* This goes through the topmost target again. */
8453 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8454 len, unit_size, xfered_len);
8455 if (res == TARGET_XFER_OK)
8456 return TARGET_XFER_OK;
8457 else
8458 {
8459 /* No use trying further, we know some memory starting
8460 at MEMADDR isn't available. */
8461 *xfered_len = len;
8462 return TARGET_XFER_UNAVAILABLE;
8463 }
8464 }
8465
8466 /* Don't try to read more than how much is available, in
8467 case the target implements the deprecated QTro packet to
8468 cater for older GDBs (the target's knowledge of read-only
8469 sections may be outdated by now). */
8470 len = VEC_index (mem_range_s, available, 0)->length;
8471
8472 do_cleanups (old_chain);
8473 }
8474 }
8475
8476 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8477 }
8478
8479 \f
8480
8481 /* Sends a packet with content determined by the printf format string
8482 FORMAT and the remaining arguments, then gets the reply. Returns
8483 whether the packet was a success, a failure, or unknown. */
8484
8485 static enum packet_result remote_send_printf (const char *format, ...)
8486 ATTRIBUTE_PRINTF (1, 2);
8487
8488 static enum packet_result
8489 remote_send_printf (const char *format, ...)
8490 {
8491 struct remote_state *rs = get_remote_state ();
8492 int max_size = get_remote_packet_size ();
8493 va_list ap;
8494
8495 va_start (ap, format);
8496
8497 rs->buf[0] = '\0';
8498 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8499 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8500
8501 if (putpkt (rs->buf) < 0)
8502 error (_("Communication problem with target."));
8503
8504 rs->buf[0] = '\0';
8505 getpkt (&rs->buf, &rs->buf_size, 0);
8506
8507 return packet_check_result (rs->buf);
8508 }
8509
8510 /* Flash writing can take quite some time. We'll set
8511 effectively infinite timeout for flash operations.
8512 In future, we'll need to decide on a better approach. */
8513 static const int remote_flash_timeout = 1000;
8514
8515 static void
8516 remote_flash_erase (struct target_ops *ops,
8517 ULONGEST address, LONGEST length)
8518 {
8519 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8520 enum packet_result ret;
8521 scoped_restore restore_timeout
8522 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8523
8524 ret = remote_send_printf ("vFlashErase:%s,%s",
8525 phex (address, addr_size),
8526 phex (length, 4));
8527 switch (ret)
8528 {
8529 case PACKET_UNKNOWN:
8530 error (_("Remote target does not support flash erase"));
8531 case PACKET_ERROR:
8532 error (_("Error erasing flash with vFlashErase packet"));
8533 default:
8534 break;
8535 }
8536 }
8537
8538 static enum target_xfer_status
8539 remote_flash_write (struct target_ops *ops, ULONGEST address,
8540 ULONGEST length, ULONGEST *xfered_len,
8541 const gdb_byte *data)
8542 {
8543 scoped_restore restore_timeout
8544 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8545 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8546 xfered_len,'X', 0);
8547 }
8548
8549 static void
8550 remote_flash_done (struct target_ops *ops)
8551 {
8552 int ret;
8553
8554 scoped_restore restore_timeout
8555 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8556
8557 ret = remote_send_printf ("vFlashDone");
8558
8559 switch (ret)
8560 {
8561 case PACKET_UNKNOWN:
8562 error (_("Remote target does not support vFlashDone"));
8563 case PACKET_ERROR:
8564 error (_("Error finishing flash operation"));
8565 default:
8566 break;
8567 }
8568 }
8569
8570 static void
8571 remote_files_info (struct target_ops *ignore)
8572 {
8573 puts_filtered ("Debugging a target over a serial line.\n");
8574 }
8575 \f
8576 /* Stuff for dealing with the packets which are part of this protocol.
8577 See comment at top of file for details. */
8578
8579 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8580 error to higher layers. Called when a serial error is detected.
8581 The exception message is STRING, followed by a colon and a blank,
8582 the system error message for errno at function entry and final dot
8583 for output compatibility with throw_perror_with_name. */
8584
8585 static void
8586 unpush_and_perror (const char *string)
8587 {
8588 int saved_errno = errno;
8589
8590 remote_unpush_target ();
8591 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8592 safe_strerror (saved_errno));
8593 }
8594
8595 /* Read a single character from the remote end. The current quit
8596 handler is overridden to avoid quitting in the middle of packet
8597 sequence, as that would break communication with the remote server.
8598 See remote_serial_quit_handler for more detail. */
8599
8600 static int
8601 readchar (int timeout)
8602 {
8603 int ch;
8604 struct remote_state *rs = get_remote_state ();
8605
8606 {
8607 scoped_restore restore_quit
8608 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8609
8610 rs->got_ctrlc_during_io = 0;
8611
8612 ch = serial_readchar (rs->remote_desc, timeout);
8613
8614 if (rs->got_ctrlc_during_io)
8615 set_quit_flag ();
8616 }
8617
8618 if (ch >= 0)
8619 return ch;
8620
8621 switch ((enum serial_rc) ch)
8622 {
8623 case SERIAL_EOF:
8624 remote_unpush_target ();
8625 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8626 /* no return */
8627 case SERIAL_ERROR:
8628 unpush_and_perror (_("Remote communication error. "
8629 "Target disconnected."));
8630 /* no return */
8631 case SERIAL_TIMEOUT:
8632 break;
8633 }
8634 return ch;
8635 }
8636
8637 /* Wrapper for serial_write that closes the target and throws if
8638 writing fails. The current quit handler is overridden to avoid
8639 quitting in the middle of packet sequence, as that would break
8640 communication with the remote server. See
8641 remote_serial_quit_handler for more detail. */
8642
8643 static void
8644 remote_serial_write (const char *str, int len)
8645 {
8646 struct remote_state *rs = get_remote_state ();
8647
8648 scoped_restore restore_quit
8649 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8650
8651 rs->got_ctrlc_during_io = 0;
8652
8653 if (serial_write (rs->remote_desc, str, len))
8654 {
8655 unpush_and_perror (_("Remote communication error. "
8656 "Target disconnected."));
8657 }
8658
8659 if (rs->got_ctrlc_during_io)
8660 set_quit_flag ();
8661 }
8662
8663 /* Send the command in *BUF to the remote machine, and read the reply
8664 into *BUF. Report an error if we get an error reply. Resize
8665 *BUF using xrealloc if necessary to hold the result, and update
8666 *SIZEOF_BUF. */
8667
8668 static void
8669 remote_send (char **buf,
8670 long *sizeof_buf)
8671 {
8672 putpkt (*buf);
8673 getpkt (buf, sizeof_buf, 0);
8674
8675 if ((*buf)[0] == 'E')
8676 error (_("Remote failure reply: %s"), *buf);
8677 }
8678
8679 /* Return a string representing an escaped version of BUF, of len N.
8680 E.g. \n is converted to \\n, \t to \\t, etc. */
8681
8682 static std::string
8683 escape_buffer (const char *buf, int n)
8684 {
8685 string_file stb;
8686
8687 stb.putstrn (buf, n, '\\');
8688 return std::move (stb.string ());
8689 }
8690
8691 /* Display a null-terminated packet on stdout, for debugging, using C
8692 string notation. */
8693
8694 static void
8695 print_packet (const char *buf)
8696 {
8697 puts_filtered ("\"");
8698 fputstr_filtered (buf, '"', gdb_stdout);
8699 puts_filtered ("\"");
8700 }
8701
8702 int
8703 putpkt (const char *buf)
8704 {
8705 return putpkt_binary (buf, strlen (buf));
8706 }
8707
8708 /* Send a packet to the remote machine, with error checking. The data
8709 of the packet is in BUF. The string in BUF can be at most
8710 get_remote_packet_size () - 5 to account for the $, # and checksum,
8711 and for a possible /0 if we are debugging (remote_debug) and want
8712 to print the sent packet as a string. */
8713
8714 static int
8715 putpkt_binary (const char *buf, int cnt)
8716 {
8717 struct remote_state *rs = get_remote_state ();
8718 int i;
8719 unsigned char csum = 0;
8720 char *buf2 = (char *) xmalloc (cnt + 6);
8721 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8722
8723 int ch;
8724 int tcount = 0;
8725 char *p;
8726
8727 /* Catch cases like trying to read memory or listing threads while
8728 we're waiting for a stop reply. The remote server wouldn't be
8729 ready to handle this request, so we'd hang and timeout. We don't
8730 have to worry about this in synchronous mode, because in that
8731 case it's not possible to issue a command while the target is
8732 running. This is not a problem in non-stop mode, because in that
8733 case, the stub is always ready to process serial input. */
8734 if (!target_is_non_stop_p ()
8735 && target_is_async_p ()
8736 && rs->waiting_for_stop_reply)
8737 {
8738 error (_("Cannot execute this command while the target is running.\n"
8739 "Use the \"interrupt\" command to stop the target\n"
8740 "and then try again."));
8741 }
8742
8743 /* We're sending out a new packet. Make sure we don't look at a
8744 stale cached response. */
8745 rs->cached_wait_status = 0;
8746
8747 /* Copy the packet into buffer BUF2, encapsulating it
8748 and giving it a checksum. */
8749
8750 p = buf2;
8751 *p++ = '$';
8752
8753 for (i = 0; i < cnt; i++)
8754 {
8755 csum += buf[i];
8756 *p++ = buf[i];
8757 }
8758 *p++ = '#';
8759 *p++ = tohex ((csum >> 4) & 0xf);
8760 *p++ = tohex (csum & 0xf);
8761
8762 /* Send it over and over until we get a positive ack. */
8763
8764 while (1)
8765 {
8766 int started_error_output = 0;
8767
8768 if (remote_debug)
8769 {
8770 *p = '\0';
8771
8772 int len = (int) (p - buf2);
8773
8774 std::string str
8775 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8776
8777 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8778
8779 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
8780 {
8781 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
8782 str.length () - REMOTE_DEBUG_MAX_CHAR);
8783 }
8784
8785 fprintf_unfiltered (gdb_stdlog, "...");
8786
8787 gdb_flush (gdb_stdlog);
8788 }
8789 remote_serial_write (buf2, p - buf2);
8790
8791 /* If this is a no acks version of the remote protocol, send the
8792 packet and move on. */
8793 if (rs->noack_mode)
8794 break;
8795
8796 /* Read until either a timeout occurs (-2) or '+' is read.
8797 Handle any notification that arrives in the mean time. */
8798 while (1)
8799 {
8800 ch = readchar (remote_timeout);
8801
8802 if (remote_debug)
8803 {
8804 switch (ch)
8805 {
8806 case '+':
8807 case '-':
8808 case SERIAL_TIMEOUT:
8809 case '$':
8810 case '%':
8811 if (started_error_output)
8812 {
8813 putchar_unfiltered ('\n');
8814 started_error_output = 0;
8815 }
8816 }
8817 }
8818
8819 switch (ch)
8820 {
8821 case '+':
8822 if (remote_debug)
8823 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8824 do_cleanups (old_chain);
8825 return 1;
8826 case '-':
8827 if (remote_debug)
8828 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8829 /* FALLTHROUGH */
8830 case SERIAL_TIMEOUT:
8831 tcount++;
8832 if (tcount > 3)
8833 {
8834 do_cleanups (old_chain);
8835 return 0;
8836 }
8837 break; /* Retransmit buffer. */
8838 case '$':
8839 {
8840 if (remote_debug)
8841 fprintf_unfiltered (gdb_stdlog,
8842 "Packet instead of Ack, ignoring it\n");
8843 /* It's probably an old response sent because an ACK
8844 was lost. Gobble up the packet and ack it so it
8845 doesn't get retransmitted when we resend this
8846 packet. */
8847 skip_frame ();
8848 remote_serial_write ("+", 1);
8849 continue; /* Now, go look for +. */
8850 }
8851
8852 case '%':
8853 {
8854 int val;
8855
8856 /* If we got a notification, handle it, and go back to looking
8857 for an ack. */
8858 /* We've found the start of a notification. Now
8859 collect the data. */
8860 val = read_frame (&rs->buf, &rs->buf_size);
8861 if (val >= 0)
8862 {
8863 if (remote_debug)
8864 {
8865 std::string str = escape_buffer (rs->buf, val);
8866
8867 fprintf_unfiltered (gdb_stdlog,
8868 " Notification received: %s\n",
8869 str.c_str ());
8870 }
8871 handle_notification (rs->notif_state, rs->buf);
8872 /* We're in sync now, rewait for the ack. */
8873 tcount = 0;
8874 }
8875 else
8876 {
8877 if (remote_debug)
8878 {
8879 if (!started_error_output)
8880 {
8881 started_error_output = 1;
8882 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8883 }
8884 fputc_unfiltered (ch & 0177, gdb_stdlog);
8885 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8886 }
8887 }
8888 continue;
8889 }
8890 /* fall-through */
8891 default:
8892 if (remote_debug)
8893 {
8894 if (!started_error_output)
8895 {
8896 started_error_output = 1;
8897 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8898 }
8899 fputc_unfiltered (ch & 0177, gdb_stdlog);
8900 }
8901 continue;
8902 }
8903 break; /* Here to retransmit. */
8904 }
8905
8906 #if 0
8907 /* This is wrong. If doing a long backtrace, the user should be
8908 able to get out next time we call QUIT, without anything as
8909 violent as interrupt_query. If we want to provide a way out of
8910 here without getting to the next QUIT, it should be based on
8911 hitting ^C twice as in remote_wait. */
8912 if (quit_flag)
8913 {
8914 quit_flag = 0;
8915 interrupt_query ();
8916 }
8917 #endif
8918 }
8919
8920 do_cleanups (old_chain);
8921 return 0;
8922 }
8923
8924 /* Come here after finding the start of a frame when we expected an
8925 ack. Do our best to discard the rest of this packet. */
8926
8927 static void
8928 skip_frame (void)
8929 {
8930 int c;
8931
8932 while (1)
8933 {
8934 c = readchar (remote_timeout);
8935 switch (c)
8936 {
8937 case SERIAL_TIMEOUT:
8938 /* Nothing we can do. */
8939 return;
8940 case '#':
8941 /* Discard the two bytes of checksum and stop. */
8942 c = readchar (remote_timeout);
8943 if (c >= 0)
8944 c = readchar (remote_timeout);
8945
8946 return;
8947 case '*': /* Run length encoding. */
8948 /* Discard the repeat count. */
8949 c = readchar (remote_timeout);
8950 if (c < 0)
8951 return;
8952 break;
8953 default:
8954 /* A regular character. */
8955 break;
8956 }
8957 }
8958 }
8959
8960 /* Come here after finding the start of the frame. Collect the rest
8961 into *BUF, verifying the checksum, length, and handling run-length
8962 compression. NUL terminate the buffer. If there is not enough room,
8963 expand *BUF using xrealloc.
8964
8965 Returns -1 on error, number of characters in buffer (ignoring the
8966 trailing NULL) on success. (could be extended to return one of the
8967 SERIAL status indications). */
8968
8969 static long
8970 read_frame (char **buf_p,
8971 long *sizeof_buf)
8972 {
8973 unsigned char csum;
8974 long bc;
8975 int c;
8976 char *buf = *buf_p;
8977 struct remote_state *rs = get_remote_state ();
8978
8979 csum = 0;
8980 bc = 0;
8981
8982 while (1)
8983 {
8984 c = readchar (remote_timeout);
8985 switch (c)
8986 {
8987 case SERIAL_TIMEOUT:
8988 if (remote_debug)
8989 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8990 return -1;
8991 case '$':
8992 if (remote_debug)
8993 fputs_filtered ("Saw new packet start in middle of old one\n",
8994 gdb_stdlog);
8995 return -1; /* Start a new packet, count retries. */
8996 case '#':
8997 {
8998 unsigned char pktcsum;
8999 int check_0 = 0;
9000 int check_1 = 0;
9001
9002 buf[bc] = '\0';
9003
9004 check_0 = readchar (remote_timeout);
9005 if (check_0 >= 0)
9006 check_1 = readchar (remote_timeout);
9007
9008 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9009 {
9010 if (remote_debug)
9011 fputs_filtered ("Timeout in checksum, retrying\n",
9012 gdb_stdlog);
9013 return -1;
9014 }
9015 else if (check_0 < 0 || check_1 < 0)
9016 {
9017 if (remote_debug)
9018 fputs_filtered ("Communication error in checksum\n",
9019 gdb_stdlog);
9020 return -1;
9021 }
9022
9023 /* Don't recompute the checksum; with no ack packets we
9024 don't have any way to indicate a packet retransmission
9025 is necessary. */
9026 if (rs->noack_mode)
9027 return bc;
9028
9029 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9030 if (csum == pktcsum)
9031 return bc;
9032
9033 if (remote_debug)
9034 {
9035 std::string str = escape_buffer (buf, bc);
9036
9037 fprintf_unfiltered (gdb_stdlog,
9038 "Bad checksum, sentsum=0x%x, "
9039 "csum=0x%x, buf=%s\n",
9040 pktcsum, csum, str.c_str ());
9041 }
9042 /* Number of characters in buffer ignoring trailing
9043 NULL. */
9044 return -1;
9045 }
9046 case '*': /* Run length encoding. */
9047 {
9048 int repeat;
9049
9050 csum += c;
9051 c = readchar (remote_timeout);
9052 csum += c;
9053 repeat = c - ' ' + 3; /* Compute repeat count. */
9054
9055 /* The character before ``*'' is repeated. */
9056
9057 if (repeat > 0 && repeat <= 255 && bc > 0)
9058 {
9059 if (bc + repeat - 1 >= *sizeof_buf - 1)
9060 {
9061 /* Make some more room in the buffer. */
9062 *sizeof_buf += repeat;
9063 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9064 buf = *buf_p;
9065 }
9066
9067 memset (&buf[bc], buf[bc - 1], repeat);
9068 bc += repeat;
9069 continue;
9070 }
9071
9072 buf[bc] = '\0';
9073 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9074 return -1;
9075 }
9076 default:
9077 if (bc >= *sizeof_buf - 1)
9078 {
9079 /* Make some more room in the buffer. */
9080 *sizeof_buf *= 2;
9081 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9082 buf = *buf_p;
9083 }
9084
9085 buf[bc++] = c;
9086 csum += c;
9087 continue;
9088 }
9089 }
9090 }
9091
9092 /* Read a packet from the remote machine, with error checking, and
9093 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9094 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9095 rather than timing out; this is used (in synchronous mode) to wait
9096 for a target that is is executing user code to stop. */
9097 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9098 don't have to change all the calls to getpkt to deal with the
9099 return value, because at the moment I don't know what the right
9100 thing to do it for those. */
9101 void
9102 getpkt (char **buf,
9103 long *sizeof_buf,
9104 int forever)
9105 {
9106 getpkt_sane (buf, sizeof_buf, forever);
9107 }
9108
9109
9110 /* Read a packet from the remote machine, with error checking, and
9111 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9112 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9113 rather than timing out; this is used (in synchronous mode) to wait
9114 for a target that is is executing user code to stop. If FOREVER ==
9115 0, this function is allowed to time out gracefully and return an
9116 indication of this to the caller. Otherwise return the number of
9117 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9118 enough reason to return to the caller. *IS_NOTIF is an output
9119 boolean that indicates whether *BUF holds a notification or not
9120 (a regular packet). */
9121
9122 static int
9123 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9124 int expecting_notif, int *is_notif)
9125 {
9126 struct remote_state *rs = get_remote_state ();
9127 int c;
9128 int tries;
9129 int timeout;
9130 int val = -1;
9131
9132 /* We're reading a new response. Make sure we don't look at a
9133 previously cached response. */
9134 rs->cached_wait_status = 0;
9135
9136 strcpy (*buf, "timeout");
9137
9138 if (forever)
9139 timeout = watchdog > 0 ? watchdog : -1;
9140 else if (expecting_notif)
9141 timeout = 0; /* There should already be a char in the buffer. If
9142 not, bail out. */
9143 else
9144 timeout = remote_timeout;
9145
9146 #define MAX_TRIES 3
9147
9148 /* Process any number of notifications, and then return when
9149 we get a packet. */
9150 for (;;)
9151 {
9152 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9153 times. */
9154 for (tries = 1; tries <= MAX_TRIES; tries++)
9155 {
9156 /* This can loop forever if the remote side sends us
9157 characters continuously, but if it pauses, we'll get
9158 SERIAL_TIMEOUT from readchar because of timeout. Then
9159 we'll count that as a retry.
9160
9161 Note that even when forever is set, we will only wait
9162 forever prior to the start of a packet. After that, we
9163 expect characters to arrive at a brisk pace. They should
9164 show up within remote_timeout intervals. */
9165 do
9166 c = readchar (timeout);
9167 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9168
9169 if (c == SERIAL_TIMEOUT)
9170 {
9171 if (expecting_notif)
9172 return -1; /* Don't complain, it's normal to not get
9173 anything in this case. */
9174
9175 if (forever) /* Watchdog went off? Kill the target. */
9176 {
9177 remote_unpush_target ();
9178 throw_error (TARGET_CLOSE_ERROR,
9179 _("Watchdog timeout has expired. "
9180 "Target detached."));
9181 }
9182 if (remote_debug)
9183 fputs_filtered ("Timed out.\n", gdb_stdlog);
9184 }
9185 else
9186 {
9187 /* We've found the start of a packet or notification.
9188 Now collect the data. */
9189 val = read_frame (buf, sizeof_buf);
9190 if (val >= 0)
9191 break;
9192 }
9193
9194 remote_serial_write ("-", 1);
9195 }
9196
9197 if (tries > MAX_TRIES)
9198 {
9199 /* We have tried hard enough, and just can't receive the
9200 packet/notification. Give up. */
9201 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9202
9203 /* Skip the ack char if we're in no-ack mode. */
9204 if (!rs->noack_mode)
9205 remote_serial_write ("+", 1);
9206 return -1;
9207 }
9208
9209 /* If we got an ordinary packet, return that to our caller. */
9210 if (c == '$')
9211 {
9212 if (remote_debug)
9213 {
9214 std::string str
9215 = escape_buffer (*buf,
9216 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9217
9218 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9219 str.c_str ());
9220
9221 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
9222 {
9223 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
9224 str.length () - REMOTE_DEBUG_MAX_CHAR);
9225 }
9226
9227 fprintf_unfiltered (gdb_stdlog, "\n");
9228 }
9229
9230 /* Skip the ack char if we're in no-ack mode. */
9231 if (!rs->noack_mode)
9232 remote_serial_write ("+", 1);
9233 if (is_notif != NULL)
9234 *is_notif = 0;
9235 return val;
9236 }
9237
9238 /* If we got a notification, handle it, and go back to looking
9239 for a packet. */
9240 else
9241 {
9242 gdb_assert (c == '%');
9243
9244 if (remote_debug)
9245 {
9246 std::string str = escape_buffer (*buf, val);
9247
9248 fprintf_unfiltered (gdb_stdlog,
9249 " Notification received: %s\n",
9250 str.c_str ());
9251 }
9252 if (is_notif != NULL)
9253 *is_notif = 1;
9254
9255 handle_notification (rs->notif_state, *buf);
9256
9257 /* Notifications require no acknowledgement. */
9258
9259 if (expecting_notif)
9260 return val;
9261 }
9262 }
9263 }
9264
9265 static int
9266 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9267 {
9268 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9269 }
9270
9271 static int
9272 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9273 int *is_notif)
9274 {
9275 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9276 is_notif);
9277 }
9278
9279 /* Check whether EVENT is a fork event for the process specified
9280 by the pid passed in DATA, and if it is, kill the fork child. */
9281
9282 static int
9283 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9284 QUEUE_ITER (stop_reply_p) *iter,
9285 stop_reply_p event,
9286 void *data)
9287 {
9288 struct queue_iter_param *param = (struct queue_iter_param *) data;
9289 int parent_pid = *(int *) param->input;
9290
9291 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9292 {
9293 struct remote_state *rs = get_remote_state ();
9294 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9295 int res;
9296
9297 res = remote_vkill (child_pid, rs);
9298 if (res != 0)
9299 error (_("Can't kill fork child process %d"), child_pid);
9300 }
9301
9302 return 1;
9303 }
9304
9305 /* Kill any new fork children of process PID that haven't been
9306 processed by follow_fork. */
9307
9308 static void
9309 kill_new_fork_children (int pid, struct remote_state *rs)
9310 {
9311 struct thread_info *thread;
9312 struct notif_client *notif = &notif_client_stop;
9313 struct queue_iter_param param;
9314
9315 /* Kill the fork child threads of any threads in process PID
9316 that are stopped at a fork event. */
9317 ALL_NON_EXITED_THREADS (thread)
9318 {
9319 struct target_waitstatus *ws = &thread->pending_follow;
9320
9321 if (is_pending_fork_parent (ws, pid, thread->ptid))
9322 {
9323 struct remote_state *rs = get_remote_state ();
9324 int child_pid = ptid_get_pid (ws->value.related_pid);
9325 int res;
9326
9327 res = remote_vkill (child_pid, rs);
9328 if (res != 0)
9329 error (_("Can't kill fork child process %d"), child_pid);
9330 }
9331 }
9332
9333 /* Check for any pending fork events (not reported or processed yet)
9334 in process PID and kill those fork child threads as well. */
9335 remote_notif_get_pending_events (notif);
9336 param.input = &pid;
9337 param.output = NULL;
9338 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9339 kill_child_of_pending_fork, &param);
9340 }
9341
9342 \f
9343 /* Target hook to kill the current inferior. */
9344
9345 static void
9346 remote_kill (struct target_ops *ops)
9347 {
9348 int res = -1;
9349 int pid = ptid_get_pid (inferior_ptid);
9350 struct remote_state *rs = get_remote_state ();
9351
9352 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9353 {
9354 /* If we're stopped while forking and we haven't followed yet,
9355 kill the child task. We need to do this before killing the
9356 parent task because if this is a vfork then the parent will
9357 be sleeping. */
9358 kill_new_fork_children (pid, rs);
9359
9360 res = remote_vkill (pid, rs);
9361 if (res == 0)
9362 {
9363 target_mourn_inferior (inferior_ptid);
9364 return;
9365 }
9366 }
9367
9368 /* If we are in 'target remote' mode and we are killing the only
9369 inferior, then we will tell gdbserver to exit and unpush the
9370 target. */
9371 if (res == -1 && !remote_multi_process_p (rs)
9372 && number_of_live_inferiors () == 1)
9373 {
9374 remote_kill_k ();
9375
9376 /* We've killed the remote end, we get to mourn it. If we are
9377 not in extended mode, mourning the inferior also unpushes
9378 remote_ops from the target stack, which closes the remote
9379 connection. */
9380 target_mourn_inferior (inferior_ptid);
9381
9382 return;
9383 }
9384
9385 error (_("Can't kill process"));
9386 }
9387
9388 /* Send a kill request to the target using the 'vKill' packet. */
9389
9390 static int
9391 remote_vkill (int pid, struct remote_state *rs)
9392 {
9393 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9394 return -1;
9395
9396 /* Tell the remote target to detach. */
9397 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9398 putpkt (rs->buf);
9399 getpkt (&rs->buf, &rs->buf_size, 0);
9400
9401 switch (packet_ok (rs->buf,
9402 &remote_protocol_packets[PACKET_vKill]))
9403 {
9404 case PACKET_OK:
9405 return 0;
9406 case PACKET_ERROR:
9407 return 1;
9408 case PACKET_UNKNOWN:
9409 return -1;
9410 default:
9411 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9412 }
9413 }
9414
9415 /* Send a kill request to the target using the 'k' packet. */
9416
9417 static void
9418 remote_kill_k (void)
9419 {
9420 /* Catch errors so the user can quit from gdb even when we
9421 aren't on speaking terms with the remote system. */
9422 TRY
9423 {
9424 putpkt ("k");
9425 }
9426 CATCH (ex, RETURN_MASK_ERROR)
9427 {
9428 if (ex.error == TARGET_CLOSE_ERROR)
9429 {
9430 /* If we got an (EOF) error that caused the target
9431 to go away, then we're done, that's what we wanted.
9432 "k" is susceptible to cause a premature EOF, given
9433 that the remote server isn't actually required to
9434 reply to "k", and it can happen that it doesn't
9435 even get to reply ACK to the "k". */
9436 return;
9437 }
9438
9439 /* Otherwise, something went wrong. We didn't actually kill
9440 the target. Just propagate the exception, and let the
9441 user or higher layers decide what to do. */
9442 throw_exception (ex);
9443 }
9444 END_CATCH
9445 }
9446
9447 static void
9448 remote_mourn (struct target_ops *target)
9449 {
9450 struct remote_state *rs = get_remote_state ();
9451
9452 /* In 'target remote' mode with one inferior, we close the connection. */
9453 if (!rs->extended && number_of_live_inferiors () <= 1)
9454 {
9455 unpush_target (target);
9456
9457 /* remote_close takes care of doing most of the clean up. */
9458 generic_mourn_inferior ();
9459 return;
9460 }
9461
9462 /* In case we got here due to an error, but we're going to stay
9463 connected. */
9464 rs->waiting_for_stop_reply = 0;
9465
9466 /* If the current general thread belonged to the process we just
9467 detached from or has exited, the remote side current general
9468 thread becomes undefined. Considering a case like this:
9469
9470 - We just got here due to a detach.
9471 - The process that we're detaching from happens to immediately
9472 report a global breakpoint being hit in non-stop mode, in the
9473 same thread we had selected before.
9474 - GDB attaches to this process again.
9475 - This event happens to be the next event we handle.
9476
9477 GDB would consider that the current general thread didn't need to
9478 be set on the stub side (with Hg), since for all it knew,
9479 GENERAL_THREAD hadn't changed.
9480
9481 Notice that although in all-stop mode, the remote server always
9482 sets the current thread to the thread reporting the stop event,
9483 that doesn't happen in non-stop mode; in non-stop, the stub *must
9484 not* change the current thread when reporting a breakpoint hit,
9485 due to the decoupling of event reporting and event handling.
9486
9487 To keep things simple, we always invalidate our notion of the
9488 current thread. */
9489 record_currthread (rs, minus_one_ptid);
9490
9491 /* Call common code to mark the inferior as not running. */
9492 generic_mourn_inferior ();
9493
9494 if (!have_inferiors ())
9495 {
9496 if (!remote_multi_process_p (rs))
9497 {
9498 /* Check whether the target is running now - some remote stubs
9499 automatically restart after kill. */
9500 putpkt ("?");
9501 getpkt (&rs->buf, &rs->buf_size, 0);
9502
9503 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9504 {
9505 /* Assume that the target has been restarted. Set
9506 inferior_ptid so that bits of core GDB realizes
9507 there's something here, e.g., so that the user can
9508 say "kill" again. */
9509 inferior_ptid = magic_null_ptid;
9510 }
9511 }
9512 }
9513 }
9514
9515 static int
9516 extended_remote_supports_disable_randomization (struct target_ops *self)
9517 {
9518 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9519 }
9520
9521 static void
9522 extended_remote_disable_randomization (int val)
9523 {
9524 struct remote_state *rs = get_remote_state ();
9525 char *reply;
9526
9527 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9528 val);
9529 putpkt (rs->buf);
9530 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9531 if (*reply == '\0')
9532 error (_("Target does not support QDisableRandomization."));
9533 if (strcmp (reply, "OK") != 0)
9534 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9535 }
9536
9537 static int
9538 extended_remote_run (const std::string &args)
9539 {
9540 struct remote_state *rs = get_remote_state ();
9541 int len;
9542 const char *remote_exec_file = get_remote_exec_file ();
9543
9544 /* If the user has disabled vRun support, or we have detected that
9545 support is not available, do not try it. */
9546 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9547 return -1;
9548
9549 strcpy (rs->buf, "vRun;");
9550 len = strlen (rs->buf);
9551
9552 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9553 error (_("Remote file name too long for run packet"));
9554 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9555 strlen (remote_exec_file));
9556
9557 if (!args.empty ())
9558 {
9559 int i;
9560
9561 gdb_argv argv (args.c_str ());
9562 for (i = 0; argv[i] != NULL; i++)
9563 {
9564 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9565 error (_("Argument list too long for run packet"));
9566 rs->buf[len++] = ';';
9567 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9568 strlen (argv[i]));
9569 }
9570 }
9571
9572 rs->buf[len++] = '\0';
9573
9574 putpkt (rs->buf);
9575 getpkt (&rs->buf, &rs->buf_size, 0);
9576
9577 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9578 {
9579 case PACKET_OK:
9580 /* We have a wait response. All is well. */
9581 return 0;
9582 case PACKET_UNKNOWN:
9583 return -1;
9584 case PACKET_ERROR:
9585 if (remote_exec_file[0] == '\0')
9586 error (_("Running the default executable on the remote target failed; "
9587 "try \"set remote exec-file\"?"));
9588 else
9589 error (_("Running \"%s\" on the remote target failed"),
9590 remote_exec_file);
9591 default:
9592 gdb_assert_not_reached (_("bad switch"));
9593 }
9594 }
9595
9596 /* Helper function to send set/unset environment packets. ACTION is
9597 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9598 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9599 sent. */
9600
9601 static void
9602 send_environment_packet (struct remote_state *rs,
9603 const char *action,
9604 const char *packet,
9605 const char *value)
9606 {
9607 /* Convert the environment variable to an hex string, which
9608 is the best format to be transmitted over the wire. */
9609 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9610 strlen (value));
9611
9612 xsnprintf (rs->buf, get_remote_packet_size (),
9613 "%s:%s", packet, encoded_value.c_str ());
9614
9615 putpkt (rs->buf);
9616 getpkt (&rs->buf, &rs->buf_size, 0);
9617 if (strcmp (rs->buf, "OK") != 0)
9618 warning (_("Unable to %s environment variable '%s' on remote."),
9619 action, value);
9620 }
9621
9622 /* Helper function to handle the QEnvironment* packets. */
9623
9624 static void
9625 extended_remote_environment_support (struct remote_state *rs)
9626 {
9627 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9628 {
9629 putpkt ("QEnvironmentReset");
9630 getpkt (&rs->buf, &rs->buf_size, 0);
9631 if (strcmp (rs->buf, "OK") != 0)
9632 warning (_("Unable to reset environment on remote."));
9633 }
9634
9635 gdb_environ *e = &current_inferior ()->environment;
9636
9637 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9638 for (const std::string &el : e->user_set_env ())
9639 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9640 el.c_str ());
9641
9642 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9643 for (const std::string &el : e->user_unset_env ())
9644 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9645 }
9646
9647 /* In the extended protocol we want to be able to do things like
9648 "run" and have them basically work as expected. So we need
9649 a special create_inferior function. We support changing the
9650 executable file and the command line arguments, but not the
9651 environment. */
9652
9653 static void
9654 extended_remote_create_inferior (struct target_ops *ops,
9655 const char *exec_file,
9656 const std::string &args,
9657 char **env, int from_tty)
9658 {
9659 int run_worked;
9660 char *stop_reply;
9661 struct remote_state *rs = get_remote_state ();
9662 const char *remote_exec_file = get_remote_exec_file ();
9663
9664 /* If running asynchronously, register the target file descriptor
9665 with the event loop. */
9666 if (target_can_async_p ())
9667 target_async (1);
9668
9669 /* Disable address space randomization if requested (and supported). */
9670 if (extended_remote_supports_disable_randomization (ops))
9671 extended_remote_disable_randomization (disable_randomization);
9672
9673 /* If startup-with-shell is on, we inform gdbserver to start the
9674 remote inferior using a shell. */
9675 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9676 {
9677 xsnprintf (rs->buf, get_remote_packet_size (),
9678 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9679 putpkt (rs->buf);
9680 getpkt (&rs->buf, &rs->buf_size, 0);
9681 if (strcmp (rs->buf, "OK") != 0)
9682 error (_("\
9683 Remote replied unexpectedly while setting startup-with-shell: %s"),
9684 rs->buf);
9685 }
9686
9687 extended_remote_environment_support (rs);
9688
9689 /* Now restart the remote server. */
9690 run_worked = extended_remote_run (args) != -1;
9691 if (!run_worked)
9692 {
9693 /* vRun was not supported. Fail if we need it to do what the
9694 user requested. */
9695 if (remote_exec_file[0])
9696 error (_("Remote target does not support \"set remote exec-file\""));
9697 if (!args.empty ())
9698 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9699
9700 /* Fall back to "R". */
9701 extended_remote_restart ();
9702 }
9703
9704 if (!have_inferiors ())
9705 {
9706 /* Clean up from the last time we ran, before we mark the target
9707 running again. This will mark breakpoints uninserted, and
9708 get_offsets may insert breakpoints. */
9709 init_thread_list ();
9710 init_wait_for_inferior ();
9711 }
9712
9713 /* vRun's success return is a stop reply. */
9714 stop_reply = run_worked ? rs->buf : NULL;
9715 add_current_inferior_and_thread (stop_reply);
9716
9717 /* Get updated offsets, if the stub uses qOffsets. */
9718 get_offsets ();
9719 }
9720 \f
9721
9722 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9723 the list of conditions (in agent expression bytecode format), if any, the
9724 target needs to evaluate. The output is placed into the packet buffer
9725 started from BUF and ended at BUF_END. */
9726
9727 static int
9728 remote_add_target_side_condition (struct gdbarch *gdbarch,
9729 struct bp_target_info *bp_tgt, char *buf,
9730 char *buf_end)
9731 {
9732 if (bp_tgt->conditions.empty ())
9733 return 0;
9734
9735 buf += strlen (buf);
9736 xsnprintf (buf, buf_end - buf, "%s", ";");
9737 buf++;
9738
9739 /* Send conditions to the target. */
9740 for (agent_expr *aexpr : bp_tgt->conditions)
9741 {
9742 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9743 buf += strlen (buf);
9744 for (int i = 0; i < aexpr->len; ++i)
9745 buf = pack_hex_byte (buf, aexpr->buf[i]);
9746 *buf = '\0';
9747 }
9748 return 0;
9749 }
9750
9751 static void
9752 remote_add_target_side_commands (struct gdbarch *gdbarch,
9753 struct bp_target_info *bp_tgt, char *buf)
9754 {
9755 if (bp_tgt->tcommands.empty ())
9756 return;
9757
9758 buf += strlen (buf);
9759
9760 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9761 buf += strlen (buf);
9762
9763 /* Concatenate all the agent expressions that are commands into the
9764 cmds parameter. */
9765 for (agent_expr *aexpr : bp_tgt->tcommands)
9766 {
9767 sprintf (buf, "X%x,", aexpr->len);
9768 buf += strlen (buf);
9769 for (int i = 0; i < aexpr->len; ++i)
9770 buf = pack_hex_byte (buf, aexpr->buf[i]);
9771 *buf = '\0';
9772 }
9773 }
9774
9775 /* Insert a breakpoint. On targets that have software breakpoint
9776 support, we ask the remote target to do the work; on targets
9777 which don't, we insert a traditional memory breakpoint. */
9778
9779 static int
9780 remote_insert_breakpoint (struct target_ops *ops,
9781 struct gdbarch *gdbarch,
9782 struct bp_target_info *bp_tgt)
9783 {
9784 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9785 If it succeeds, then set the support to PACKET_ENABLE. If it
9786 fails, and the user has explicitly requested the Z support then
9787 report an error, otherwise, mark it disabled and go on. */
9788
9789 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9790 {
9791 CORE_ADDR addr = bp_tgt->reqstd_address;
9792 struct remote_state *rs;
9793 char *p, *endbuf;
9794 int bpsize;
9795
9796 /* Make sure the remote is pointing at the right process, if
9797 necessary. */
9798 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9799 set_general_process ();
9800
9801 rs = get_remote_state ();
9802 p = rs->buf;
9803 endbuf = rs->buf + get_remote_packet_size ();
9804
9805 *(p++) = 'Z';
9806 *(p++) = '0';
9807 *(p++) = ',';
9808 addr = (ULONGEST) remote_address_masked (addr);
9809 p += hexnumstr (p, addr);
9810 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9811
9812 if (remote_supports_cond_breakpoints (ops))
9813 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9814
9815 if (remote_can_run_breakpoint_commands (ops))
9816 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9817
9818 putpkt (rs->buf);
9819 getpkt (&rs->buf, &rs->buf_size, 0);
9820
9821 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9822 {
9823 case PACKET_ERROR:
9824 return -1;
9825 case PACKET_OK:
9826 return 0;
9827 case PACKET_UNKNOWN:
9828 break;
9829 }
9830 }
9831
9832 /* If this breakpoint has target-side commands but this stub doesn't
9833 support Z0 packets, throw error. */
9834 if (!bp_tgt->tcommands.empty ())
9835 throw_error (NOT_SUPPORTED_ERROR, _("\
9836 Target doesn't support breakpoints that have target side commands."));
9837
9838 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9839 }
9840
9841 static int
9842 remote_remove_breakpoint (struct target_ops *ops,
9843 struct gdbarch *gdbarch,
9844 struct bp_target_info *bp_tgt,
9845 enum remove_bp_reason reason)
9846 {
9847 CORE_ADDR addr = bp_tgt->placed_address;
9848 struct remote_state *rs = get_remote_state ();
9849
9850 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9851 {
9852 char *p = rs->buf;
9853 char *endbuf = rs->buf + get_remote_packet_size ();
9854
9855 /* Make sure the remote is pointing at the right process, if
9856 necessary. */
9857 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9858 set_general_process ();
9859
9860 *(p++) = 'z';
9861 *(p++) = '0';
9862 *(p++) = ',';
9863
9864 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9865 p += hexnumstr (p, addr);
9866 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9867
9868 putpkt (rs->buf);
9869 getpkt (&rs->buf, &rs->buf_size, 0);
9870
9871 return (rs->buf[0] == 'E');
9872 }
9873
9874 return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
9875 }
9876
9877 static enum Z_packet_type
9878 watchpoint_to_Z_packet (int type)
9879 {
9880 switch (type)
9881 {
9882 case hw_write:
9883 return Z_PACKET_WRITE_WP;
9884 break;
9885 case hw_read:
9886 return Z_PACKET_READ_WP;
9887 break;
9888 case hw_access:
9889 return Z_PACKET_ACCESS_WP;
9890 break;
9891 default:
9892 internal_error (__FILE__, __LINE__,
9893 _("hw_bp_to_z: bad watchpoint type %d"), type);
9894 }
9895 }
9896
9897 static int
9898 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9899 enum target_hw_bp_type type, struct expression *cond)
9900 {
9901 struct remote_state *rs = get_remote_state ();
9902 char *endbuf = rs->buf + get_remote_packet_size ();
9903 char *p;
9904 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9905
9906 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9907 return 1;
9908
9909 /* Make sure the remote is pointing at the right process, if
9910 necessary. */
9911 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9912 set_general_process ();
9913
9914 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9915 p = strchr (rs->buf, '\0');
9916 addr = remote_address_masked (addr);
9917 p += hexnumstr (p, (ULONGEST) addr);
9918 xsnprintf (p, endbuf - p, ",%x", len);
9919
9920 putpkt (rs->buf);
9921 getpkt (&rs->buf, &rs->buf_size, 0);
9922
9923 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9924 {
9925 case PACKET_ERROR:
9926 return -1;
9927 case PACKET_UNKNOWN:
9928 return 1;
9929 case PACKET_OK:
9930 return 0;
9931 }
9932 internal_error (__FILE__, __LINE__,
9933 _("remote_insert_watchpoint: reached end of function"));
9934 }
9935
9936 static int
9937 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9938 CORE_ADDR start, int length)
9939 {
9940 CORE_ADDR diff = remote_address_masked (addr - start);
9941
9942 return diff < length;
9943 }
9944
9945
9946 static int
9947 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9948 enum target_hw_bp_type type, struct expression *cond)
9949 {
9950 struct remote_state *rs = get_remote_state ();
9951 char *endbuf = rs->buf + get_remote_packet_size ();
9952 char *p;
9953 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9954
9955 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9956 return -1;
9957
9958 /* Make sure the remote is pointing at the right process, if
9959 necessary. */
9960 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9961 set_general_process ();
9962
9963 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9964 p = strchr (rs->buf, '\0');
9965 addr = remote_address_masked (addr);
9966 p += hexnumstr (p, (ULONGEST) addr);
9967 xsnprintf (p, endbuf - p, ",%x", len);
9968 putpkt (rs->buf);
9969 getpkt (&rs->buf, &rs->buf_size, 0);
9970
9971 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9972 {
9973 case PACKET_ERROR:
9974 case PACKET_UNKNOWN:
9975 return -1;
9976 case PACKET_OK:
9977 return 0;
9978 }
9979 internal_error (__FILE__, __LINE__,
9980 _("remote_remove_watchpoint: reached end of function"));
9981 }
9982
9983
9984 int remote_hw_watchpoint_limit = -1;
9985 int remote_hw_watchpoint_length_limit = -1;
9986 int remote_hw_breakpoint_limit = -1;
9987
9988 static int
9989 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9990 CORE_ADDR addr, int len)
9991 {
9992 if (remote_hw_watchpoint_length_limit == 0)
9993 return 0;
9994 else if (remote_hw_watchpoint_length_limit < 0)
9995 return 1;
9996 else if (len <= remote_hw_watchpoint_length_limit)
9997 return 1;
9998 else
9999 return 0;
10000 }
10001
10002 static int
10003 remote_check_watch_resources (struct target_ops *self,
10004 enum bptype type, int cnt, int ot)
10005 {
10006 if (type == bp_hardware_breakpoint)
10007 {
10008 if (remote_hw_breakpoint_limit == 0)
10009 return 0;
10010 else if (remote_hw_breakpoint_limit < 0)
10011 return 1;
10012 else if (cnt <= remote_hw_breakpoint_limit)
10013 return 1;
10014 }
10015 else
10016 {
10017 if (remote_hw_watchpoint_limit == 0)
10018 return 0;
10019 else if (remote_hw_watchpoint_limit < 0)
10020 return 1;
10021 else if (ot)
10022 return -1;
10023 else if (cnt <= remote_hw_watchpoint_limit)
10024 return 1;
10025 }
10026 return -1;
10027 }
10028
10029 /* The to_stopped_by_sw_breakpoint method of target remote. */
10030
10031 static int
10032 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
10033 {
10034 struct thread_info *thread = inferior_thread ();
10035
10036 return (thread->priv != NULL
10037 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
10038 }
10039
10040 /* The to_supports_stopped_by_sw_breakpoint method of target
10041 remote. */
10042
10043 static int
10044 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
10045 {
10046 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10047 }
10048
10049 /* The to_stopped_by_hw_breakpoint method of target remote. */
10050
10051 static int
10052 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
10053 {
10054 struct thread_info *thread = inferior_thread ();
10055
10056 return (thread->priv != NULL
10057 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
10058 }
10059
10060 /* The to_supports_stopped_by_hw_breakpoint method of target
10061 remote. */
10062
10063 static int
10064 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
10065 {
10066 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10067 }
10068
10069 static int
10070 remote_stopped_by_watchpoint (struct target_ops *ops)
10071 {
10072 struct thread_info *thread = inferior_thread ();
10073
10074 return (thread->priv != NULL
10075 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
10076 }
10077
10078 static int
10079 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
10080 {
10081 struct thread_info *thread = inferior_thread ();
10082
10083 if (thread->priv != NULL
10084 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
10085 {
10086 *addr_p = thread->priv->watch_data_address;
10087 return 1;
10088 }
10089
10090 return 0;
10091 }
10092
10093
10094 static int
10095 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10096 struct bp_target_info *bp_tgt)
10097 {
10098 CORE_ADDR addr = bp_tgt->reqstd_address;
10099 struct remote_state *rs;
10100 char *p, *endbuf;
10101 char *message;
10102
10103 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10104 return -1;
10105
10106 /* Make sure the remote is pointing at the right process, if
10107 necessary. */
10108 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10109 set_general_process ();
10110
10111 rs = get_remote_state ();
10112 p = rs->buf;
10113 endbuf = rs->buf + get_remote_packet_size ();
10114
10115 *(p++) = 'Z';
10116 *(p++) = '1';
10117 *(p++) = ',';
10118
10119 addr = remote_address_masked (addr);
10120 p += hexnumstr (p, (ULONGEST) addr);
10121 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10122
10123 if (remote_supports_cond_breakpoints (self))
10124 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10125
10126 if (remote_can_run_breakpoint_commands (self))
10127 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10128
10129 putpkt (rs->buf);
10130 getpkt (&rs->buf, &rs->buf_size, 0);
10131
10132 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10133 {
10134 case PACKET_ERROR:
10135 if (rs->buf[1] == '.')
10136 {
10137 message = strchr (rs->buf + 2, '.');
10138 if (message)
10139 error (_("Remote failure reply: %s"), message + 1);
10140 }
10141 return -1;
10142 case PACKET_UNKNOWN:
10143 return -1;
10144 case PACKET_OK:
10145 return 0;
10146 }
10147 internal_error (__FILE__, __LINE__,
10148 _("remote_insert_hw_breakpoint: reached end of function"));
10149 }
10150
10151
10152 static int
10153 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10154 struct bp_target_info *bp_tgt)
10155 {
10156 CORE_ADDR addr;
10157 struct remote_state *rs = get_remote_state ();
10158 char *p = rs->buf;
10159 char *endbuf = rs->buf + get_remote_packet_size ();
10160
10161 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10162 return -1;
10163
10164 /* Make sure the remote is pointing at the right process, if
10165 necessary. */
10166 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10167 set_general_process ();
10168
10169 *(p++) = 'z';
10170 *(p++) = '1';
10171 *(p++) = ',';
10172
10173 addr = remote_address_masked (bp_tgt->placed_address);
10174 p += hexnumstr (p, (ULONGEST) addr);
10175 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10176
10177 putpkt (rs->buf);
10178 getpkt (&rs->buf, &rs->buf_size, 0);
10179
10180 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10181 {
10182 case PACKET_ERROR:
10183 case PACKET_UNKNOWN:
10184 return -1;
10185 case PACKET_OK:
10186 return 0;
10187 }
10188 internal_error (__FILE__, __LINE__,
10189 _("remote_remove_hw_breakpoint: reached end of function"));
10190 }
10191
10192 /* Verify memory using the "qCRC:" request. */
10193
10194 static int
10195 remote_verify_memory (struct target_ops *ops,
10196 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10197 {
10198 struct remote_state *rs = get_remote_state ();
10199 unsigned long host_crc, target_crc;
10200 char *tmp;
10201
10202 /* It doesn't make sense to use qCRC if the remote target is
10203 connected but not running. */
10204 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10205 {
10206 enum packet_result result;
10207
10208 /* Make sure the remote is pointing at the right process. */
10209 set_general_process ();
10210
10211 /* FIXME: assumes lma can fit into long. */
10212 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10213 (long) lma, (long) size);
10214 putpkt (rs->buf);
10215
10216 /* Be clever; compute the host_crc before waiting for target
10217 reply. */
10218 host_crc = xcrc32 (data, size, 0xffffffff);
10219
10220 getpkt (&rs->buf, &rs->buf_size, 0);
10221
10222 result = packet_ok (rs->buf,
10223 &remote_protocol_packets[PACKET_qCRC]);
10224 if (result == PACKET_ERROR)
10225 return -1;
10226 else if (result == PACKET_OK)
10227 {
10228 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10229 target_crc = target_crc * 16 + fromhex (*tmp);
10230
10231 return (host_crc == target_crc);
10232 }
10233 }
10234
10235 return simple_verify_memory (ops, data, lma, size);
10236 }
10237
10238 /* compare-sections command
10239
10240 With no arguments, compares each loadable section in the exec bfd
10241 with the same memory range on the target, and reports mismatches.
10242 Useful for verifying the image on the target against the exec file. */
10243
10244 static void
10245 compare_sections_command (char *args, int from_tty)
10246 {
10247 asection *s;
10248 struct cleanup *old_chain;
10249 gdb_byte *sectdata;
10250 const char *sectname;
10251 bfd_size_type size;
10252 bfd_vma lma;
10253 int matched = 0;
10254 int mismatched = 0;
10255 int res;
10256 int read_only = 0;
10257
10258 if (!exec_bfd)
10259 error (_("command cannot be used without an exec file"));
10260
10261 /* Make sure the remote is pointing at the right process. */
10262 set_general_process ();
10263
10264 if (args != NULL && strcmp (args, "-r") == 0)
10265 {
10266 read_only = 1;
10267 args = NULL;
10268 }
10269
10270 for (s = exec_bfd->sections; s; s = s->next)
10271 {
10272 if (!(s->flags & SEC_LOAD))
10273 continue; /* Skip non-loadable section. */
10274
10275 if (read_only && (s->flags & SEC_READONLY) == 0)
10276 continue; /* Skip writeable sections */
10277
10278 size = bfd_get_section_size (s);
10279 if (size == 0)
10280 continue; /* Skip zero-length section. */
10281
10282 sectname = bfd_get_section_name (exec_bfd, s);
10283 if (args && strcmp (args, sectname) != 0)
10284 continue; /* Not the section selected by user. */
10285
10286 matched = 1; /* Do this section. */
10287 lma = s->lma;
10288
10289 sectdata = (gdb_byte *) xmalloc (size);
10290 old_chain = make_cleanup (xfree, sectdata);
10291 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
10292
10293 res = target_verify_memory (sectdata, lma, size);
10294
10295 if (res == -1)
10296 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10297 paddress (target_gdbarch (), lma),
10298 paddress (target_gdbarch (), lma + size));
10299
10300 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10301 paddress (target_gdbarch (), lma),
10302 paddress (target_gdbarch (), lma + size));
10303 if (res)
10304 printf_filtered ("matched.\n");
10305 else
10306 {
10307 printf_filtered ("MIS-MATCHED!\n");
10308 mismatched++;
10309 }
10310
10311 do_cleanups (old_chain);
10312 }
10313 if (mismatched > 0)
10314 warning (_("One or more sections of the target image does not match\n\
10315 the loaded file\n"));
10316 if (args && !matched)
10317 printf_filtered (_("No loaded section named '%s'.\n"), args);
10318 }
10319
10320 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10321 into remote target. The number of bytes written to the remote
10322 target is returned, or -1 for error. */
10323
10324 static enum target_xfer_status
10325 remote_write_qxfer (struct target_ops *ops, const char *object_name,
10326 const char *annex, const gdb_byte *writebuf,
10327 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10328 struct packet_config *packet)
10329 {
10330 int i, buf_len;
10331 ULONGEST n;
10332 struct remote_state *rs = get_remote_state ();
10333 int max_size = get_memory_write_packet_size ();
10334
10335 if (packet->support == PACKET_DISABLE)
10336 return TARGET_XFER_E_IO;
10337
10338 /* Insert header. */
10339 i = snprintf (rs->buf, max_size,
10340 "qXfer:%s:write:%s:%s:",
10341 object_name, annex ? annex : "",
10342 phex_nz (offset, sizeof offset));
10343 max_size -= (i + 1);
10344
10345 /* Escape as much data as fits into rs->buf. */
10346 buf_len = remote_escape_output
10347 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10348
10349 if (putpkt_binary (rs->buf, i + buf_len) < 0
10350 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10351 || packet_ok (rs->buf, packet) != PACKET_OK)
10352 return TARGET_XFER_E_IO;
10353
10354 unpack_varlen_hex (rs->buf, &n);
10355
10356 *xfered_len = n;
10357 return TARGET_XFER_OK;
10358 }
10359
10360 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10361 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10362 number of bytes read is returned, or 0 for EOF, or -1 for error.
10363 The number of bytes read may be less than LEN without indicating an
10364 EOF. PACKET is checked and updated to indicate whether the remote
10365 target supports this object. */
10366
10367 static enum target_xfer_status
10368 remote_read_qxfer (struct target_ops *ops, const char *object_name,
10369 const char *annex,
10370 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10371 ULONGEST *xfered_len,
10372 struct packet_config *packet)
10373 {
10374 struct remote_state *rs = get_remote_state ();
10375 LONGEST i, n, packet_len;
10376
10377 if (packet->support == PACKET_DISABLE)
10378 return TARGET_XFER_E_IO;
10379
10380 /* Check whether we've cached an end-of-object packet that matches
10381 this request. */
10382 if (rs->finished_object)
10383 {
10384 if (strcmp (object_name, rs->finished_object) == 0
10385 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10386 && offset == rs->finished_offset)
10387 return TARGET_XFER_EOF;
10388
10389
10390 /* Otherwise, we're now reading something different. Discard
10391 the cache. */
10392 xfree (rs->finished_object);
10393 xfree (rs->finished_annex);
10394 rs->finished_object = NULL;
10395 rs->finished_annex = NULL;
10396 }
10397
10398 /* Request only enough to fit in a single packet. The actual data
10399 may not, since we don't know how much of it will need to be escaped;
10400 the target is free to respond with slightly less data. We subtract
10401 five to account for the response type and the protocol frame. */
10402 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10403 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10404 object_name, annex ? annex : "",
10405 phex_nz (offset, sizeof offset),
10406 phex_nz (n, sizeof n));
10407 i = putpkt (rs->buf);
10408 if (i < 0)
10409 return TARGET_XFER_E_IO;
10410
10411 rs->buf[0] = '\0';
10412 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10413 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10414 return TARGET_XFER_E_IO;
10415
10416 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10417 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10418
10419 /* 'm' means there is (or at least might be) more data after this
10420 batch. That does not make sense unless there's at least one byte
10421 of data in this reply. */
10422 if (rs->buf[0] == 'm' && packet_len == 1)
10423 error (_("Remote qXfer reply contained no data."));
10424
10425 /* Got some data. */
10426 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10427 packet_len - 1, readbuf, n);
10428
10429 /* 'l' is an EOF marker, possibly including a final block of data,
10430 or possibly empty. If we have the final block of a non-empty
10431 object, record this fact to bypass a subsequent partial read. */
10432 if (rs->buf[0] == 'l' && offset + i > 0)
10433 {
10434 rs->finished_object = xstrdup (object_name);
10435 rs->finished_annex = xstrdup (annex ? annex : "");
10436 rs->finished_offset = offset + i;
10437 }
10438
10439 if (i == 0)
10440 return TARGET_XFER_EOF;
10441 else
10442 {
10443 *xfered_len = i;
10444 return TARGET_XFER_OK;
10445 }
10446 }
10447
10448 static enum target_xfer_status
10449 remote_xfer_partial (struct target_ops *ops, enum target_object object,
10450 const char *annex, gdb_byte *readbuf,
10451 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10452 ULONGEST *xfered_len)
10453 {
10454 struct remote_state *rs;
10455 int i;
10456 char *p2;
10457 char query_type;
10458 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10459
10460 set_remote_traceframe ();
10461 set_general_thread (inferior_ptid);
10462
10463 rs = get_remote_state ();
10464
10465 /* Handle memory using the standard memory routines. */
10466 if (object == TARGET_OBJECT_MEMORY)
10467 {
10468 /* If the remote target is connected but not running, we should
10469 pass this request down to a lower stratum (e.g. the executable
10470 file). */
10471 if (!target_has_execution)
10472 return TARGET_XFER_EOF;
10473
10474 if (writebuf != NULL)
10475 return remote_write_bytes (offset, writebuf, len, unit_size,
10476 xfered_len);
10477 else
10478 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10479 xfered_len);
10480 }
10481
10482 /* Handle SPU memory using qxfer packets. */
10483 if (object == TARGET_OBJECT_SPU)
10484 {
10485 if (readbuf)
10486 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
10487 xfered_len, &remote_protocol_packets
10488 [PACKET_qXfer_spu_read]);
10489 else
10490 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
10491 xfered_len, &remote_protocol_packets
10492 [PACKET_qXfer_spu_write]);
10493 }
10494
10495 /* Handle extra signal info using qxfer packets. */
10496 if (object == TARGET_OBJECT_SIGNAL_INFO)
10497 {
10498 if (readbuf)
10499 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10500 xfered_len, &remote_protocol_packets
10501 [PACKET_qXfer_siginfo_read]);
10502 else
10503 return remote_write_qxfer (ops, "siginfo", annex,
10504 writebuf, offset, len, xfered_len,
10505 &remote_protocol_packets
10506 [PACKET_qXfer_siginfo_write]);
10507 }
10508
10509 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10510 {
10511 if (readbuf)
10512 return remote_read_qxfer (ops, "statictrace", annex,
10513 readbuf, offset, len, xfered_len,
10514 &remote_protocol_packets
10515 [PACKET_qXfer_statictrace_read]);
10516 else
10517 return TARGET_XFER_E_IO;
10518 }
10519
10520 /* Only handle flash writes. */
10521 if (writebuf != NULL)
10522 {
10523 switch (object)
10524 {
10525 case TARGET_OBJECT_FLASH:
10526 return remote_flash_write (ops, offset, len, xfered_len,
10527 writebuf);
10528
10529 default:
10530 return TARGET_XFER_E_IO;
10531 }
10532 }
10533
10534 /* Map pre-existing objects onto letters. DO NOT do this for new
10535 objects!!! Instead specify new query packets. */
10536 switch (object)
10537 {
10538 case TARGET_OBJECT_AVR:
10539 query_type = 'R';
10540 break;
10541
10542 case TARGET_OBJECT_AUXV:
10543 gdb_assert (annex == NULL);
10544 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10545 xfered_len,
10546 &remote_protocol_packets[PACKET_qXfer_auxv]);
10547
10548 case TARGET_OBJECT_AVAILABLE_FEATURES:
10549 return remote_read_qxfer
10550 (ops, "features", annex, readbuf, offset, len, xfered_len,
10551 &remote_protocol_packets[PACKET_qXfer_features]);
10552
10553 case TARGET_OBJECT_LIBRARIES:
10554 return remote_read_qxfer
10555 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10556 &remote_protocol_packets[PACKET_qXfer_libraries]);
10557
10558 case TARGET_OBJECT_LIBRARIES_SVR4:
10559 return remote_read_qxfer
10560 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10561 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10562
10563 case TARGET_OBJECT_MEMORY_MAP:
10564 gdb_assert (annex == NULL);
10565 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10566 xfered_len,
10567 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10568
10569 case TARGET_OBJECT_OSDATA:
10570 /* Should only get here if we're connected. */
10571 gdb_assert (rs->remote_desc);
10572 return remote_read_qxfer
10573 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10574 &remote_protocol_packets[PACKET_qXfer_osdata]);
10575
10576 case TARGET_OBJECT_THREADS:
10577 gdb_assert (annex == NULL);
10578 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10579 xfered_len,
10580 &remote_protocol_packets[PACKET_qXfer_threads]);
10581
10582 case TARGET_OBJECT_TRACEFRAME_INFO:
10583 gdb_assert (annex == NULL);
10584 return remote_read_qxfer
10585 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10586 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10587
10588 case TARGET_OBJECT_FDPIC:
10589 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10590 xfered_len,
10591 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10592
10593 case TARGET_OBJECT_OPENVMS_UIB:
10594 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10595 xfered_len,
10596 &remote_protocol_packets[PACKET_qXfer_uib]);
10597
10598 case TARGET_OBJECT_BTRACE:
10599 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10600 xfered_len,
10601 &remote_protocol_packets[PACKET_qXfer_btrace]);
10602
10603 case TARGET_OBJECT_BTRACE_CONF:
10604 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10605 len, xfered_len,
10606 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10607
10608 case TARGET_OBJECT_EXEC_FILE:
10609 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10610 len, xfered_len,
10611 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10612
10613 default:
10614 return TARGET_XFER_E_IO;
10615 }
10616
10617 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10618 large enough let the caller deal with it. */
10619 if (len < get_remote_packet_size ())
10620 return TARGET_XFER_E_IO;
10621 len = get_remote_packet_size ();
10622
10623 /* Except for querying the minimum buffer size, target must be open. */
10624 if (!rs->remote_desc)
10625 error (_("remote query is only available after target open"));
10626
10627 gdb_assert (annex != NULL);
10628 gdb_assert (readbuf != NULL);
10629
10630 p2 = rs->buf;
10631 *p2++ = 'q';
10632 *p2++ = query_type;
10633
10634 /* We used one buffer char for the remote protocol q command and
10635 another for the query type. As the remote protocol encapsulation
10636 uses 4 chars plus one extra in case we are debugging
10637 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10638 string. */
10639 i = 0;
10640 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10641 {
10642 /* Bad caller may have sent forbidden characters. */
10643 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10644 *p2++ = annex[i];
10645 i++;
10646 }
10647 *p2 = '\0';
10648 gdb_assert (annex[i] == '\0');
10649
10650 i = putpkt (rs->buf);
10651 if (i < 0)
10652 return TARGET_XFER_E_IO;
10653
10654 getpkt (&rs->buf, &rs->buf_size, 0);
10655 strcpy ((char *) readbuf, rs->buf);
10656
10657 *xfered_len = strlen ((char *) readbuf);
10658 return TARGET_XFER_OK;
10659 }
10660
10661 /* Implementation of to_get_memory_xfer_limit. */
10662
10663 static ULONGEST
10664 remote_get_memory_xfer_limit (struct target_ops *ops)
10665 {
10666 return get_memory_write_packet_size ();
10667 }
10668
10669 static int
10670 remote_search_memory (struct target_ops* ops,
10671 CORE_ADDR start_addr, ULONGEST search_space_len,
10672 const gdb_byte *pattern, ULONGEST pattern_len,
10673 CORE_ADDR *found_addrp)
10674 {
10675 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10676 struct remote_state *rs = get_remote_state ();
10677 int max_size = get_memory_write_packet_size ();
10678 struct packet_config *packet =
10679 &remote_protocol_packets[PACKET_qSearch_memory];
10680 /* Number of packet bytes used to encode the pattern;
10681 this could be more than PATTERN_LEN due to escape characters. */
10682 int escaped_pattern_len;
10683 /* Amount of pattern that was encodable in the packet. */
10684 int used_pattern_len;
10685 int i;
10686 int found;
10687 ULONGEST found_addr;
10688
10689 /* Don't go to the target if we don't have to.
10690 This is done before checking packet->support to avoid the possibility that
10691 a success for this edge case means the facility works in general. */
10692 if (pattern_len > search_space_len)
10693 return 0;
10694 if (pattern_len == 0)
10695 {
10696 *found_addrp = start_addr;
10697 return 1;
10698 }
10699
10700 /* If we already know the packet isn't supported, fall back to the simple
10701 way of searching memory. */
10702
10703 if (packet_config_support (packet) == PACKET_DISABLE)
10704 {
10705 /* Target doesn't provided special support, fall back and use the
10706 standard support (copy memory and do the search here). */
10707 return simple_search_memory (ops, start_addr, search_space_len,
10708 pattern, pattern_len, found_addrp);
10709 }
10710
10711 /* Make sure the remote is pointing at the right process. */
10712 set_general_process ();
10713
10714 /* Insert header. */
10715 i = snprintf (rs->buf, max_size,
10716 "qSearch:memory:%s;%s;",
10717 phex_nz (start_addr, addr_size),
10718 phex_nz (search_space_len, sizeof (search_space_len)));
10719 max_size -= (i + 1);
10720
10721 /* Escape as much data as fits into rs->buf. */
10722 escaped_pattern_len =
10723 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10724 &used_pattern_len, max_size);
10725
10726 /* Bail if the pattern is too large. */
10727 if (used_pattern_len != pattern_len)
10728 error (_("Pattern is too large to transmit to remote target."));
10729
10730 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10731 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10732 || packet_ok (rs->buf, packet) != PACKET_OK)
10733 {
10734 /* The request may not have worked because the command is not
10735 supported. If so, fall back to the simple way. */
10736 if (packet->support == PACKET_DISABLE)
10737 {
10738 return simple_search_memory (ops, start_addr, search_space_len,
10739 pattern, pattern_len, found_addrp);
10740 }
10741 return -1;
10742 }
10743
10744 if (rs->buf[0] == '0')
10745 found = 0;
10746 else if (rs->buf[0] == '1')
10747 {
10748 found = 1;
10749 if (rs->buf[1] != ',')
10750 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10751 unpack_varlen_hex (rs->buf + 2, &found_addr);
10752 *found_addrp = found_addr;
10753 }
10754 else
10755 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10756
10757 return found;
10758 }
10759
10760 static void
10761 remote_rcmd (struct target_ops *self, const char *command,
10762 struct ui_file *outbuf)
10763 {
10764 struct remote_state *rs = get_remote_state ();
10765 char *p = rs->buf;
10766
10767 if (!rs->remote_desc)
10768 error (_("remote rcmd is only available after target open"));
10769
10770 /* Send a NULL command across as an empty command. */
10771 if (command == NULL)
10772 command = "";
10773
10774 /* The query prefix. */
10775 strcpy (rs->buf, "qRcmd,");
10776 p = strchr (rs->buf, '\0');
10777
10778 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10779 > get_remote_packet_size ())
10780 error (_("\"monitor\" command ``%s'' is too long."), command);
10781
10782 /* Encode the actual command. */
10783 bin2hex ((const gdb_byte *) command, p, strlen (command));
10784
10785 if (putpkt (rs->buf) < 0)
10786 error (_("Communication problem with target."));
10787
10788 /* get/display the response */
10789 while (1)
10790 {
10791 char *buf;
10792
10793 /* XXX - see also remote_get_noisy_reply(). */
10794 QUIT; /* Allow user to bail out with ^C. */
10795 rs->buf[0] = '\0';
10796 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10797 {
10798 /* Timeout. Continue to (try to) read responses.
10799 This is better than stopping with an error, assuming the stub
10800 is still executing the (long) monitor command.
10801 If needed, the user can interrupt gdb using C-c, obtaining
10802 an effect similar to stop on timeout. */
10803 continue;
10804 }
10805 buf = rs->buf;
10806 if (buf[0] == '\0')
10807 error (_("Target does not support this command."));
10808 if (buf[0] == 'O' && buf[1] != 'K')
10809 {
10810 remote_console_output (buf + 1); /* 'O' message from stub. */
10811 continue;
10812 }
10813 if (strcmp (buf, "OK") == 0)
10814 break;
10815 if (strlen (buf) == 3 && buf[0] == 'E'
10816 && isdigit (buf[1]) && isdigit (buf[2]))
10817 {
10818 error (_("Protocol error with Rcmd"));
10819 }
10820 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10821 {
10822 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10823
10824 fputc_unfiltered (c, outbuf);
10825 }
10826 break;
10827 }
10828 }
10829
10830 static VEC(mem_region_s) *
10831 remote_memory_map (struct target_ops *ops)
10832 {
10833 VEC(mem_region_s) *result = NULL;
10834 char *text = target_read_stralloc (&current_target,
10835 TARGET_OBJECT_MEMORY_MAP, NULL);
10836
10837 if (text)
10838 {
10839 struct cleanup *back_to = make_cleanup (xfree, text);
10840
10841 result = parse_memory_map (text);
10842 do_cleanups (back_to);
10843 }
10844
10845 return result;
10846 }
10847
10848 static void
10849 packet_command (char *args, int from_tty)
10850 {
10851 struct remote_state *rs = get_remote_state ();
10852
10853 if (!rs->remote_desc)
10854 error (_("command can only be used with remote target"));
10855
10856 if (!args)
10857 error (_("remote-packet command requires packet text as argument"));
10858
10859 puts_filtered ("sending: ");
10860 print_packet (args);
10861 puts_filtered ("\n");
10862 putpkt (args);
10863
10864 getpkt (&rs->buf, &rs->buf_size, 0);
10865 puts_filtered ("received: ");
10866 print_packet (rs->buf);
10867 puts_filtered ("\n");
10868 }
10869
10870 #if 0
10871 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10872
10873 static void display_thread_info (struct gdb_ext_thread_info *info);
10874
10875 static void threadset_test_cmd (char *cmd, int tty);
10876
10877 static void threadalive_test (char *cmd, int tty);
10878
10879 static void threadlist_test_cmd (char *cmd, int tty);
10880
10881 int get_and_display_threadinfo (threadref *ref);
10882
10883 static void threadinfo_test_cmd (char *cmd, int tty);
10884
10885 static int thread_display_step (threadref *ref, void *context);
10886
10887 static void threadlist_update_test_cmd (char *cmd, int tty);
10888
10889 static void init_remote_threadtests (void);
10890
10891 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10892
10893 static void
10894 threadset_test_cmd (char *cmd, int tty)
10895 {
10896 int sample_thread = SAMPLE_THREAD;
10897
10898 printf_filtered (_("Remote threadset test\n"));
10899 set_general_thread (sample_thread);
10900 }
10901
10902
10903 static void
10904 threadalive_test (char *cmd, int tty)
10905 {
10906 int sample_thread = SAMPLE_THREAD;
10907 int pid = ptid_get_pid (inferior_ptid);
10908 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10909
10910 if (remote_thread_alive (ptid))
10911 printf_filtered ("PASS: Thread alive test\n");
10912 else
10913 printf_filtered ("FAIL: Thread alive test\n");
10914 }
10915
10916 void output_threadid (char *title, threadref *ref);
10917
10918 void
10919 output_threadid (char *title, threadref *ref)
10920 {
10921 char hexid[20];
10922
10923 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10924 hexid[16] = 0;
10925 printf_filtered ("%s %s\n", title, (&hexid[0]));
10926 }
10927
10928 static void
10929 threadlist_test_cmd (char *cmd, int tty)
10930 {
10931 int startflag = 1;
10932 threadref nextthread;
10933 int done, result_count;
10934 threadref threadlist[3];
10935
10936 printf_filtered ("Remote Threadlist test\n");
10937 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10938 &result_count, &threadlist[0]))
10939 printf_filtered ("FAIL: threadlist test\n");
10940 else
10941 {
10942 threadref *scan = threadlist;
10943 threadref *limit = scan + result_count;
10944
10945 while (scan < limit)
10946 output_threadid (" thread ", scan++);
10947 }
10948 }
10949
10950 void
10951 display_thread_info (struct gdb_ext_thread_info *info)
10952 {
10953 output_threadid ("Threadid: ", &info->threadid);
10954 printf_filtered ("Name: %s\n ", info->shortname);
10955 printf_filtered ("State: %s\n", info->display);
10956 printf_filtered ("other: %s\n\n", info->more_display);
10957 }
10958
10959 int
10960 get_and_display_threadinfo (threadref *ref)
10961 {
10962 int result;
10963 int set;
10964 struct gdb_ext_thread_info threadinfo;
10965
10966 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10967 | TAG_MOREDISPLAY | TAG_DISPLAY;
10968 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10969 display_thread_info (&threadinfo);
10970 return result;
10971 }
10972
10973 static void
10974 threadinfo_test_cmd (char *cmd, int tty)
10975 {
10976 int athread = SAMPLE_THREAD;
10977 threadref thread;
10978 int set;
10979
10980 int_to_threadref (&thread, athread);
10981 printf_filtered ("Remote Threadinfo test\n");
10982 if (!get_and_display_threadinfo (&thread))
10983 printf_filtered ("FAIL cannot get thread info\n");
10984 }
10985
10986 static int
10987 thread_display_step (threadref *ref, void *context)
10988 {
10989 /* output_threadid(" threadstep ",ref); *//* simple test */
10990 return get_and_display_threadinfo (ref);
10991 }
10992
10993 static void
10994 threadlist_update_test_cmd (char *cmd, int tty)
10995 {
10996 printf_filtered ("Remote Threadlist update test\n");
10997 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10998 }
10999
11000 static void
11001 init_remote_threadtests (void)
11002 {
11003 add_com ("tlist", class_obscure, threadlist_test_cmd,
11004 _("Fetch and print the remote list of "
11005 "thread identifiers, one pkt only"));
11006 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11007 _("Fetch and display info about one thread"));
11008 add_com ("tset", class_obscure, threadset_test_cmd,
11009 _("Test setting to a different thread"));
11010 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11011 _("Iterate through updating all remote thread info"));
11012 add_com ("talive", class_obscure, threadalive_test,
11013 _(" Remote thread alive test "));
11014 }
11015
11016 #endif /* 0 */
11017
11018 /* Convert a thread ID to a string. Returns the string in a static
11019 buffer. */
11020
11021 static const char *
11022 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
11023 {
11024 static char buf[64];
11025 struct remote_state *rs = get_remote_state ();
11026
11027 if (ptid_equal (ptid, null_ptid))
11028 return normal_pid_to_str (ptid);
11029 else if (ptid_is_pid (ptid))
11030 {
11031 /* Printing an inferior target id. */
11032
11033 /* When multi-process extensions are off, there's no way in the
11034 remote protocol to know the remote process id, if there's any
11035 at all. There's one exception --- when we're connected with
11036 target extended-remote, and we manually attached to a process
11037 with "attach PID". We don't record anywhere a flag that
11038 allows us to distinguish that case from the case of
11039 connecting with extended-remote and the stub already being
11040 attached to a process, and reporting yes to qAttached, hence
11041 no smart special casing here. */
11042 if (!remote_multi_process_p (rs))
11043 {
11044 xsnprintf (buf, sizeof buf, "Remote target");
11045 return buf;
11046 }
11047
11048 return normal_pid_to_str (ptid);
11049 }
11050 else
11051 {
11052 if (ptid_equal (magic_null_ptid, ptid))
11053 xsnprintf (buf, sizeof buf, "Thread <main>");
11054 else if (remote_multi_process_p (rs))
11055 if (ptid_get_lwp (ptid) == 0)
11056 return normal_pid_to_str (ptid);
11057 else
11058 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11059 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11060 else
11061 xsnprintf (buf, sizeof buf, "Thread %ld",
11062 ptid_get_lwp (ptid));
11063 return buf;
11064 }
11065 }
11066
11067 /* Get the address of the thread local variable in OBJFILE which is
11068 stored at OFFSET within the thread local storage for thread PTID. */
11069
11070 static CORE_ADDR
11071 remote_get_thread_local_address (struct target_ops *ops,
11072 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
11073 {
11074 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11075 {
11076 struct remote_state *rs = get_remote_state ();
11077 char *p = rs->buf;
11078 char *endp = rs->buf + get_remote_packet_size ();
11079 enum packet_result result;
11080
11081 strcpy (p, "qGetTLSAddr:");
11082 p += strlen (p);
11083 p = write_ptid (p, endp, ptid);
11084 *p++ = ',';
11085 p += hexnumstr (p, offset);
11086 *p++ = ',';
11087 p += hexnumstr (p, lm);
11088 *p++ = '\0';
11089
11090 putpkt (rs->buf);
11091 getpkt (&rs->buf, &rs->buf_size, 0);
11092 result = packet_ok (rs->buf,
11093 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11094 if (result == PACKET_OK)
11095 {
11096 ULONGEST result;
11097
11098 unpack_varlen_hex (rs->buf, &result);
11099 return result;
11100 }
11101 else if (result == PACKET_UNKNOWN)
11102 throw_error (TLS_GENERIC_ERROR,
11103 _("Remote target doesn't support qGetTLSAddr packet"));
11104 else
11105 throw_error (TLS_GENERIC_ERROR,
11106 _("Remote target failed to process qGetTLSAddr request"));
11107 }
11108 else
11109 throw_error (TLS_GENERIC_ERROR,
11110 _("TLS not supported or disabled on this target"));
11111 /* Not reached. */
11112 return 0;
11113 }
11114
11115 /* Provide thread local base, i.e. Thread Information Block address.
11116 Returns 1 if ptid is found and thread_local_base is non zero. */
11117
11118 static int
11119 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
11120 {
11121 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11122 {
11123 struct remote_state *rs = get_remote_state ();
11124 char *p = rs->buf;
11125 char *endp = rs->buf + get_remote_packet_size ();
11126 enum packet_result result;
11127
11128 strcpy (p, "qGetTIBAddr:");
11129 p += strlen (p);
11130 p = write_ptid (p, endp, ptid);
11131 *p++ = '\0';
11132
11133 putpkt (rs->buf);
11134 getpkt (&rs->buf, &rs->buf_size, 0);
11135 result = packet_ok (rs->buf,
11136 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11137 if (result == PACKET_OK)
11138 {
11139 ULONGEST result;
11140
11141 unpack_varlen_hex (rs->buf, &result);
11142 if (addr)
11143 *addr = (CORE_ADDR) result;
11144 return 1;
11145 }
11146 else if (result == PACKET_UNKNOWN)
11147 error (_("Remote target doesn't support qGetTIBAddr packet"));
11148 else
11149 error (_("Remote target failed to process qGetTIBAddr request"));
11150 }
11151 else
11152 error (_("qGetTIBAddr not supported or disabled on this target"));
11153 /* Not reached. */
11154 return 0;
11155 }
11156
11157 /* Support for inferring a target description based on the current
11158 architecture and the size of a 'g' packet. While the 'g' packet
11159 can have any size (since optional registers can be left off the
11160 end), some sizes are easily recognizable given knowledge of the
11161 approximate architecture. */
11162
11163 struct remote_g_packet_guess
11164 {
11165 int bytes;
11166 const struct target_desc *tdesc;
11167 };
11168 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11169 DEF_VEC_O(remote_g_packet_guess_s);
11170
11171 struct remote_g_packet_data
11172 {
11173 VEC(remote_g_packet_guess_s) *guesses;
11174 };
11175
11176 static struct gdbarch_data *remote_g_packet_data_handle;
11177
11178 static void *
11179 remote_g_packet_data_init (struct obstack *obstack)
11180 {
11181 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11182 }
11183
11184 void
11185 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11186 const struct target_desc *tdesc)
11187 {
11188 struct remote_g_packet_data *data
11189 = ((struct remote_g_packet_data *)
11190 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11191 struct remote_g_packet_guess new_guess, *guess;
11192 int ix;
11193
11194 gdb_assert (tdesc != NULL);
11195
11196 for (ix = 0;
11197 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11198 ix++)
11199 if (guess->bytes == bytes)
11200 internal_error (__FILE__, __LINE__,
11201 _("Duplicate g packet description added for size %d"),
11202 bytes);
11203
11204 new_guess.bytes = bytes;
11205 new_guess.tdesc = tdesc;
11206 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11207 }
11208
11209 /* Return 1 if remote_read_description would do anything on this target
11210 and architecture, 0 otherwise. */
11211
11212 static int
11213 remote_read_description_p (struct target_ops *target)
11214 {
11215 struct remote_g_packet_data *data
11216 = ((struct remote_g_packet_data *)
11217 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11218
11219 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11220 return 1;
11221
11222 return 0;
11223 }
11224
11225 static const struct target_desc *
11226 remote_read_description (struct target_ops *target)
11227 {
11228 struct remote_g_packet_data *data
11229 = ((struct remote_g_packet_data *)
11230 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11231
11232 /* Do not try this during initial connection, when we do not know
11233 whether there is a running but stopped thread. */
11234 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11235 return target->beneath->to_read_description (target->beneath);
11236
11237 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11238 {
11239 struct remote_g_packet_guess *guess;
11240 int ix;
11241 int bytes = send_g_packet ();
11242
11243 for (ix = 0;
11244 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11245 ix++)
11246 if (guess->bytes == bytes)
11247 return guess->tdesc;
11248
11249 /* We discard the g packet. A minor optimization would be to
11250 hold on to it, and fill the register cache once we have selected
11251 an architecture, but it's too tricky to do safely. */
11252 }
11253
11254 return target->beneath->to_read_description (target->beneath);
11255 }
11256
11257 /* Remote file transfer support. This is host-initiated I/O, not
11258 target-initiated; for target-initiated, see remote-fileio.c. */
11259
11260 /* If *LEFT is at least the length of STRING, copy STRING to
11261 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11262 decrease *LEFT. Otherwise raise an error. */
11263
11264 static void
11265 remote_buffer_add_string (char **buffer, int *left, const char *string)
11266 {
11267 int len = strlen (string);
11268
11269 if (len > *left)
11270 error (_("Packet too long for target."));
11271
11272 memcpy (*buffer, string, len);
11273 *buffer += len;
11274 *left -= len;
11275
11276 /* NUL-terminate the buffer as a convenience, if there is
11277 room. */
11278 if (*left)
11279 **buffer = '\0';
11280 }
11281
11282 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11283 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11284 decrease *LEFT. Otherwise raise an error. */
11285
11286 static void
11287 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11288 int len)
11289 {
11290 if (2 * len > *left)
11291 error (_("Packet too long for target."));
11292
11293 bin2hex (bytes, *buffer, len);
11294 *buffer += 2 * len;
11295 *left -= 2 * len;
11296
11297 /* NUL-terminate the buffer as a convenience, if there is
11298 room. */
11299 if (*left)
11300 **buffer = '\0';
11301 }
11302
11303 /* If *LEFT is large enough, convert VALUE to hex and add it to
11304 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11305 decrease *LEFT. Otherwise raise an error. */
11306
11307 static void
11308 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11309 {
11310 int len = hexnumlen (value);
11311
11312 if (len > *left)
11313 error (_("Packet too long for target."));
11314
11315 hexnumstr (*buffer, value);
11316 *buffer += len;
11317 *left -= len;
11318
11319 /* NUL-terminate the buffer as a convenience, if there is
11320 room. */
11321 if (*left)
11322 **buffer = '\0';
11323 }
11324
11325 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11326 value, *REMOTE_ERRNO to the remote error number or zero if none
11327 was included, and *ATTACHMENT to point to the start of the annex
11328 if any. The length of the packet isn't needed here; there may
11329 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11330
11331 Return 0 if the packet could be parsed, -1 if it could not. If
11332 -1 is returned, the other variables may not be initialized. */
11333
11334 static int
11335 remote_hostio_parse_result (char *buffer, int *retcode,
11336 int *remote_errno, char **attachment)
11337 {
11338 char *p, *p2;
11339
11340 *remote_errno = 0;
11341 *attachment = NULL;
11342
11343 if (buffer[0] != 'F')
11344 return -1;
11345
11346 errno = 0;
11347 *retcode = strtol (&buffer[1], &p, 16);
11348 if (errno != 0 || p == &buffer[1])
11349 return -1;
11350
11351 /* Check for ",errno". */
11352 if (*p == ',')
11353 {
11354 errno = 0;
11355 *remote_errno = strtol (p + 1, &p2, 16);
11356 if (errno != 0 || p + 1 == p2)
11357 return -1;
11358 p = p2;
11359 }
11360
11361 /* Check for ";attachment". If there is no attachment, the
11362 packet should end here. */
11363 if (*p == ';')
11364 {
11365 *attachment = p + 1;
11366 return 0;
11367 }
11368 else if (*p == '\0')
11369 return 0;
11370 else
11371 return -1;
11372 }
11373
11374 /* Send a prepared I/O packet to the target and read its response.
11375 The prepared packet is in the global RS->BUF before this function
11376 is called, and the answer is there when we return.
11377
11378 COMMAND_BYTES is the length of the request to send, which may include
11379 binary data. WHICH_PACKET is the packet configuration to check
11380 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11381 is set to the error number and -1 is returned. Otherwise the value
11382 returned by the function is returned.
11383
11384 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11385 attachment is expected; an error will be reported if there's a
11386 mismatch. If one is found, *ATTACHMENT will be set to point into
11387 the packet buffer and *ATTACHMENT_LEN will be set to the
11388 attachment's length. */
11389
11390 static int
11391 remote_hostio_send_command (int command_bytes, int which_packet,
11392 int *remote_errno, char **attachment,
11393 int *attachment_len)
11394 {
11395 struct remote_state *rs = get_remote_state ();
11396 int ret, bytes_read;
11397 char *attachment_tmp;
11398
11399 if (!rs->remote_desc
11400 || packet_support (which_packet) == PACKET_DISABLE)
11401 {
11402 *remote_errno = FILEIO_ENOSYS;
11403 return -1;
11404 }
11405
11406 putpkt_binary (rs->buf, command_bytes);
11407 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11408
11409 /* If it timed out, something is wrong. Don't try to parse the
11410 buffer. */
11411 if (bytes_read < 0)
11412 {
11413 *remote_errno = FILEIO_EINVAL;
11414 return -1;
11415 }
11416
11417 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11418 {
11419 case PACKET_ERROR:
11420 *remote_errno = FILEIO_EINVAL;
11421 return -1;
11422 case PACKET_UNKNOWN:
11423 *remote_errno = FILEIO_ENOSYS;
11424 return -1;
11425 case PACKET_OK:
11426 break;
11427 }
11428
11429 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11430 &attachment_tmp))
11431 {
11432 *remote_errno = FILEIO_EINVAL;
11433 return -1;
11434 }
11435
11436 /* Make sure we saw an attachment if and only if we expected one. */
11437 if ((attachment_tmp == NULL && attachment != NULL)
11438 || (attachment_tmp != NULL && attachment == NULL))
11439 {
11440 *remote_errno = FILEIO_EINVAL;
11441 return -1;
11442 }
11443
11444 /* If an attachment was found, it must point into the packet buffer;
11445 work out how many bytes there were. */
11446 if (attachment_tmp != NULL)
11447 {
11448 *attachment = attachment_tmp;
11449 *attachment_len = bytes_read - (*attachment - rs->buf);
11450 }
11451
11452 return ret;
11453 }
11454
11455 /* Invalidate the readahead cache. */
11456
11457 static void
11458 readahead_cache_invalidate (void)
11459 {
11460 struct remote_state *rs = get_remote_state ();
11461
11462 rs->readahead_cache.fd = -1;
11463 }
11464
11465 /* Invalidate the readahead cache if it is holding data for FD. */
11466
11467 static void
11468 readahead_cache_invalidate_fd (int fd)
11469 {
11470 struct remote_state *rs = get_remote_state ();
11471
11472 if (rs->readahead_cache.fd == fd)
11473 rs->readahead_cache.fd = -1;
11474 }
11475
11476 /* Set the filesystem remote_hostio functions that take FILENAME
11477 arguments will use. Return 0 on success, or -1 if an error
11478 occurs (and set *REMOTE_ERRNO). */
11479
11480 static int
11481 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11482 {
11483 struct remote_state *rs = get_remote_state ();
11484 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11485 char *p = rs->buf;
11486 int left = get_remote_packet_size () - 1;
11487 char arg[9];
11488 int ret;
11489
11490 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11491 return 0;
11492
11493 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11494 return 0;
11495
11496 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11497
11498 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11499 remote_buffer_add_string (&p, &left, arg);
11500
11501 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11502 remote_errno, NULL, NULL);
11503
11504 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11505 return 0;
11506
11507 if (ret == 0)
11508 rs->fs_pid = required_pid;
11509
11510 return ret;
11511 }
11512
11513 /* Implementation of to_fileio_open. */
11514
11515 static int
11516 remote_hostio_open (struct target_ops *self,
11517 struct inferior *inf, const char *filename,
11518 int flags, int mode, int warn_if_slow,
11519 int *remote_errno)
11520 {
11521 struct remote_state *rs = get_remote_state ();
11522 char *p = rs->buf;
11523 int left = get_remote_packet_size () - 1;
11524
11525 if (warn_if_slow)
11526 {
11527 static int warning_issued = 0;
11528
11529 printf_unfiltered (_("Reading %s from remote target...\n"),
11530 filename);
11531
11532 if (!warning_issued)
11533 {
11534 warning (_("File transfers from remote targets can be slow."
11535 " Use \"set sysroot\" to access files locally"
11536 " instead."));
11537 warning_issued = 1;
11538 }
11539 }
11540
11541 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11542 return -1;
11543
11544 remote_buffer_add_string (&p, &left, "vFile:open:");
11545
11546 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11547 strlen (filename));
11548 remote_buffer_add_string (&p, &left, ",");
11549
11550 remote_buffer_add_int (&p, &left, flags);
11551 remote_buffer_add_string (&p, &left, ",");
11552
11553 remote_buffer_add_int (&p, &left, mode);
11554
11555 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11556 remote_errno, NULL, NULL);
11557 }
11558
11559 /* Implementation of to_fileio_pwrite. */
11560
11561 static int
11562 remote_hostio_pwrite (struct target_ops *self,
11563 int fd, const gdb_byte *write_buf, int len,
11564 ULONGEST offset, int *remote_errno)
11565 {
11566 struct remote_state *rs = get_remote_state ();
11567 char *p = rs->buf;
11568 int left = get_remote_packet_size ();
11569 int out_len;
11570
11571 readahead_cache_invalidate_fd (fd);
11572
11573 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11574
11575 remote_buffer_add_int (&p, &left, fd);
11576 remote_buffer_add_string (&p, &left, ",");
11577
11578 remote_buffer_add_int (&p, &left, offset);
11579 remote_buffer_add_string (&p, &left, ",");
11580
11581 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11582 get_remote_packet_size () - (p - rs->buf));
11583
11584 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11585 remote_errno, NULL, NULL);
11586 }
11587
11588 /* Helper for the implementation of to_fileio_pread. Read the file
11589 from the remote side with vFile:pread. */
11590
11591 static int
11592 remote_hostio_pread_vFile (struct target_ops *self,
11593 int fd, gdb_byte *read_buf, int len,
11594 ULONGEST offset, int *remote_errno)
11595 {
11596 struct remote_state *rs = get_remote_state ();
11597 char *p = rs->buf;
11598 char *attachment;
11599 int left = get_remote_packet_size ();
11600 int ret, attachment_len;
11601 int read_len;
11602
11603 remote_buffer_add_string (&p, &left, "vFile:pread:");
11604
11605 remote_buffer_add_int (&p, &left, fd);
11606 remote_buffer_add_string (&p, &left, ",");
11607
11608 remote_buffer_add_int (&p, &left, len);
11609 remote_buffer_add_string (&p, &left, ",");
11610
11611 remote_buffer_add_int (&p, &left, offset);
11612
11613 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11614 remote_errno, &attachment,
11615 &attachment_len);
11616
11617 if (ret < 0)
11618 return ret;
11619
11620 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11621 read_buf, len);
11622 if (read_len != ret)
11623 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11624
11625 return ret;
11626 }
11627
11628 /* Serve pread from the readahead cache. Returns number of bytes
11629 read, or 0 if the request can't be served from the cache. */
11630
11631 static int
11632 remote_hostio_pread_from_cache (struct remote_state *rs,
11633 int fd, gdb_byte *read_buf, size_t len,
11634 ULONGEST offset)
11635 {
11636 struct readahead_cache *cache = &rs->readahead_cache;
11637
11638 if (cache->fd == fd
11639 && cache->offset <= offset
11640 && offset < cache->offset + cache->bufsize)
11641 {
11642 ULONGEST max = cache->offset + cache->bufsize;
11643
11644 if (offset + len > max)
11645 len = max - offset;
11646
11647 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11648 return len;
11649 }
11650
11651 return 0;
11652 }
11653
11654 /* Implementation of to_fileio_pread. */
11655
11656 static int
11657 remote_hostio_pread (struct target_ops *self,
11658 int fd, gdb_byte *read_buf, int len,
11659 ULONGEST offset, int *remote_errno)
11660 {
11661 int ret;
11662 struct remote_state *rs = get_remote_state ();
11663 struct readahead_cache *cache = &rs->readahead_cache;
11664
11665 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11666 if (ret > 0)
11667 {
11668 cache->hit_count++;
11669
11670 if (remote_debug)
11671 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11672 pulongest (cache->hit_count));
11673 return ret;
11674 }
11675
11676 cache->miss_count++;
11677 if (remote_debug)
11678 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11679 pulongest (cache->miss_count));
11680
11681 cache->fd = fd;
11682 cache->offset = offset;
11683 cache->bufsize = get_remote_packet_size ();
11684 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11685
11686 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11687 cache->offset, remote_errno);
11688 if (ret <= 0)
11689 {
11690 readahead_cache_invalidate_fd (fd);
11691 return ret;
11692 }
11693
11694 cache->bufsize = ret;
11695 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11696 }
11697
11698 /* Implementation of to_fileio_close. */
11699
11700 static int
11701 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11702 {
11703 struct remote_state *rs = get_remote_state ();
11704 char *p = rs->buf;
11705 int left = get_remote_packet_size () - 1;
11706
11707 readahead_cache_invalidate_fd (fd);
11708
11709 remote_buffer_add_string (&p, &left, "vFile:close:");
11710
11711 remote_buffer_add_int (&p, &left, fd);
11712
11713 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11714 remote_errno, NULL, NULL);
11715 }
11716
11717 /* Implementation of to_fileio_unlink. */
11718
11719 static int
11720 remote_hostio_unlink (struct target_ops *self,
11721 struct inferior *inf, const char *filename,
11722 int *remote_errno)
11723 {
11724 struct remote_state *rs = get_remote_state ();
11725 char *p = rs->buf;
11726 int left = get_remote_packet_size () - 1;
11727
11728 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11729 return -1;
11730
11731 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11732
11733 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11734 strlen (filename));
11735
11736 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11737 remote_errno, NULL, NULL);
11738 }
11739
11740 /* Implementation of to_fileio_readlink. */
11741
11742 static char *
11743 remote_hostio_readlink (struct target_ops *self,
11744 struct inferior *inf, const char *filename,
11745 int *remote_errno)
11746 {
11747 struct remote_state *rs = get_remote_state ();
11748 char *p = rs->buf;
11749 char *attachment;
11750 int left = get_remote_packet_size ();
11751 int len, attachment_len;
11752 int read_len;
11753 char *ret;
11754
11755 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11756 return NULL;
11757
11758 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11759
11760 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11761 strlen (filename));
11762
11763 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11764 remote_errno, &attachment,
11765 &attachment_len);
11766
11767 if (len < 0)
11768 return NULL;
11769
11770 ret = (char *) xmalloc (len + 1);
11771
11772 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11773 (gdb_byte *) ret, len);
11774 if (read_len != len)
11775 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11776
11777 ret[len] = '\0';
11778 return ret;
11779 }
11780
11781 /* Implementation of to_fileio_fstat. */
11782
11783 static int
11784 remote_hostio_fstat (struct target_ops *self,
11785 int fd, struct stat *st,
11786 int *remote_errno)
11787 {
11788 struct remote_state *rs = get_remote_state ();
11789 char *p = rs->buf;
11790 int left = get_remote_packet_size ();
11791 int attachment_len, ret;
11792 char *attachment;
11793 struct fio_stat fst;
11794 int read_len;
11795
11796 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11797
11798 remote_buffer_add_int (&p, &left, fd);
11799
11800 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11801 remote_errno, &attachment,
11802 &attachment_len);
11803 if (ret < 0)
11804 {
11805 if (*remote_errno != FILEIO_ENOSYS)
11806 return ret;
11807
11808 /* Strictly we should return -1, ENOSYS here, but when
11809 "set sysroot remote:" was implemented in August 2008
11810 BFD's need for a stat function was sidestepped with
11811 this hack. This was not remedied until March 2015
11812 so we retain the previous behavior to avoid breaking
11813 compatibility.
11814
11815 Note that the memset is a March 2015 addition; older
11816 GDBs set st_size *and nothing else* so the structure
11817 would have garbage in all other fields. This might
11818 break something but retaining the previous behavior
11819 here would be just too wrong. */
11820
11821 memset (st, 0, sizeof (struct stat));
11822 st->st_size = INT_MAX;
11823 return 0;
11824 }
11825
11826 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11827 (gdb_byte *) &fst, sizeof (fst));
11828
11829 if (read_len != ret)
11830 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11831
11832 if (read_len != sizeof (fst))
11833 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11834 read_len, (int) sizeof (fst));
11835
11836 remote_fileio_to_host_stat (&fst, st);
11837
11838 return 0;
11839 }
11840
11841 /* Implementation of to_filesystem_is_local. */
11842
11843 static int
11844 remote_filesystem_is_local (struct target_ops *self)
11845 {
11846 /* Valgrind GDB presents itself as a remote target but works
11847 on the local filesystem: it does not implement remote get
11848 and users are not expected to set a sysroot. To handle
11849 this case we treat the remote filesystem as local if the
11850 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11851 does not support vFile:open. */
11852 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11853 {
11854 enum packet_support ps = packet_support (PACKET_vFile_open);
11855
11856 if (ps == PACKET_SUPPORT_UNKNOWN)
11857 {
11858 int fd, remote_errno;
11859
11860 /* Try opening a file to probe support. The supplied
11861 filename is irrelevant, we only care about whether
11862 the stub recognizes the packet or not. */
11863 fd = remote_hostio_open (self, NULL, "just probing",
11864 FILEIO_O_RDONLY, 0700, 0,
11865 &remote_errno);
11866
11867 if (fd >= 0)
11868 remote_hostio_close (self, fd, &remote_errno);
11869
11870 ps = packet_support (PACKET_vFile_open);
11871 }
11872
11873 if (ps == PACKET_DISABLE)
11874 {
11875 static int warning_issued = 0;
11876
11877 if (!warning_issued)
11878 {
11879 warning (_("remote target does not support file"
11880 " transfer, attempting to access files"
11881 " from local filesystem."));
11882 warning_issued = 1;
11883 }
11884
11885 return 1;
11886 }
11887 }
11888
11889 return 0;
11890 }
11891
11892 static int
11893 remote_fileio_errno_to_host (int errnum)
11894 {
11895 switch (errnum)
11896 {
11897 case FILEIO_EPERM:
11898 return EPERM;
11899 case FILEIO_ENOENT:
11900 return ENOENT;
11901 case FILEIO_EINTR:
11902 return EINTR;
11903 case FILEIO_EIO:
11904 return EIO;
11905 case FILEIO_EBADF:
11906 return EBADF;
11907 case FILEIO_EACCES:
11908 return EACCES;
11909 case FILEIO_EFAULT:
11910 return EFAULT;
11911 case FILEIO_EBUSY:
11912 return EBUSY;
11913 case FILEIO_EEXIST:
11914 return EEXIST;
11915 case FILEIO_ENODEV:
11916 return ENODEV;
11917 case FILEIO_ENOTDIR:
11918 return ENOTDIR;
11919 case FILEIO_EISDIR:
11920 return EISDIR;
11921 case FILEIO_EINVAL:
11922 return EINVAL;
11923 case FILEIO_ENFILE:
11924 return ENFILE;
11925 case FILEIO_EMFILE:
11926 return EMFILE;
11927 case FILEIO_EFBIG:
11928 return EFBIG;
11929 case FILEIO_ENOSPC:
11930 return ENOSPC;
11931 case FILEIO_ESPIPE:
11932 return ESPIPE;
11933 case FILEIO_EROFS:
11934 return EROFS;
11935 case FILEIO_ENOSYS:
11936 return ENOSYS;
11937 case FILEIO_ENAMETOOLONG:
11938 return ENAMETOOLONG;
11939 }
11940 return -1;
11941 }
11942
11943 static char *
11944 remote_hostio_error (int errnum)
11945 {
11946 int host_error = remote_fileio_errno_to_host (errnum);
11947
11948 if (host_error == -1)
11949 error (_("Unknown remote I/O error %d"), errnum);
11950 else
11951 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11952 }
11953
11954 static void
11955 remote_hostio_close_cleanup (void *opaque)
11956 {
11957 int fd = *(int *) opaque;
11958 int remote_errno;
11959
11960 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11961 }
11962
11963 void
11964 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11965 {
11966 struct cleanup *back_to, *close_cleanup;
11967 int retcode, fd, remote_errno, bytes, io_size;
11968 gdb_byte *buffer;
11969 int bytes_in_buffer;
11970 int saw_eof;
11971 ULONGEST offset;
11972 struct remote_state *rs = get_remote_state ();
11973
11974 if (!rs->remote_desc)
11975 error (_("command can only be used with remote target"));
11976
11977 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
11978 if (file == NULL)
11979 perror_with_name (local_file);
11980
11981 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11982 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11983 | FILEIO_O_TRUNC),
11984 0700, 0, &remote_errno);
11985 if (fd == -1)
11986 remote_hostio_error (remote_errno);
11987
11988 /* Send up to this many bytes at once. They won't all fit in the
11989 remote packet limit, so we'll transfer slightly fewer. */
11990 io_size = get_remote_packet_size ();
11991 buffer = (gdb_byte *) xmalloc (io_size);
11992 back_to = make_cleanup (xfree, buffer);
11993
11994 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11995
11996 bytes_in_buffer = 0;
11997 saw_eof = 0;
11998 offset = 0;
11999 while (bytes_in_buffer || !saw_eof)
12000 {
12001 if (!saw_eof)
12002 {
12003 bytes = fread (buffer + bytes_in_buffer, 1,
12004 io_size - bytes_in_buffer,
12005 file.get ());
12006 if (bytes == 0)
12007 {
12008 if (ferror (file.get ()))
12009 error (_("Error reading %s."), local_file);
12010 else
12011 {
12012 /* EOF. Unless there is something still in the
12013 buffer from the last iteration, we are done. */
12014 saw_eof = 1;
12015 if (bytes_in_buffer == 0)
12016 break;
12017 }
12018 }
12019 }
12020 else
12021 bytes = 0;
12022
12023 bytes += bytes_in_buffer;
12024 bytes_in_buffer = 0;
12025
12026 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12027 fd, buffer, bytes,
12028 offset, &remote_errno);
12029
12030 if (retcode < 0)
12031 remote_hostio_error (remote_errno);
12032 else if (retcode == 0)
12033 error (_("Remote write of %d bytes returned 0!"), bytes);
12034 else if (retcode < bytes)
12035 {
12036 /* Short write. Save the rest of the read data for the next
12037 write. */
12038 bytes_in_buffer = bytes - retcode;
12039 memmove (buffer, buffer + retcode, bytes_in_buffer);
12040 }
12041
12042 offset += retcode;
12043 }
12044
12045 discard_cleanups (close_cleanup);
12046 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12047 remote_hostio_error (remote_errno);
12048
12049 if (from_tty)
12050 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12051 do_cleanups (back_to);
12052 }
12053
12054 void
12055 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12056 {
12057 struct cleanup *back_to, *close_cleanup;
12058 int fd, remote_errno, bytes, io_size;
12059 gdb_byte *buffer;
12060 ULONGEST offset;
12061 struct remote_state *rs = get_remote_state ();
12062
12063 if (!rs->remote_desc)
12064 error (_("command can only be used with remote target"));
12065
12066 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12067 remote_file, FILEIO_O_RDONLY, 0, 0,
12068 &remote_errno);
12069 if (fd == -1)
12070 remote_hostio_error (remote_errno);
12071
12072 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12073 if (file == NULL)
12074 perror_with_name (local_file);
12075
12076 /* Send up to this many bytes at once. They won't all fit in the
12077 remote packet limit, so we'll transfer slightly fewer. */
12078 io_size = get_remote_packet_size ();
12079 buffer = (gdb_byte *) xmalloc (io_size);
12080 back_to = make_cleanup (xfree, buffer);
12081
12082 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12083
12084 offset = 0;
12085 while (1)
12086 {
12087 bytes = remote_hostio_pread (find_target_at (process_stratum),
12088 fd, buffer, io_size, offset, &remote_errno);
12089 if (bytes == 0)
12090 /* Success, but no bytes, means end-of-file. */
12091 break;
12092 if (bytes == -1)
12093 remote_hostio_error (remote_errno);
12094
12095 offset += bytes;
12096
12097 bytes = fwrite (buffer, 1, bytes, file.get ());
12098 if (bytes == 0)
12099 perror_with_name (local_file);
12100 }
12101
12102 discard_cleanups (close_cleanup);
12103 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12104 remote_hostio_error (remote_errno);
12105
12106 if (from_tty)
12107 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12108 do_cleanups (back_to);
12109 }
12110
12111 void
12112 remote_file_delete (const char *remote_file, int from_tty)
12113 {
12114 int retcode, remote_errno;
12115 struct remote_state *rs = get_remote_state ();
12116
12117 if (!rs->remote_desc)
12118 error (_("command can only be used with remote target"));
12119
12120 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12121 NULL, remote_file, &remote_errno);
12122 if (retcode == -1)
12123 remote_hostio_error (remote_errno);
12124
12125 if (from_tty)
12126 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12127 }
12128
12129 static void
12130 remote_put_command (char *args, int from_tty)
12131 {
12132 if (args == NULL)
12133 error_no_arg (_("file to put"));
12134
12135 gdb_argv argv (args);
12136 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12137 error (_("Invalid parameters to remote put"));
12138
12139 remote_file_put (argv[0], argv[1], from_tty);
12140 }
12141
12142 static void
12143 remote_get_command (char *args, int from_tty)
12144 {
12145 if (args == NULL)
12146 error_no_arg (_("file to get"));
12147
12148 gdb_argv argv (args);
12149 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12150 error (_("Invalid parameters to remote get"));
12151
12152 remote_file_get (argv[0], argv[1], from_tty);
12153 }
12154
12155 static void
12156 remote_delete_command (char *args, int from_tty)
12157 {
12158 if (args == NULL)
12159 error_no_arg (_("file to delete"));
12160
12161 gdb_argv argv (args);
12162 if (argv[0] == NULL || argv[1] != NULL)
12163 error (_("Invalid parameters to remote delete"));
12164
12165 remote_file_delete (argv[0], from_tty);
12166 }
12167
12168 static void
12169 remote_command (char *args, int from_tty)
12170 {
12171 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12172 }
12173
12174 static int
12175 remote_can_execute_reverse (struct target_ops *self)
12176 {
12177 if (packet_support (PACKET_bs) == PACKET_ENABLE
12178 || packet_support (PACKET_bc) == PACKET_ENABLE)
12179 return 1;
12180 else
12181 return 0;
12182 }
12183
12184 static int
12185 remote_supports_non_stop (struct target_ops *self)
12186 {
12187 return 1;
12188 }
12189
12190 static int
12191 remote_supports_disable_randomization (struct target_ops *self)
12192 {
12193 /* Only supported in extended mode. */
12194 return 0;
12195 }
12196
12197 static int
12198 remote_supports_multi_process (struct target_ops *self)
12199 {
12200 struct remote_state *rs = get_remote_state ();
12201
12202 return remote_multi_process_p (rs);
12203 }
12204
12205 static int
12206 remote_supports_cond_tracepoints (void)
12207 {
12208 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12209 }
12210
12211 static int
12212 remote_supports_cond_breakpoints (struct target_ops *self)
12213 {
12214 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12215 }
12216
12217 static int
12218 remote_supports_fast_tracepoints (void)
12219 {
12220 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12221 }
12222
12223 static int
12224 remote_supports_static_tracepoints (void)
12225 {
12226 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12227 }
12228
12229 static int
12230 remote_supports_install_in_trace (void)
12231 {
12232 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12233 }
12234
12235 static int
12236 remote_supports_enable_disable_tracepoint (struct target_ops *self)
12237 {
12238 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12239 == PACKET_ENABLE);
12240 }
12241
12242 static int
12243 remote_supports_string_tracing (struct target_ops *self)
12244 {
12245 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12246 }
12247
12248 static int
12249 remote_can_run_breakpoint_commands (struct target_ops *self)
12250 {
12251 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12252 }
12253
12254 static void
12255 remote_trace_init (struct target_ops *self)
12256 {
12257 putpkt ("QTinit");
12258 remote_get_noisy_reply (&target_buf, &target_buf_size);
12259 if (strcmp (target_buf, "OK") != 0)
12260 error (_("Target does not support this command."));
12261 }
12262
12263 static void free_actions_list (char **actions_list);
12264 static void free_actions_list_cleanup_wrapper (void *);
12265 static void
12266 free_actions_list_cleanup_wrapper (void *al)
12267 {
12268 free_actions_list ((char **) al);
12269 }
12270
12271 static void
12272 free_actions_list (char **actions_list)
12273 {
12274 int ndx;
12275
12276 if (actions_list == 0)
12277 return;
12278
12279 for (ndx = 0; actions_list[ndx]; ndx++)
12280 xfree (actions_list[ndx]);
12281
12282 xfree (actions_list);
12283 }
12284
12285 /* Recursive routine to walk through command list including loops, and
12286 download packets for each command. */
12287
12288 static void
12289 remote_download_command_source (int num, ULONGEST addr,
12290 struct command_line *cmds)
12291 {
12292 struct remote_state *rs = get_remote_state ();
12293 struct command_line *cmd;
12294
12295 for (cmd = cmds; cmd; cmd = cmd->next)
12296 {
12297 QUIT; /* Allow user to bail out with ^C. */
12298 strcpy (rs->buf, "QTDPsrc:");
12299 encode_source_string (num, addr, "cmd", cmd->line,
12300 rs->buf + strlen (rs->buf),
12301 rs->buf_size - strlen (rs->buf));
12302 putpkt (rs->buf);
12303 remote_get_noisy_reply (&target_buf, &target_buf_size);
12304 if (strcmp (target_buf, "OK"))
12305 warning (_("Target does not support source download."));
12306
12307 if (cmd->control_type == while_control
12308 || cmd->control_type == while_stepping_control)
12309 {
12310 remote_download_command_source (num, addr, *cmd->body_list);
12311
12312 QUIT; /* Allow user to bail out with ^C. */
12313 strcpy (rs->buf, "QTDPsrc:");
12314 encode_source_string (num, addr, "cmd", "end",
12315 rs->buf + strlen (rs->buf),
12316 rs->buf_size - strlen (rs->buf));
12317 putpkt (rs->buf);
12318 remote_get_noisy_reply (&target_buf, &target_buf_size);
12319 if (strcmp (target_buf, "OK"))
12320 warning (_("Target does not support source download."));
12321 }
12322 }
12323 }
12324
12325 static void
12326 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
12327 {
12328 #define BUF_SIZE 2048
12329
12330 CORE_ADDR tpaddr;
12331 char addrbuf[40];
12332 char buf[BUF_SIZE];
12333 char **tdp_actions;
12334 char **stepping_actions;
12335 int ndx;
12336 struct cleanup *old_chain = NULL;
12337 char *pkt;
12338 struct breakpoint *b = loc->owner;
12339 struct tracepoint *t = (struct tracepoint *) b;
12340
12341 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12342 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
12343 tdp_actions);
12344 (void) make_cleanup (free_actions_list_cleanup_wrapper,
12345 stepping_actions);
12346
12347 tpaddr = loc->address;
12348 sprintf_vma (addrbuf, tpaddr);
12349 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12350 addrbuf, /* address */
12351 (b->enable_state == bp_enabled ? 'E' : 'D'),
12352 t->step_count, t->pass_count);
12353 /* Fast tracepoints are mostly handled by the target, but we can
12354 tell the target how big of an instruction block should be moved
12355 around. */
12356 if (b->type == bp_fast_tracepoint)
12357 {
12358 /* Only test for support at download time; we may not know
12359 target capabilities at definition time. */
12360 if (remote_supports_fast_tracepoints ())
12361 {
12362 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12363 NULL))
12364 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12365 gdb_insn_length (loc->gdbarch, tpaddr));
12366 else
12367 /* If it passed validation at definition but fails now,
12368 something is very wrong. */
12369 internal_error (__FILE__, __LINE__,
12370 _("Fast tracepoint not "
12371 "valid during download"));
12372 }
12373 else
12374 /* Fast tracepoints are functionally identical to regular
12375 tracepoints, so don't take lack of support as a reason to
12376 give up on the trace run. */
12377 warning (_("Target does not support fast tracepoints, "
12378 "downloading %d as regular tracepoint"), b->number);
12379 }
12380 else if (b->type == bp_static_tracepoint)
12381 {
12382 /* Only test for support at download time; we may not know
12383 target capabilities at definition time. */
12384 if (remote_supports_static_tracepoints ())
12385 {
12386 struct static_tracepoint_marker marker;
12387
12388 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12389 strcat (buf, ":S");
12390 else
12391 error (_("Static tracepoint not valid during download"));
12392 }
12393 else
12394 /* Fast tracepoints are functionally identical to regular
12395 tracepoints, so don't take lack of support as a reason
12396 to give up on the trace run. */
12397 error (_("Target does not support static tracepoints"));
12398 }
12399 /* If the tracepoint has a conditional, make it into an agent
12400 expression and append to the definition. */
12401 if (loc->cond)
12402 {
12403 /* Only test support at download time, we may not know target
12404 capabilities at definition time. */
12405 if (remote_supports_cond_tracepoints ())
12406 {
12407 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12408 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12409 aexpr->len);
12410 pkt = buf + strlen (buf);
12411 for (ndx = 0; ndx < aexpr->len; ++ndx)
12412 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12413 *pkt = '\0';
12414 }
12415 else
12416 warning (_("Target does not support conditional tracepoints, "
12417 "ignoring tp %d cond"), b->number);
12418 }
12419
12420 if (b->commands || *default_collect)
12421 strcat (buf, "-");
12422 putpkt (buf);
12423 remote_get_noisy_reply (&target_buf, &target_buf_size);
12424 if (strcmp (target_buf, "OK"))
12425 error (_("Target does not support tracepoints."));
12426
12427 /* do_single_steps (t); */
12428 if (tdp_actions)
12429 {
12430 for (ndx = 0; tdp_actions[ndx]; ndx++)
12431 {
12432 QUIT; /* Allow user to bail out with ^C. */
12433 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12434 b->number, addrbuf, /* address */
12435 tdp_actions[ndx],
12436 ((tdp_actions[ndx + 1] || stepping_actions)
12437 ? '-' : 0));
12438 putpkt (buf);
12439 remote_get_noisy_reply (&target_buf,
12440 &target_buf_size);
12441 if (strcmp (target_buf, "OK"))
12442 error (_("Error on target while setting tracepoints."));
12443 }
12444 }
12445 if (stepping_actions)
12446 {
12447 for (ndx = 0; stepping_actions[ndx]; ndx++)
12448 {
12449 QUIT; /* Allow user to bail out with ^C. */
12450 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12451 b->number, addrbuf, /* address */
12452 ((ndx == 0) ? "S" : ""),
12453 stepping_actions[ndx],
12454 (stepping_actions[ndx + 1] ? "-" : ""));
12455 putpkt (buf);
12456 remote_get_noisy_reply (&target_buf,
12457 &target_buf_size);
12458 if (strcmp (target_buf, "OK"))
12459 error (_("Error on target while setting tracepoints."));
12460 }
12461 }
12462
12463 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12464 {
12465 if (b->location != NULL)
12466 {
12467 strcpy (buf, "QTDPsrc:");
12468 encode_source_string (b->number, loc->address, "at",
12469 event_location_to_string (b->location.get ()),
12470 buf + strlen (buf), 2048 - strlen (buf));
12471 putpkt (buf);
12472 remote_get_noisy_reply (&target_buf, &target_buf_size);
12473 if (strcmp (target_buf, "OK"))
12474 warning (_("Target does not support source download."));
12475 }
12476 if (b->cond_string)
12477 {
12478 strcpy (buf, "QTDPsrc:");
12479 encode_source_string (b->number, loc->address,
12480 "cond", b->cond_string, buf + strlen (buf),
12481 2048 - strlen (buf));
12482 putpkt (buf);
12483 remote_get_noisy_reply (&target_buf, &target_buf_size);
12484 if (strcmp (target_buf, "OK"))
12485 warning (_("Target does not support source download."));
12486 }
12487 remote_download_command_source (b->number, loc->address,
12488 breakpoint_commands (b));
12489 }
12490
12491 do_cleanups (old_chain);
12492 }
12493
12494 static int
12495 remote_can_download_tracepoint (struct target_ops *self)
12496 {
12497 struct remote_state *rs = get_remote_state ();
12498 struct trace_status *ts;
12499 int status;
12500
12501 /* Don't try to install tracepoints until we've relocated our
12502 symbols, and fetched and merged the target's tracepoint list with
12503 ours. */
12504 if (rs->starting_up)
12505 return 0;
12506
12507 ts = current_trace_status ();
12508 status = remote_get_trace_status (self, ts);
12509
12510 if (status == -1 || !ts->running_known || !ts->running)
12511 return 0;
12512
12513 /* If we are in a tracing experiment, but remote stub doesn't support
12514 installing tracepoint in trace, we have to return. */
12515 if (!remote_supports_install_in_trace ())
12516 return 0;
12517
12518 return 1;
12519 }
12520
12521
12522 static void
12523 remote_download_trace_state_variable (struct target_ops *self,
12524 struct trace_state_variable *tsv)
12525 {
12526 struct remote_state *rs = get_remote_state ();
12527 char *p;
12528
12529 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12530 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12531 tsv->builtin);
12532 p = rs->buf + strlen (rs->buf);
12533 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12534 error (_("Trace state variable name too long for tsv definition packet"));
12535 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12536 *p++ = '\0';
12537 putpkt (rs->buf);
12538 remote_get_noisy_reply (&target_buf, &target_buf_size);
12539 if (*target_buf == '\0')
12540 error (_("Target does not support this command."));
12541 if (strcmp (target_buf, "OK") != 0)
12542 error (_("Error on target while downloading trace state variable."));
12543 }
12544
12545 static void
12546 remote_enable_tracepoint (struct target_ops *self,
12547 struct bp_location *location)
12548 {
12549 struct remote_state *rs = get_remote_state ();
12550 char addr_buf[40];
12551
12552 sprintf_vma (addr_buf, location->address);
12553 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12554 location->owner->number, addr_buf);
12555 putpkt (rs->buf);
12556 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12557 if (*rs->buf == '\0')
12558 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12559 if (strcmp (rs->buf, "OK") != 0)
12560 error (_("Error on target while enabling tracepoint."));
12561 }
12562
12563 static void
12564 remote_disable_tracepoint (struct target_ops *self,
12565 struct bp_location *location)
12566 {
12567 struct remote_state *rs = get_remote_state ();
12568 char addr_buf[40];
12569
12570 sprintf_vma (addr_buf, location->address);
12571 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12572 location->owner->number, addr_buf);
12573 putpkt (rs->buf);
12574 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12575 if (*rs->buf == '\0')
12576 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12577 if (strcmp (rs->buf, "OK") != 0)
12578 error (_("Error on target while disabling tracepoint."));
12579 }
12580
12581 static void
12582 remote_trace_set_readonly_regions (struct target_ops *self)
12583 {
12584 asection *s;
12585 bfd *abfd = NULL;
12586 bfd_size_type size;
12587 bfd_vma vma;
12588 int anysecs = 0;
12589 int offset = 0;
12590
12591 if (!exec_bfd)
12592 return; /* No information to give. */
12593
12594 strcpy (target_buf, "QTro");
12595 offset = strlen (target_buf);
12596 for (s = exec_bfd->sections; s; s = s->next)
12597 {
12598 char tmp1[40], tmp2[40];
12599 int sec_length;
12600
12601 if ((s->flags & SEC_LOAD) == 0 ||
12602 /* (s->flags & SEC_CODE) == 0 || */
12603 (s->flags & SEC_READONLY) == 0)
12604 continue;
12605
12606 anysecs = 1;
12607 vma = bfd_get_section_vma (abfd, s);
12608 size = bfd_get_section_size (s);
12609 sprintf_vma (tmp1, vma);
12610 sprintf_vma (tmp2, vma + size);
12611 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12612 if (offset + sec_length + 1 > target_buf_size)
12613 {
12614 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12615 warning (_("\
12616 Too many sections for read-only sections definition packet."));
12617 break;
12618 }
12619 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12620 tmp1, tmp2);
12621 offset += sec_length;
12622 }
12623 if (anysecs)
12624 {
12625 putpkt (target_buf);
12626 getpkt (&target_buf, &target_buf_size, 0);
12627 }
12628 }
12629
12630 static void
12631 remote_trace_start (struct target_ops *self)
12632 {
12633 putpkt ("QTStart");
12634 remote_get_noisy_reply (&target_buf, &target_buf_size);
12635 if (*target_buf == '\0')
12636 error (_("Target does not support this command."));
12637 if (strcmp (target_buf, "OK") != 0)
12638 error (_("Bogus reply from target: %s"), target_buf);
12639 }
12640
12641 static int
12642 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12643 {
12644 /* Initialize it just to avoid a GCC false warning. */
12645 char *p = NULL;
12646 /* FIXME we need to get register block size some other way. */
12647 extern int trace_regblock_size;
12648 enum packet_result result;
12649
12650 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12651 return -1;
12652
12653 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12654
12655 putpkt ("qTStatus");
12656
12657 TRY
12658 {
12659 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12660 }
12661 CATCH (ex, RETURN_MASK_ERROR)
12662 {
12663 if (ex.error != TARGET_CLOSE_ERROR)
12664 {
12665 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12666 return -1;
12667 }
12668 throw_exception (ex);
12669 }
12670 END_CATCH
12671
12672 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12673
12674 /* If the remote target doesn't do tracing, flag it. */
12675 if (result == PACKET_UNKNOWN)
12676 return -1;
12677
12678 /* We're working with a live target. */
12679 ts->filename = NULL;
12680
12681 if (*p++ != 'T')
12682 error (_("Bogus trace status reply from target: %s"), target_buf);
12683
12684 /* Function 'parse_trace_status' sets default value of each field of
12685 'ts' at first, so we don't have to do it here. */
12686 parse_trace_status (p, ts);
12687
12688 return ts->running;
12689 }
12690
12691 static void
12692 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12693 struct uploaded_tp *utp)
12694 {
12695 struct remote_state *rs = get_remote_state ();
12696 char *reply;
12697 struct bp_location *loc;
12698 struct tracepoint *tp = (struct tracepoint *) bp;
12699 size_t size = get_remote_packet_size ();
12700
12701 if (tp)
12702 {
12703 tp->hit_count = 0;
12704 tp->traceframe_usage = 0;
12705 for (loc = tp->loc; loc; loc = loc->next)
12706 {
12707 /* If the tracepoint was never downloaded, don't go asking for
12708 any status. */
12709 if (tp->number_on_target == 0)
12710 continue;
12711 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12712 phex_nz (loc->address, 0));
12713 putpkt (rs->buf);
12714 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12715 if (reply && *reply)
12716 {
12717 if (*reply == 'V')
12718 parse_tracepoint_status (reply + 1, bp, utp);
12719 }
12720 }
12721 }
12722 else if (utp)
12723 {
12724 utp->hit_count = 0;
12725 utp->traceframe_usage = 0;
12726 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12727 phex_nz (utp->addr, 0));
12728 putpkt (rs->buf);
12729 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12730 if (reply && *reply)
12731 {
12732 if (*reply == 'V')
12733 parse_tracepoint_status (reply + 1, bp, utp);
12734 }
12735 }
12736 }
12737
12738 static void
12739 remote_trace_stop (struct target_ops *self)
12740 {
12741 putpkt ("QTStop");
12742 remote_get_noisy_reply (&target_buf, &target_buf_size);
12743 if (*target_buf == '\0')
12744 error (_("Target does not support this command."));
12745 if (strcmp (target_buf, "OK") != 0)
12746 error (_("Bogus reply from target: %s"), target_buf);
12747 }
12748
12749 static int
12750 remote_trace_find (struct target_ops *self,
12751 enum trace_find_type type, int num,
12752 CORE_ADDR addr1, CORE_ADDR addr2,
12753 int *tpp)
12754 {
12755 struct remote_state *rs = get_remote_state ();
12756 char *endbuf = rs->buf + get_remote_packet_size ();
12757 char *p, *reply;
12758 int target_frameno = -1, target_tracept = -1;
12759
12760 /* Lookups other than by absolute frame number depend on the current
12761 trace selected, so make sure it is correct on the remote end
12762 first. */
12763 if (type != tfind_number)
12764 set_remote_traceframe ();
12765
12766 p = rs->buf;
12767 strcpy (p, "QTFrame:");
12768 p = strchr (p, '\0');
12769 switch (type)
12770 {
12771 case tfind_number:
12772 xsnprintf (p, endbuf - p, "%x", num);
12773 break;
12774 case tfind_pc:
12775 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12776 break;
12777 case tfind_tp:
12778 xsnprintf (p, endbuf - p, "tdp:%x", num);
12779 break;
12780 case tfind_range:
12781 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12782 phex_nz (addr2, 0));
12783 break;
12784 case tfind_outside:
12785 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12786 phex_nz (addr2, 0));
12787 break;
12788 default:
12789 error (_("Unknown trace find type %d"), type);
12790 }
12791
12792 putpkt (rs->buf);
12793 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12794 if (*reply == '\0')
12795 error (_("Target does not support this command."));
12796
12797 while (reply && *reply)
12798 switch (*reply)
12799 {
12800 case 'F':
12801 p = ++reply;
12802 target_frameno = (int) strtol (p, &reply, 16);
12803 if (reply == p)
12804 error (_("Unable to parse trace frame number"));
12805 /* Don't update our remote traceframe number cache on failure
12806 to select a remote traceframe. */
12807 if (target_frameno == -1)
12808 return -1;
12809 break;
12810 case 'T':
12811 p = ++reply;
12812 target_tracept = (int) strtol (p, &reply, 16);
12813 if (reply == p)
12814 error (_("Unable to parse tracepoint number"));
12815 break;
12816 case 'O': /* "OK"? */
12817 if (reply[1] == 'K' && reply[2] == '\0')
12818 reply += 2;
12819 else
12820 error (_("Bogus reply from target: %s"), reply);
12821 break;
12822 default:
12823 error (_("Bogus reply from target: %s"), reply);
12824 }
12825 if (tpp)
12826 *tpp = target_tracept;
12827
12828 rs->remote_traceframe_number = target_frameno;
12829 return target_frameno;
12830 }
12831
12832 static int
12833 remote_get_trace_state_variable_value (struct target_ops *self,
12834 int tsvnum, LONGEST *val)
12835 {
12836 struct remote_state *rs = get_remote_state ();
12837 char *reply;
12838 ULONGEST uval;
12839
12840 set_remote_traceframe ();
12841
12842 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12843 putpkt (rs->buf);
12844 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12845 if (reply && *reply)
12846 {
12847 if (*reply == 'V')
12848 {
12849 unpack_varlen_hex (reply + 1, &uval);
12850 *val = (LONGEST) uval;
12851 return 1;
12852 }
12853 }
12854 return 0;
12855 }
12856
12857 static int
12858 remote_save_trace_data (struct target_ops *self, const char *filename)
12859 {
12860 struct remote_state *rs = get_remote_state ();
12861 char *p, *reply;
12862
12863 p = rs->buf;
12864 strcpy (p, "QTSave:");
12865 p += strlen (p);
12866 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12867 error (_("Remote file name too long for trace save packet"));
12868 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12869 *p++ = '\0';
12870 putpkt (rs->buf);
12871 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12872 if (*reply == '\0')
12873 error (_("Target does not support this command."));
12874 if (strcmp (reply, "OK") != 0)
12875 error (_("Bogus reply from target: %s"), reply);
12876 return 0;
12877 }
12878
12879 /* This is basically a memory transfer, but needs to be its own packet
12880 because we don't know how the target actually organizes its trace
12881 memory, plus we want to be able to ask for as much as possible, but
12882 not be unhappy if we don't get as much as we ask for. */
12883
12884 static LONGEST
12885 remote_get_raw_trace_data (struct target_ops *self,
12886 gdb_byte *buf, ULONGEST offset, LONGEST len)
12887 {
12888 struct remote_state *rs = get_remote_state ();
12889 char *reply;
12890 char *p;
12891 int rslt;
12892
12893 p = rs->buf;
12894 strcpy (p, "qTBuffer:");
12895 p += strlen (p);
12896 p += hexnumstr (p, offset);
12897 *p++ = ',';
12898 p += hexnumstr (p, len);
12899 *p++ = '\0';
12900
12901 putpkt (rs->buf);
12902 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12903 if (reply && *reply)
12904 {
12905 /* 'l' by itself means we're at the end of the buffer and
12906 there is nothing more to get. */
12907 if (*reply == 'l')
12908 return 0;
12909
12910 /* Convert the reply into binary. Limit the number of bytes to
12911 convert according to our passed-in buffer size, rather than
12912 what was returned in the packet; if the target is
12913 unexpectedly generous and gives us a bigger reply than we
12914 asked for, we don't want to crash. */
12915 rslt = hex2bin (target_buf, buf, len);
12916 return rslt;
12917 }
12918
12919 /* Something went wrong, flag as an error. */
12920 return -1;
12921 }
12922
12923 static void
12924 remote_set_disconnected_tracing (struct target_ops *self, int val)
12925 {
12926 struct remote_state *rs = get_remote_state ();
12927
12928 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12929 {
12930 char *reply;
12931
12932 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12933 putpkt (rs->buf);
12934 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12935 if (*reply == '\0')
12936 error (_("Target does not support this command."));
12937 if (strcmp (reply, "OK") != 0)
12938 error (_("Bogus reply from target: %s"), reply);
12939 }
12940 else if (val)
12941 warning (_("Target does not support disconnected tracing."));
12942 }
12943
12944 static int
12945 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12946 {
12947 struct thread_info *info = find_thread_ptid (ptid);
12948
12949 if (info && info->priv)
12950 return info->priv->core;
12951 return -1;
12952 }
12953
12954 static void
12955 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12956 {
12957 struct remote_state *rs = get_remote_state ();
12958 char *reply;
12959
12960 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12961 putpkt (rs->buf);
12962 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12963 if (*reply == '\0')
12964 error (_("Target does not support this command."));
12965 if (strcmp (reply, "OK") != 0)
12966 error (_("Bogus reply from target: %s"), reply);
12967 }
12968
12969 static struct traceframe_info *
12970 remote_traceframe_info (struct target_ops *self)
12971 {
12972 char *text;
12973
12974 text = target_read_stralloc (&current_target,
12975 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12976 if (text != NULL)
12977 {
12978 struct traceframe_info *info;
12979 struct cleanup *back_to = make_cleanup (xfree, text);
12980
12981 info = parse_traceframe_info (text);
12982 do_cleanups (back_to);
12983 return info;
12984 }
12985
12986 return NULL;
12987 }
12988
12989 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12990 instruction on which a fast tracepoint may be placed. Returns -1
12991 if the packet is not supported, and 0 if the minimum instruction
12992 length is unknown. */
12993
12994 static int
12995 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12996 {
12997 struct remote_state *rs = get_remote_state ();
12998 char *reply;
12999
13000 /* If we're not debugging a process yet, the IPA can't be
13001 loaded. */
13002 if (!target_has_execution)
13003 return 0;
13004
13005 /* Make sure the remote is pointing at the right process. */
13006 set_general_process ();
13007
13008 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13009 putpkt (rs->buf);
13010 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
13011 if (*reply == '\0')
13012 return -1;
13013 else
13014 {
13015 ULONGEST min_insn_len;
13016
13017 unpack_varlen_hex (reply, &min_insn_len);
13018
13019 return (int) min_insn_len;
13020 }
13021 }
13022
13023 static void
13024 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
13025 {
13026 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13027 {
13028 struct remote_state *rs = get_remote_state ();
13029 char *buf = rs->buf;
13030 char *endbuf = rs->buf + get_remote_packet_size ();
13031 enum packet_result result;
13032
13033 gdb_assert (val >= 0 || val == -1);
13034 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13035 /* Send -1 as literal "-1" to avoid host size dependency. */
13036 if (val < 0)
13037 {
13038 *buf++ = '-';
13039 buf += hexnumstr (buf, (ULONGEST) -val);
13040 }
13041 else
13042 buf += hexnumstr (buf, (ULONGEST) val);
13043
13044 putpkt (rs->buf);
13045 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
13046 result = packet_ok (rs->buf,
13047 &remote_protocol_packets[PACKET_QTBuffer_size]);
13048
13049 if (result != PACKET_OK)
13050 warning (_("Bogus reply from target: %s"), rs->buf);
13051 }
13052 }
13053
13054 static int
13055 remote_set_trace_notes (struct target_ops *self,
13056 const char *user, const char *notes,
13057 const char *stop_notes)
13058 {
13059 struct remote_state *rs = get_remote_state ();
13060 char *reply;
13061 char *buf = rs->buf;
13062 char *endbuf = rs->buf + get_remote_packet_size ();
13063 int nbytes;
13064
13065 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13066 if (user)
13067 {
13068 buf += xsnprintf (buf, endbuf - buf, "user:");
13069 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13070 buf += 2 * nbytes;
13071 *buf++ = ';';
13072 }
13073 if (notes)
13074 {
13075 buf += xsnprintf (buf, endbuf - buf, "notes:");
13076 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13077 buf += 2 * nbytes;
13078 *buf++ = ';';
13079 }
13080 if (stop_notes)
13081 {
13082 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13083 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13084 buf += 2 * nbytes;
13085 *buf++ = ';';
13086 }
13087 /* Ensure the buffer is terminated. */
13088 *buf = '\0';
13089
13090 putpkt (rs->buf);
13091 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
13092 if (*reply == '\0')
13093 return 0;
13094
13095 if (strcmp (reply, "OK") != 0)
13096 error (_("Bogus reply from target: %s"), reply);
13097
13098 return 1;
13099 }
13100
13101 static int
13102 remote_use_agent (struct target_ops *self, int use)
13103 {
13104 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13105 {
13106 struct remote_state *rs = get_remote_state ();
13107
13108 /* If the stub supports QAgent. */
13109 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13110 putpkt (rs->buf);
13111 getpkt (&rs->buf, &rs->buf_size, 0);
13112
13113 if (strcmp (rs->buf, "OK") == 0)
13114 {
13115 use_agent = use;
13116 return 1;
13117 }
13118 }
13119
13120 return 0;
13121 }
13122
13123 static int
13124 remote_can_use_agent (struct target_ops *self)
13125 {
13126 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13127 }
13128
13129 struct btrace_target_info
13130 {
13131 /* The ptid of the traced thread. */
13132 ptid_t ptid;
13133
13134 /* The obtained branch trace configuration. */
13135 struct btrace_config conf;
13136 };
13137
13138 /* Reset our idea of our target's btrace configuration. */
13139
13140 static void
13141 remote_btrace_reset (void)
13142 {
13143 struct remote_state *rs = get_remote_state ();
13144
13145 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13146 }
13147
13148 /* Check whether the target supports branch tracing. */
13149
13150 static int
13151 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
13152 {
13153 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
13154 return 0;
13155 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
13156 return 0;
13157
13158 switch (format)
13159 {
13160 case BTRACE_FORMAT_NONE:
13161 return 0;
13162
13163 case BTRACE_FORMAT_BTS:
13164 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
13165
13166 case BTRACE_FORMAT_PT:
13167 /* The trace is decoded on the host. Even if our target supports it,
13168 we still need to have libipt to decode the trace. */
13169 #if defined (HAVE_LIBIPT)
13170 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
13171 #else /* !defined (HAVE_LIBIPT) */
13172 return 0;
13173 #endif /* !defined (HAVE_LIBIPT) */
13174 }
13175
13176 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
13177 }
13178
13179 /* Synchronize the configuration with the target. */
13180
13181 static void
13182 btrace_sync_conf (const struct btrace_config *conf)
13183 {
13184 struct packet_config *packet;
13185 struct remote_state *rs;
13186 char *buf, *pos, *endbuf;
13187
13188 rs = get_remote_state ();
13189 buf = rs->buf;
13190 endbuf = buf + get_remote_packet_size ();
13191
13192 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13193 if (packet_config_support (packet) == PACKET_ENABLE
13194 && conf->bts.size != rs->btrace_config.bts.size)
13195 {
13196 pos = buf;
13197 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13198 conf->bts.size);
13199
13200 putpkt (buf);
13201 getpkt (&buf, &rs->buf_size, 0);
13202
13203 if (packet_ok (buf, packet) == PACKET_ERROR)
13204 {
13205 if (buf[0] == 'E' && buf[1] == '.')
13206 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13207 else
13208 error (_("Failed to configure the BTS buffer size."));
13209 }
13210
13211 rs->btrace_config.bts.size = conf->bts.size;
13212 }
13213
13214 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13215 if (packet_config_support (packet) == PACKET_ENABLE
13216 && conf->pt.size != rs->btrace_config.pt.size)
13217 {
13218 pos = buf;
13219 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13220 conf->pt.size);
13221
13222 putpkt (buf);
13223 getpkt (&buf, &rs->buf_size, 0);
13224
13225 if (packet_ok (buf, packet) == PACKET_ERROR)
13226 {
13227 if (buf[0] == 'E' && buf[1] == '.')
13228 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13229 else
13230 error (_("Failed to configure the trace buffer size."));
13231 }
13232
13233 rs->btrace_config.pt.size = conf->pt.size;
13234 }
13235 }
13236
13237 /* Read the current thread's btrace configuration from the target and
13238 store it into CONF. */
13239
13240 static void
13241 btrace_read_config (struct btrace_config *conf)
13242 {
13243 char *xml;
13244
13245 xml = target_read_stralloc (&current_target,
13246 TARGET_OBJECT_BTRACE_CONF, "");
13247 if (xml != NULL)
13248 {
13249 struct cleanup *cleanup;
13250
13251 cleanup = make_cleanup (xfree, xml);
13252 parse_xml_btrace_conf (conf, xml);
13253 do_cleanups (cleanup);
13254 }
13255 }
13256
13257 /* Maybe reopen target btrace. */
13258
13259 static void
13260 remote_btrace_maybe_reopen (void)
13261 {
13262 struct remote_state *rs = get_remote_state ();
13263 struct thread_info *tp;
13264 int btrace_target_pushed = 0;
13265 int warned = 0;
13266
13267 scoped_restore_current_thread restore_thread;
13268
13269 ALL_NON_EXITED_THREADS (tp)
13270 {
13271 set_general_thread (tp->ptid);
13272
13273 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13274 btrace_read_config (&rs->btrace_config);
13275
13276 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13277 continue;
13278
13279 #if !defined (HAVE_LIBIPT)
13280 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13281 {
13282 if (!warned)
13283 {
13284 warned = 1;
13285 warning (_("GDB does not support Intel Processor Trace. "
13286 "\"record\" will not work in this session."));
13287 }
13288
13289 continue;
13290 }
13291 #endif /* !defined (HAVE_LIBIPT) */
13292
13293 /* Push target, once, but before anything else happens. This way our
13294 changes to the threads will be cleaned up by unpushing the target
13295 in case btrace_read_config () throws. */
13296 if (!btrace_target_pushed)
13297 {
13298 btrace_target_pushed = 1;
13299 record_btrace_push_target ();
13300 printf_filtered (_("Target is recording using %s.\n"),
13301 btrace_format_string (rs->btrace_config.format));
13302 }
13303
13304 tp->btrace.target = XCNEW (struct btrace_target_info);
13305 tp->btrace.target->ptid = tp->ptid;
13306 tp->btrace.target->conf = rs->btrace_config;
13307 }
13308 }
13309
13310 /* Enable branch tracing. */
13311
13312 static struct btrace_target_info *
13313 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13314 const struct btrace_config *conf)
13315 {
13316 struct btrace_target_info *tinfo = NULL;
13317 struct packet_config *packet = NULL;
13318 struct remote_state *rs = get_remote_state ();
13319 char *buf = rs->buf;
13320 char *endbuf = rs->buf + get_remote_packet_size ();
13321
13322 switch (conf->format)
13323 {
13324 case BTRACE_FORMAT_BTS:
13325 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13326 break;
13327
13328 case BTRACE_FORMAT_PT:
13329 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13330 break;
13331 }
13332
13333 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13334 error (_("Target does not support branch tracing."));
13335
13336 btrace_sync_conf (conf);
13337
13338 set_general_thread (ptid);
13339
13340 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13341 putpkt (rs->buf);
13342 getpkt (&rs->buf, &rs->buf_size, 0);
13343
13344 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13345 {
13346 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13347 error (_("Could not enable branch tracing for %s: %s"),
13348 target_pid_to_str (ptid), rs->buf + 2);
13349 else
13350 error (_("Could not enable branch tracing for %s."),
13351 target_pid_to_str (ptid));
13352 }
13353
13354 tinfo = XCNEW (struct btrace_target_info);
13355 tinfo->ptid = ptid;
13356
13357 /* If we fail to read the configuration, we lose some information, but the
13358 tracing itself is not impacted. */
13359 TRY
13360 {
13361 btrace_read_config (&tinfo->conf);
13362 }
13363 CATCH (err, RETURN_MASK_ERROR)
13364 {
13365 if (err.message != NULL)
13366 warning ("%s", err.message);
13367 }
13368 END_CATCH
13369
13370 return tinfo;
13371 }
13372
13373 /* Disable branch tracing. */
13374
13375 static void
13376 remote_disable_btrace (struct target_ops *self,
13377 struct btrace_target_info *tinfo)
13378 {
13379 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13380 struct remote_state *rs = get_remote_state ();
13381 char *buf = rs->buf;
13382 char *endbuf = rs->buf + get_remote_packet_size ();
13383
13384 if (packet_config_support (packet) != PACKET_ENABLE)
13385 error (_("Target does not support branch tracing."));
13386
13387 set_general_thread (tinfo->ptid);
13388
13389 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13390 putpkt (rs->buf);
13391 getpkt (&rs->buf, &rs->buf_size, 0);
13392
13393 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13394 {
13395 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13396 error (_("Could not disable branch tracing for %s: %s"),
13397 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13398 else
13399 error (_("Could not disable branch tracing for %s."),
13400 target_pid_to_str (tinfo->ptid));
13401 }
13402
13403 xfree (tinfo);
13404 }
13405
13406 /* Teardown branch tracing. */
13407
13408 static void
13409 remote_teardown_btrace (struct target_ops *self,
13410 struct btrace_target_info *tinfo)
13411 {
13412 /* We must not talk to the target during teardown. */
13413 xfree (tinfo);
13414 }
13415
13416 /* Read the branch trace. */
13417
13418 static enum btrace_error
13419 remote_read_btrace (struct target_ops *self,
13420 struct btrace_data *btrace,
13421 struct btrace_target_info *tinfo,
13422 enum btrace_read_type type)
13423 {
13424 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13425 struct cleanup *cleanup;
13426 const char *annex;
13427 char *xml;
13428
13429 if (packet_config_support (packet) != PACKET_ENABLE)
13430 error (_("Target does not support branch tracing."));
13431
13432 #if !defined(HAVE_LIBEXPAT)
13433 error (_("Cannot process branch tracing result. XML parsing not supported."));
13434 #endif
13435
13436 switch (type)
13437 {
13438 case BTRACE_READ_ALL:
13439 annex = "all";
13440 break;
13441 case BTRACE_READ_NEW:
13442 annex = "new";
13443 break;
13444 case BTRACE_READ_DELTA:
13445 annex = "delta";
13446 break;
13447 default:
13448 internal_error (__FILE__, __LINE__,
13449 _("Bad branch tracing read type: %u."),
13450 (unsigned int) type);
13451 }
13452
13453 xml = target_read_stralloc (&current_target,
13454 TARGET_OBJECT_BTRACE, annex);
13455 if (xml == NULL)
13456 return BTRACE_ERR_UNKNOWN;
13457
13458 cleanup = make_cleanup (xfree, xml);
13459 parse_xml_btrace (btrace, xml);
13460 do_cleanups (cleanup);
13461
13462 return BTRACE_ERR_NONE;
13463 }
13464
13465 static const struct btrace_config *
13466 remote_btrace_conf (struct target_ops *self,
13467 const struct btrace_target_info *tinfo)
13468 {
13469 return &tinfo->conf;
13470 }
13471
13472 static int
13473 remote_augmented_libraries_svr4_read (struct target_ops *self)
13474 {
13475 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13476 == PACKET_ENABLE);
13477 }
13478
13479 /* Implementation of to_load. */
13480
13481 static void
13482 remote_load (struct target_ops *self, const char *name, int from_tty)
13483 {
13484 generic_load (name, from_tty);
13485 }
13486
13487 /* Accepts an integer PID; returns a string representing a file that
13488 can be opened on the remote side to get the symbols for the child
13489 process. Returns NULL if the operation is not supported. */
13490
13491 static char *
13492 remote_pid_to_exec_file (struct target_ops *self, int pid)
13493 {
13494 static char *filename = NULL;
13495 struct inferior *inf;
13496 char *annex = NULL;
13497
13498 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13499 return NULL;
13500
13501 if (filename != NULL)
13502 xfree (filename);
13503
13504 inf = find_inferior_pid (pid);
13505 if (inf == NULL)
13506 internal_error (__FILE__, __LINE__,
13507 _("not currently attached to process %d"), pid);
13508
13509 if (!inf->fake_pid_p)
13510 {
13511 const int annex_size = 9;
13512
13513 annex = (char *) alloca (annex_size);
13514 xsnprintf (annex, annex_size, "%x", pid);
13515 }
13516
13517 filename = target_read_stralloc (&current_target,
13518 TARGET_OBJECT_EXEC_FILE, annex);
13519
13520 return filename;
13521 }
13522
13523 /* Implement the to_can_do_single_step target_ops method. */
13524
13525 static int
13526 remote_can_do_single_step (struct target_ops *ops)
13527 {
13528 /* We can only tell whether target supports single step or not by
13529 supported s and S vCont actions if the stub supports vContSupported
13530 feature. If the stub doesn't support vContSupported feature,
13531 we have conservatively to think target doesn't supports single
13532 step. */
13533 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13534 {
13535 struct remote_state *rs = get_remote_state ();
13536
13537 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13538 remote_vcont_probe (rs);
13539
13540 return rs->supports_vCont.s && rs->supports_vCont.S;
13541 }
13542 else
13543 return 0;
13544 }
13545
13546 /* Implementation of the to_execution_direction method for the remote
13547 target. */
13548
13549 static enum exec_direction_kind
13550 remote_execution_direction (struct target_ops *self)
13551 {
13552 struct remote_state *rs = get_remote_state ();
13553
13554 return rs->last_resume_exec_dir;
13555 }
13556
13557 /* Return pointer to the thread_info struct which corresponds to
13558 THREAD_HANDLE (having length HANDLE_LEN). */
13559
13560 static struct thread_info *
13561 remote_thread_handle_to_thread_info (struct target_ops *ops,
13562 const gdb_byte *thread_handle,
13563 int handle_len,
13564 struct inferior *inf)
13565 {
13566 struct thread_info *tp;
13567
13568 ALL_NON_EXITED_THREADS (tp)
13569 {
13570 struct private_thread_info *priv = get_private_info_thread (tp);
13571
13572 if (tp->inf == inf && priv != NULL)
13573 {
13574 if (handle_len != priv->thread_handle->size ())
13575 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13576 handle_len, priv->thread_handle->size ());
13577 if (memcmp (thread_handle, priv->thread_handle->data (),
13578 handle_len) == 0)
13579 return tp;
13580 }
13581 }
13582
13583 return NULL;
13584 }
13585
13586 static void
13587 init_remote_ops (void)
13588 {
13589 remote_ops.to_shortname = "remote";
13590 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13591 remote_ops.to_doc =
13592 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13593 Specify the serial device it is connected to\n\
13594 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13595 remote_ops.to_open = remote_open;
13596 remote_ops.to_close = remote_close;
13597 remote_ops.to_detach = remote_detach;
13598 remote_ops.to_disconnect = remote_disconnect;
13599 remote_ops.to_resume = remote_resume;
13600 remote_ops.to_commit_resume = remote_commit_resume;
13601 remote_ops.to_wait = remote_wait;
13602 remote_ops.to_fetch_registers = remote_fetch_registers;
13603 remote_ops.to_store_registers = remote_store_registers;
13604 remote_ops.to_prepare_to_store = remote_prepare_to_store;
13605 remote_ops.to_files_info = remote_files_info;
13606 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13607 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13608 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13609 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13610 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13611 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13612 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13613 remote_ops.to_stopped_data_address = remote_stopped_data_address;
13614 remote_ops.to_watchpoint_addr_within_range =
13615 remote_watchpoint_addr_within_range;
13616 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13617 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13618 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13619 remote_ops.to_region_ok_for_hw_watchpoint
13620 = remote_region_ok_for_hw_watchpoint;
13621 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13622 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13623 remote_ops.to_kill = remote_kill;
13624 remote_ops.to_load = remote_load;
13625 remote_ops.to_mourn_inferior = remote_mourn;
13626 remote_ops.to_pass_signals = remote_pass_signals;
13627 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13628 remote_ops.to_program_signals = remote_program_signals;
13629 remote_ops.to_thread_alive = remote_thread_alive;
13630 remote_ops.to_thread_name = remote_thread_name;
13631 remote_ops.to_update_thread_list = remote_update_thread_list;
13632 remote_ops.to_pid_to_str = remote_pid_to_str;
13633 remote_ops.to_extra_thread_info = remote_threads_extra_info;
13634 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13635 remote_ops.to_stop = remote_stop;
13636 remote_ops.to_interrupt = remote_interrupt;
13637 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13638 remote_ops.to_xfer_partial = remote_xfer_partial;
13639 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
13640 remote_ops.to_rcmd = remote_rcmd;
13641 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13642 remote_ops.to_log_command = serial_log_command;
13643 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13644 remote_ops.to_stratum = process_stratum;
13645 remote_ops.to_has_all_memory = default_child_has_all_memory;
13646 remote_ops.to_has_memory = default_child_has_memory;
13647 remote_ops.to_has_stack = default_child_has_stack;
13648 remote_ops.to_has_registers = default_child_has_registers;
13649 remote_ops.to_has_execution = default_child_has_execution;
13650 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
13651 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13652 remote_ops.to_magic = OPS_MAGIC;
13653 remote_ops.to_memory_map = remote_memory_map;
13654 remote_ops.to_flash_erase = remote_flash_erase;
13655 remote_ops.to_flash_done = remote_flash_done;
13656 remote_ops.to_read_description = remote_read_description;
13657 remote_ops.to_search_memory = remote_search_memory;
13658 remote_ops.to_can_async_p = remote_can_async_p;
13659 remote_ops.to_is_async_p = remote_is_async_p;
13660 remote_ops.to_async = remote_async;
13661 remote_ops.to_thread_events = remote_thread_events;
13662 remote_ops.to_can_do_single_step = remote_can_do_single_step;
13663 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13664 remote_ops.to_terminal_ours = remote_terminal_ours;
13665 remote_ops.to_supports_non_stop = remote_supports_non_stop;
13666 remote_ops.to_supports_multi_process = remote_supports_multi_process;
13667 remote_ops.to_supports_disable_randomization
13668 = remote_supports_disable_randomization;
13669 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13670 remote_ops.to_fileio_open = remote_hostio_open;
13671 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13672 remote_ops.to_fileio_pread = remote_hostio_pread;
13673 remote_ops.to_fileio_fstat = remote_hostio_fstat;
13674 remote_ops.to_fileio_close = remote_hostio_close;
13675 remote_ops.to_fileio_unlink = remote_hostio_unlink;
13676 remote_ops.to_fileio_readlink = remote_hostio_readlink;
13677 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13678 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13679 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13680 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13681 remote_ops.to_trace_init = remote_trace_init;
13682 remote_ops.to_download_tracepoint = remote_download_tracepoint;
13683 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13684 remote_ops.to_download_trace_state_variable
13685 = remote_download_trace_state_variable;
13686 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13687 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13688 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13689 remote_ops.to_trace_start = remote_trace_start;
13690 remote_ops.to_get_trace_status = remote_get_trace_status;
13691 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13692 remote_ops.to_trace_stop = remote_trace_stop;
13693 remote_ops.to_trace_find = remote_trace_find;
13694 remote_ops.to_get_trace_state_variable_value
13695 = remote_get_trace_state_variable_value;
13696 remote_ops.to_save_trace_data = remote_save_trace_data;
13697 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13698 remote_ops.to_upload_trace_state_variables
13699 = remote_upload_trace_state_variables;
13700 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13701 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13702 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13703 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13704 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13705 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13706 remote_ops.to_core_of_thread = remote_core_of_thread;
13707 remote_ops.to_verify_memory = remote_verify_memory;
13708 remote_ops.to_get_tib_address = remote_get_tib_address;
13709 remote_ops.to_set_permissions = remote_set_permissions;
13710 remote_ops.to_static_tracepoint_marker_at
13711 = remote_static_tracepoint_marker_at;
13712 remote_ops.to_static_tracepoint_markers_by_strid
13713 = remote_static_tracepoint_markers_by_strid;
13714 remote_ops.to_traceframe_info = remote_traceframe_info;
13715 remote_ops.to_use_agent = remote_use_agent;
13716 remote_ops.to_can_use_agent = remote_can_use_agent;
13717 remote_ops.to_supports_btrace = remote_supports_btrace;
13718 remote_ops.to_enable_btrace = remote_enable_btrace;
13719 remote_ops.to_disable_btrace = remote_disable_btrace;
13720 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13721 remote_ops.to_read_btrace = remote_read_btrace;
13722 remote_ops.to_btrace_conf = remote_btrace_conf;
13723 remote_ops.to_augmented_libraries_svr4_read =
13724 remote_augmented_libraries_svr4_read;
13725 remote_ops.to_follow_fork = remote_follow_fork;
13726 remote_ops.to_follow_exec = remote_follow_exec;
13727 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13728 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13729 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13730 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13731 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13732 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13733 remote_ops.to_execution_direction = remote_execution_direction;
13734 remote_ops.to_thread_handle_to_thread_info =
13735 remote_thread_handle_to_thread_info;
13736 }
13737
13738 /* Set up the extended remote vector by making a copy of the standard
13739 remote vector and adding to it. */
13740
13741 static void
13742 init_extended_remote_ops (void)
13743 {
13744 extended_remote_ops = remote_ops;
13745
13746 extended_remote_ops.to_shortname = "extended-remote";
13747 extended_remote_ops.to_longname =
13748 "Extended remote serial target in gdb-specific protocol";
13749 extended_remote_ops.to_doc =
13750 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13751 Specify the serial device it is connected to (e.g. /dev/ttya).";
13752 extended_remote_ops.to_open = extended_remote_open;
13753 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13754 extended_remote_ops.to_detach = extended_remote_detach;
13755 extended_remote_ops.to_attach = extended_remote_attach;
13756 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13757 extended_remote_ops.to_supports_disable_randomization
13758 = extended_remote_supports_disable_randomization;
13759 }
13760
13761 static int
13762 remote_can_async_p (struct target_ops *ops)
13763 {
13764 struct remote_state *rs = get_remote_state ();
13765
13766 /* We don't go async if the user has explicitly prevented it with the
13767 "maint set target-async" command. */
13768 if (!target_async_permitted)
13769 return 0;
13770
13771 /* We're async whenever the serial device is. */
13772 return serial_can_async_p (rs->remote_desc);
13773 }
13774
13775 static int
13776 remote_is_async_p (struct target_ops *ops)
13777 {
13778 struct remote_state *rs = get_remote_state ();
13779
13780 if (!target_async_permitted)
13781 /* We only enable async when the user specifically asks for it. */
13782 return 0;
13783
13784 /* We're async whenever the serial device is. */
13785 return serial_is_async_p (rs->remote_desc);
13786 }
13787
13788 /* Pass the SERIAL event on and up to the client. One day this code
13789 will be able to delay notifying the client of an event until the
13790 point where an entire packet has been received. */
13791
13792 static serial_event_ftype remote_async_serial_handler;
13793
13794 static void
13795 remote_async_serial_handler (struct serial *scb, void *context)
13796 {
13797 /* Don't propogate error information up to the client. Instead let
13798 the client find out about the error by querying the target. */
13799 inferior_event_handler (INF_REG_EVENT, NULL);
13800 }
13801
13802 static void
13803 remote_async_inferior_event_handler (gdb_client_data data)
13804 {
13805 inferior_event_handler (INF_REG_EVENT, NULL);
13806 }
13807
13808 static void
13809 remote_async (struct target_ops *ops, int enable)
13810 {
13811 struct remote_state *rs = get_remote_state ();
13812
13813 if (enable)
13814 {
13815 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13816
13817 /* If there are pending events in the stop reply queue tell the
13818 event loop to process them. */
13819 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13820 mark_async_event_handler (remote_async_inferior_event_token);
13821 /* For simplicity, below we clear the pending events token
13822 without remembering whether it is marked, so here we always
13823 mark it. If there's actually no pending notification to
13824 process, this ends up being a no-op (other than a spurious
13825 event-loop wakeup). */
13826 if (target_is_non_stop_p ())
13827 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13828 }
13829 else
13830 {
13831 serial_async (rs->remote_desc, NULL, NULL);
13832 /* If the core is disabling async, it doesn't want to be
13833 disturbed with target events. Clear all async event sources
13834 too. */
13835 clear_async_event_handler (remote_async_inferior_event_token);
13836 if (target_is_non_stop_p ())
13837 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13838 }
13839 }
13840
13841 /* Implementation of the to_thread_events method. */
13842
13843 static void
13844 remote_thread_events (struct target_ops *ops, int enable)
13845 {
13846 struct remote_state *rs = get_remote_state ();
13847 size_t size = get_remote_packet_size ();
13848
13849 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13850 return;
13851
13852 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13853 putpkt (rs->buf);
13854 getpkt (&rs->buf, &rs->buf_size, 0);
13855
13856 switch (packet_ok (rs->buf,
13857 &remote_protocol_packets[PACKET_QThreadEvents]))
13858 {
13859 case PACKET_OK:
13860 if (strcmp (rs->buf, "OK") != 0)
13861 error (_("Remote refused setting thread events: %s"), rs->buf);
13862 break;
13863 case PACKET_ERROR:
13864 warning (_("Remote failure reply: %s"), rs->buf);
13865 break;
13866 case PACKET_UNKNOWN:
13867 break;
13868 }
13869 }
13870
13871 static void
13872 set_remote_cmd (char *args, int from_tty)
13873 {
13874 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13875 }
13876
13877 static void
13878 show_remote_cmd (char *args, int from_tty)
13879 {
13880 /* We can't just use cmd_show_list here, because we want to skip
13881 the redundant "show remote Z-packet" and the legacy aliases. */
13882 struct cmd_list_element *list = remote_show_cmdlist;
13883 struct ui_out *uiout = current_uiout;
13884
13885 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13886 for (; list != NULL; list = list->next)
13887 if (strcmp (list->name, "Z-packet") == 0)
13888 continue;
13889 else if (list->type == not_set_cmd)
13890 /* Alias commands are exactly like the original, except they
13891 don't have the normal type. */
13892 continue;
13893 else
13894 {
13895 ui_out_emit_tuple option_emitter (uiout, "option");
13896
13897 uiout->field_string ("name", list->name);
13898 uiout->text (": ");
13899 if (list->type == show_cmd)
13900 do_show_command (NULL, from_tty, list);
13901 else
13902 cmd_func (list, NULL, from_tty);
13903 }
13904 }
13905
13906
13907 /* Function to be called whenever a new objfile (shlib) is detected. */
13908 static void
13909 remote_new_objfile (struct objfile *objfile)
13910 {
13911 struct remote_state *rs = get_remote_state ();
13912
13913 if (rs->remote_desc != 0) /* Have a remote connection. */
13914 remote_check_symbols ();
13915 }
13916
13917 /* Pull all the tracepoints defined on the target and create local
13918 data structures representing them. We don't want to create real
13919 tracepoints yet, we don't want to mess up the user's existing
13920 collection. */
13921
13922 static int
13923 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13924 {
13925 struct remote_state *rs = get_remote_state ();
13926 char *p;
13927
13928 /* Ask for a first packet of tracepoint definition. */
13929 putpkt ("qTfP");
13930 getpkt (&rs->buf, &rs->buf_size, 0);
13931 p = rs->buf;
13932 while (*p && *p != 'l')
13933 {
13934 parse_tracepoint_definition (p, utpp);
13935 /* Ask for another packet of tracepoint definition. */
13936 putpkt ("qTsP");
13937 getpkt (&rs->buf, &rs->buf_size, 0);
13938 p = rs->buf;
13939 }
13940 return 0;
13941 }
13942
13943 static int
13944 remote_upload_trace_state_variables (struct target_ops *self,
13945 struct uploaded_tsv **utsvp)
13946 {
13947 struct remote_state *rs = get_remote_state ();
13948 char *p;
13949
13950 /* Ask for a first packet of variable definition. */
13951 putpkt ("qTfV");
13952 getpkt (&rs->buf, &rs->buf_size, 0);
13953 p = rs->buf;
13954 while (*p && *p != 'l')
13955 {
13956 parse_tsv_definition (p, utsvp);
13957 /* Ask for another packet of variable definition. */
13958 putpkt ("qTsV");
13959 getpkt (&rs->buf, &rs->buf_size, 0);
13960 p = rs->buf;
13961 }
13962 return 0;
13963 }
13964
13965 /* The "set/show range-stepping" show hook. */
13966
13967 static void
13968 show_range_stepping (struct ui_file *file, int from_tty,
13969 struct cmd_list_element *c,
13970 const char *value)
13971 {
13972 fprintf_filtered (file,
13973 _("Debugger's willingness to use range stepping "
13974 "is %s.\n"), value);
13975 }
13976
13977 /* The "set/show range-stepping" set hook. */
13978
13979 static void
13980 set_range_stepping (char *ignore_args, int from_tty,
13981 struct cmd_list_element *c)
13982 {
13983 struct remote_state *rs = get_remote_state ();
13984
13985 /* Whene enabling, check whether range stepping is actually
13986 supported by the target, and warn if not. */
13987 if (use_range_stepping)
13988 {
13989 if (rs->remote_desc != NULL)
13990 {
13991 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13992 remote_vcont_probe (rs);
13993
13994 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13995 && rs->supports_vCont.r)
13996 return;
13997 }
13998
13999 warning (_("Range stepping is not supported by the current target"));
14000 }
14001 }
14002
14003 void
14004 _initialize_remote (void)
14005 {
14006 struct cmd_list_element *cmd;
14007 const char *cmd_name;
14008
14009 /* architecture specific data */
14010 remote_gdbarch_data_handle =
14011 gdbarch_data_register_post_init (init_remote_state);
14012 remote_g_packet_data_handle =
14013 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14014
14015 remote_pspace_data
14016 = register_program_space_data_with_cleanup (NULL,
14017 remote_pspace_data_cleanup);
14018
14019 /* Initialize the per-target state. At the moment there is only one
14020 of these, not one per target. Only one target is active at a
14021 time. */
14022 remote_state = new_remote_state ();
14023
14024 init_remote_ops ();
14025 add_target (&remote_ops);
14026
14027 init_extended_remote_ops ();
14028 add_target (&extended_remote_ops);
14029
14030 /* Hook into new objfile notification. */
14031 observer_attach_new_objfile (remote_new_objfile);
14032 /* We're no longer interested in notification events of an inferior
14033 when it exits. */
14034 observer_attach_inferior_exit (discard_pending_stop_replies);
14035
14036 #if 0
14037 init_remote_threadtests ();
14038 #endif
14039
14040 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14041 /* set/show remote ... */
14042
14043 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14044 Remote protocol specific variables\n\
14045 Configure various remote-protocol specific variables such as\n\
14046 the packets being used"),
14047 &remote_set_cmdlist, "set remote ",
14048 0 /* allow-unknown */, &setlist);
14049 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14050 Remote protocol specific variables\n\
14051 Configure various remote-protocol specific variables such as\n\
14052 the packets being used"),
14053 &remote_show_cmdlist, "show remote ",
14054 0 /* allow-unknown */, &showlist);
14055
14056 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14057 Compare section data on target to the exec file.\n\
14058 Argument is a single section name (default: all loaded sections).\n\
14059 To compare only read-only loaded sections, specify the -r option."),
14060 &cmdlist);
14061
14062 add_cmd ("packet", class_maintenance, packet_command, _("\
14063 Send an arbitrary packet to a remote target.\n\
14064 maintenance packet TEXT\n\
14065 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14066 this command sends the string TEXT to the inferior, and displays the\n\
14067 response packet. GDB supplies the initial `$' character, and the\n\
14068 terminating `#' character and checksum."),
14069 &maintenancelist);
14070
14071 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14072 Set whether to send break if interrupted."), _("\
14073 Show whether to send break if interrupted."), _("\
14074 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14075 set_remotebreak, show_remotebreak,
14076 &setlist, &showlist);
14077 cmd_name = "remotebreak";
14078 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14079 deprecate_cmd (cmd, "set remote interrupt-sequence");
14080 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14081 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14082 deprecate_cmd (cmd, "show remote interrupt-sequence");
14083
14084 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14085 interrupt_sequence_modes, &interrupt_sequence_mode,
14086 _("\
14087 Set interrupt sequence to remote target."), _("\
14088 Show interrupt sequence to remote target."), _("\
14089 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14090 NULL, show_interrupt_sequence,
14091 &remote_set_cmdlist,
14092 &remote_show_cmdlist);
14093
14094 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14095 &interrupt_on_connect, _("\
14096 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14097 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14098 If set, interrupt sequence is sent to remote target."),
14099 NULL, NULL,
14100 &remote_set_cmdlist, &remote_show_cmdlist);
14101
14102 /* Install commands for configuring memory read/write packets. */
14103
14104 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14105 Set the maximum number of bytes per memory write packet (deprecated)."),
14106 &setlist);
14107 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14108 Show the maximum number of bytes per memory write packet (deprecated)."),
14109 &showlist);
14110 add_cmd ("memory-write-packet-size", no_class,
14111 set_memory_write_packet_size, _("\
14112 Set the maximum number of bytes per memory-write packet.\n\
14113 Specify the number of bytes in a packet or 0 (zero) for the\n\
14114 default packet size. The actual limit is further reduced\n\
14115 dependent on the target. Specify ``fixed'' to disable the\n\
14116 further restriction and ``limit'' to enable that restriction."),
14117 &remote_set_cmdlist);
14118 add_cmd ("memory-read-packet-size", no_class,
14119 set_memory_read_packet_size, _("\
14120 Set the maximum number of bytes per memory-read packet.\n\
14121 Specify the number of bytes in a packet or 0 (zero) for the\n\
14122 default packet size. The actual limit is further reduced\n\
14123 dependent on the target. Specify ``fixed'' to disable the\n\
14124 further restriction and ``limit'' to enable that restriction."),
14125 &remote_set_cmdlist);
14126 add_cmd ("memory-write-packet-size", no_class,
14127 show_memory_write_packet_size,
14128 _("Show the maximum number of bytes per memory-write packet."),
14129 &remote_show_cmdlist);
14130 add_cmd ("memory-read-packet-size", no_class,
14131 show_memory_read_packet_size,
14132 _("Show the maximum number of bytes per memory-read packet."),
14133 &remote_show_cmdlist);
14134
14135 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14136 &remote_hw_watchpoint_limit, _("\
14137 Set the maximum number of target hardware watchpoints."), _("\
14138 Show the maximum number of target hardware watchpoints."), _("\
14139 Specify a negative limit for unlimited."),
14140 NULL, NULL, /* FIXME: i18n: The maximum
14141 number of target hardware
14142 watchpoints is %s. */
14143 &remote_set_cmdlist, &remote_show_cmdlist);
14144 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14145 &remote_hw_watchpoint_length_limit, _("\
14146 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14147 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14148 Specify a negative limit for unlimited."),
14149 NULL, NULL, /* FIXME: i18n: The maximum
14150 length (in bytes) of a target
14151 hardware watchpoint is %s. */
14152 &remote_set_cmdlist, &remote_show_cmdlist);
14153 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14154 &remote_hw_breakpoint_limit, _("\
14155 Set the maximum number of target hardware breakpoints."), _("\
14156 Show the maximum number of target hardware breakpoints."), _("\
14157 Specify a negative limit for unlimited."),
14158 NULL, NULL, /* FIXME: i18n: The maximum
14159 number of target hardware
14160 breakpoints is %s. */
14161 &remote_set_cmdlist, &remote_show_cmdlist);
14162
14163 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14164 &remote_address_size, _("\
14165 Set the maximum size of the address (in bits) in a memory packet."), _("\
14166 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14167 NULL,
14168 NULL, /* FIXME: i18n: */
14169 &setlist, &showlist);
14170
14171 init_all_packet_configs ();
14172
14173 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14174 "X", "binary-download", 1);
14175
14176 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14177 "vCont", "verbose-resume", 0);
14178
14179 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14180 "QPassSignals", "pass-signals", 0);
14181
14182 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14183 "QCatchSyscalls", "catch-syscalls", 0);
14184
14185 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14186 "QProgramSignals", "program-signals", 0);
14187
14188 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14189 "QStartupWithShell", "startup-with-shell", 0);
14190
14191 add_packet_config_cmd (&remote_protocol_packets
14192 [PACKET_QEnvironmentHexEncoded],
14193 "QEnvironmentHexEncoded", "environment-hex-encoded",
14194 0);
14195
14196 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14197 "QEnvironmentReset", "environment-reset",
14198 0);
14199
14200 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14201 "QEnvironmentUnset", "environment-unset",
14202 0);
14203
14204 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14205 "qSymbol", "symbol-lookup", 0);
14206
14207 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14208 "P", "set-register", 1);
14209
14210 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14211 "p", "fetch-register", 1);
14212
14213 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14214 "Z0", "software-breakpoint", 0);
14215
14216 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14217 "Z1", "hardware-breakpoint", 0);
14218
14219 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14220 "Z2", "write-watchpoint", 0);
14221
14222 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14223 "Z3", "read-watchpoint", 0);
14224
14225 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14226 "Z4", "access-watchpoint", 0);
14227
14228 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14229 "qXfer:auxv:read", "read-aux-vector", 0);
14230
14231 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14232 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14233
14234 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14235 "qXfer:features:read", "target-features", 0);
14236
14237 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14238 "qXfer:libraries:read", "library-info", 0);
14239
14240 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14241 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14242
14243 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14244 "qXfer:memory-map:read", "memory-map", 0);
14245
14246 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14247 "qXfer:spu:read", "read-spu-object", 0);
14248
14249 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14250 "qXfer:spu:write", "write-spu-object", 0);
14251
14252 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14253 "qXfer:osdata:read", "osdata", 0);
14254
14255 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14256 "qXfer:threads:read", "threads", 0);
14257
14258 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14259 "qXfer:siginfo:read", "read-siginfo-object", 0);
14260
14261 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14262 "qXfer:siginfo:write", "write-siginfo-object", 0);
14263
14264 add_packet_config_cmd
14265 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14266 "qXfer:traceframe-info:read", "traceframe-info", 0);
14267
14268 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14269 "qXfer:uib:read", "unwind-info-block", 0);
14270
14271 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14272 "qGetTLSAddr", "get-thread-local-storage-address",
14273 0);
14274
14275 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14276 "qGetTIBAddr", "get-thread-information-block-address",
14277 0);
14278
14279 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14280 "bc", "reverse-continue", 0);
14281
14282 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14283 "bs", "reverse-step", 0);
14284
14285 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14286 "qSupported", "supported-packets", 0);
14287
14288 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14289 "qSearch:memory", "search-memory", 0);
14290
14291 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14292 "qTStatus", "trace-status", 0);
14293
14294 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14295 "vFile:setfs", "hostio-setfs", 0);
14296
14297 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14298 "vFile:open", "hostio-open", 0);
14299
14300 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14301 "vFile:pread", "hostio-pread", 0);
14302
14303 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14304 "vFile:pwrite", "hostio-pwrite", 0);
14305
14306 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14307 "vFile:close", "hostio-close", 0);
14308
14309 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14310 "vFile:unlink", "hostio-unlink", 0);
14311
14312 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14313 "vFile:readlink", "hostio-readlink", 0);
14314
14315 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14316 "vFile:fstat", "hostio-fstat", 0);
14317
14318 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14319 "vAttach", "attach", 0);
14320
14321 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14322 "vRun", "run", 0);
14323
14324 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14325 "QStartNoAckMode", "noack", 0);
14326
14327 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14328 "vKill", "kill", 0);
14329
14330 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14331 "qAttached", "query-attached", 0);
14332
14333 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14334 "ConditionalTracepoints",
14335 "conditional-tracepoints", 0);
14336
14337 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14338 "ConditionalBreakpoints",
14339 "conditional-breakpoints", 0);
14340
14341 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14342 "BreakpointCommands",
14343 "breakpoint-commands", 0);
14344
14345 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14346 "FastTracepoints", "fast-tracepoints", 0);
14347
14348 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14349 "TracepointSource", "TracepointSource", 0);
14350
14351 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14352 "QAllow", "allow", 0);
14353
14354 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14355 "StaticTracepoints", "static-tracepoints", 0);
14356
14357 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14358 "InstallInTrace", "install-in-trace", 0);
14359
14360 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14361 "qXfer:statictrace:read", "read-sdata-object", 0);
14362
14363 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14364 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14365
14366 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14367 "QDisableRandomization", "disable-randomization", 0);
14368
14369 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14370 "QAgent", "agent", 0);
14371
14372 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14373 "QTBuffer:size", "trace-buffer-size", 0);
14374
14375 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14376 "Qbtrace:off", "disable-btrace", 0);
14377
14378 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14379 "Qbtrace:bts", "enable-btrace-bts", 0);
14380
14381 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14382 "Qbtrace:pt", "enable-btrace-pt", 0);
14383
14384 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14385 "qXfer:btrace", "read-btrace", 0);
14386
14387 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14388 "qXfer:btrace-conf", "read-btrace-conf", 0);
14389
14390 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14391 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14392
14393 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14394 "multiprocess-feature", "multiprocess-feature", 0);
14395
14396 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14397 "swbreak-feature", "swbreak-feature", 0);
14398
14399 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14400 "hwbreak-feature", "hwbreak-feature", 0);
14401
14402 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14403 "fork-event-feature", "fork-event-feature", 0);
14404
14405 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14406 "vfork-event-feature", "vfork-event-feature", 0);
14407
14408 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14409 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14410
14411 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14412 "vContSupported", "verbose-resume-supported", 0);
14413
14414 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14415 "exec-event-feature", "exec-event-feature", 0);
14416
14417 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14418 "vCtrlC", "ctrl-c", 0);
14419
14420 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14421 "QThreadEvents", "thread-events", 0);
14422
14423 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14424 "N stop reply", "no-resumed-stop-reply", 0);
14425
14426 /* Assert that we've registered "set remote foo-packet" commands
14427 for all packet configs. */
14428 {
14429 int i;
14430
14431 for (i = 0; i < PACKET_MAX; i++)
14432 {
14433 /* Ideally all configs would have a command associated. Some
14434 still don't though. */
14435 int excepted;
14436
14437 switch (i)
14438 {
14439 case PACKET_QNonStop:
14440 case PACKET_EnableDisableTracepoints_feature:
14441 case PACKET_tracenz_feature:
14442 case PACKET_DisconnectedTracing_feature:
14443 case PACKET_augmented_libraries_svr4_read_feature:
14444 case PACKET_qCRC:
14445 /* Additions to this list need to be well justified:
14446 pre-existing packets are OK; new packets are not. */
14447 excepted = 1;
14448 break;
14449 default:
14450 excepted = 0;
14451 break;
14452 }
14453
14454 /* This catches both forgetting to add a config command, and
14455 forgetting to remove a packet from the exception list. */
14456 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14457 }
14458 }
14459
14460 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14461 Z sub-packet has its own set and show commands, but users may
14462 have sets to this variable in their .gdbinit files (or in their
14463 documentation). */
14464 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14465 &remote_Z_packet_detect, _("\
14466 Set use of remote protocol `Z' packets"), _("\
14467 Show use of remote protocol `Z' packets "), _("\
14468 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14469 packets."),
14470 set_remote_protocol_Z_packet_cmd,
14471 show_remote_protocol_Z_packet_cmd,
14472 /* FIXME: i18n: Use of remote protocol
14473 `Z' packets is %s. */
14474 &remote_set_cmdlist, &remote_show_cmdlist);
14475
14476 add_prefix_cmd ("remote", class_files, remote_command, _("\
14477 Manipulate files on the remote system\n\
14478 Transfer files to and from the remote target system."),
14479 &remote_cmdlist, "remote ",
14480 0 /* allow-unknown */, &cmdlist);
14481
14482 add_cmd ("put", class_files, remote_put_command,
14483 _("Copy a local file to the remote system."),
14484 &remote_cmdlist);
14485
14486 add_cmd ("get", class_files, remote_get_command,
14487 _("Copy a remote file to the local system."),
14488 &remote_cmdlist);
14489
14490 add_cmd ("delete", class_files, remote_delete_command,
14491 _("Delete a remote file."),
14492 &remote_cmdlist);
14493
14494 add_setshow_string_noescape_cmd ("exec-file", class_files,
14495 &remote_exec_file_var, _("\
14496 Set the remote pathname for \"run\""), _("\
14497 Show the remote pathname for \"run\""), NULL,
14498 set_remote_exec_file,
14499 show_remote_exec_file,
14500 &remote_set_cmdlist,
14501 &remote_show_cmdlist);
14502
14503 add_setshow_boolean_cmd ("range-stepping", class_run,
14504 &use_range_stepping, _("\
14505 Enable or disable range stepping."), _("\
14506 Show whether target-assisted range stepping is enabled."), _("\
14507 If on, and the target supports it, when stepping a source line, GDB\n\
14508 tells the target to step the corresponding range of addresses itself instead\n\
14509 of issuing multiple single-steps. This speeds up source level\n\
14510 stepping. If off, GDB always issues single-steps, even if range\n\
14511 stepping is supported by the target. The default is on."),
14512 set_range_stepping,
14513 show_range_stepping,
14514 &setlist,
14515 &showlist);
14516
14517 /* Eventually initialize fileio. See fileio.c */
14518 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14519
14520 /* Take advantage of the fact that the TID field is not used, to tag
14521 special ptids with it set to != 0. */
14522 magic_null_ptid = ptid_build (42000, -1, 1);
14523 not_sent_ptid = ptid_build (42000, -2, 1);
14524 any_thread_ptid = ptid_build (42000, 0, 1);
14525
14526 target_buf_size = 2048;
14527 target_buf = (char *) xmalloc (target_buf_size);
14528 }
14529
This page took 0.318074 seconds and 5 git commands to generate.