New vCtrlC packet, non-stop mode equivalent of \003
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2015 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
74 /* Temp hacks for tracepoint encoding migration. */
75 static char *target_buf;
76 static long target_buf_size;
77
78 /* Per-program-space data key. */
79 static const struct program_space_data *remote_pspace_data;
80
81 /* The variable registered as the control variable used by the
82 remote exec-file commands. While the remote exec-file setting is
83 per-program-space, the set/show machinery uses this as the
84 location of the remote exec-file value. */
85 static char *remote_exec_file_var;
86
87 /* The size to align memory write packets, when practical. The protocol
88 does not guarantee any alignment, and gdb will generate short
89 writes and unaligned writes, but even as a best-effort attempt this
90 can improve bulk transfers. For instance, if a write is misaligned
91 relative to the target's data bus, the stub may need to make an extra
92 round trip fetching data from the target. This doesn't make a
93 huge difference, but it's easy to do, so we try to be helpful.
94
95 The alignment chosen is arbitrary; usually data bus width is
96 important here, not the possibly larger cache line size. */
97 enum { REMOTE_ALIGN_WRITES = 16 };
98
99 /* Prototypes for local functions. */
100 static void async_cleanup_sigint_signal_handler (void *dummy);
101 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
102 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
103 int forever, int *is_notif);
104
105 static void async_handle_remote_sigint (int);
106 static void async_handle_remote_sigint_twice (int);
107
108 static void remote_files_info (struct target_ops *ignore);
109
110 static void remote_prepare_to_store (struct target_ops *self,
111 struct regcache *regcache);
112
113 static void remote_open_1 (const char *, int, struct target_ops *,
114 int extended_p);
115
116 static void remote_close (struct target_ops *self);
117
118 struct remote_state;
119
120 static int remote_vkill (int pid, struct remote_state *rs);
121
122 static void remote_mourn (struct target_ops *ops);
123
124 static void extended_remote_restart (void);
125
126 static void extended_remote_mourn (struct target_ops *);
127
128 static void remote_send (char **buf, long *sizeof_buf_p);
129
130 static int readchar (int timeout);
131
132 static void remote_serial_write (const char *str, int len);
133
134 static void remote_kill (struct target_ops *ops);
135
136 static int remote_can_async_p (struct target_ops *);
137
138 static int remote_is_async_p (struct target_ops *);
139
140 static void remote_async (struct target_ops *ops, int enable);
141
142 static void sync_remote_interrupt_twice (int signo);
143
144 static void interrupt_query (void);
145
146 static void set_general_thread (struct ptid ptid);
147 static void set_continue_thread (struct ptid ptid);
148
149 static void get_offsets (void);
150
151 static void skip_frame (void);
152
153 static long read_frame (char **buf_p, long *sizeof_buf);
154
155 static int hexnumlen (ULONGEST num);
156
157 static void init_remote_ops (void);
158
159 static void init_extended_remote_ops (void);
160
161 static void remote_stop (struct target_ops *self, ptid_t);
162
163 static int stubhex (int ch);
164
165 static int hexnumstr (char *, ULONGEST);
166
167 static int hexnumnstr (char *, ULONGEST, int);
168
169 static CORE_ADDR remote_address_masked (CORE_ADDR);
170
171 static void print_packet (const char *);
172
173 static void compare_sections_command (char *, int);
174
175 static void packet_command (char *, int);
176
177 static int stub_unpack_int (char *buff, int fieldlength);
178
179 static ptid_t remote_current_thread (ptid_t oldptid);
180
181 static int putpkt_binary (const char *buf, int cnt);
182
183 static void check_binary_download (CORE_ADDR addr);
184
185 struct packet_config;
186
187 static void show_packet_config_cmd (struct packet_config *config);
188
189 static void show_remote_protocol_packet_cmd (struct ui_file *file,
190 int from_tty,
191 struct cmd_list_element *c,
192 const char *value);
193
194 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
195 static ptid_t read_ptid (char *buf, char **obuf);
196
197 static void remote_set_permissions (struct target_ops *self);
198
199 static int remote_get_trace_status (struct target_ops *self,
200 struct trace_status *ts);
201
202 static int remote_upload_tracepoints (struct target_ops *self,
203 struct uploaded_tp **utpp);
204
205 static int remote_upload_trace_state_variables (struct target_ops *self,
206 struct uploaded_tsv **utsvp);
207
208 static void remote_query_supported (void);
209
210 static void remote_check_symbols (void);
211
212 void _initialize_remote (void);
213
214 struct stop_reply;
215 static void stop_reply_xfree (struct stop_reply *);
216 static void remote_parse_stop_reply (char *, struct stop_reply *);
217 static void push_stop_reply (struct stop_reply *);
218 static void discard_pending_stop_replies_in_queue (struct remote_state *);
219 static int peek_stop_reply (ptid_t ptid);
220
221 struct threads_listing_context;
222 static void remove_new_fork_children (struct threads_listing_context *);
223
224 static void remote_async_inferior_event_handler (gdb_client_data);
225
226 static void remote_terminal_ours (struct target_ops *self);
227
228 static int remote_read_description_p (struct target_ops *target);
229
230 static void remote_console_output (char *msg);
231
232 static int remote_supports_cond_breakpoints (struct target_ops *self);
233
234 static int remote_can_run_breakpoint_commands (struct target_ops *self);
235
236 static void remote_btrace_reset (void);
237
238 static int stop_reply_queue_length (void);
239
240 static void readahead_cache_invalidate (void);
241
242 /* For "remote". */
243
244 static struct cmd_list_element *remote_cmdlist;
245
246 /* For "set remote" and "show remote". */
247
248 static struct cmd_list_element *remote_set_cmdlist;
249 static struct cmd_list_element *remote_show_cmdlist;
250
251 /* Stub vCont actions support.
252
253 Each field is a boolean flag indicating whether the stub reports
254 support for the corresponding action. */
255
256 struct vCont_action_support
257 {
258 /* vCont;t */
259 int t;
260
261 /* vCont;r */
262 int r;
263
264 /* vCont;s */
265 int s;
266
267 /* vCont;S */
268 int S;
269 };
270
271 /* Controls whether GDB is willing to use range stepping. */
272
273 static int use_range_stepping = 1;
274
275 #define OPAQUETHREADBYTES 8
276
277 /* a 64 bit opaque identifier */
278 typedef unsigned char threadref[OPAQUETHREADBYTES];
279
280 /* About this many threadisds fit in a packet. */
281
282 #define MAXTHREADLISTRESULTS 32
283
284 /* Data for the vFile:pread readahead cache. */
285
286 struct readahead_cache
287 {
288 /* The file descriptor for the file that is being cached. -1 if the
289 cache is invalid. */
290 int fd;
291
292 /* The offset into the file that the cache buffer corresponds
293 to. */
294 ULONGEST offset;
295
296 /* The buffer holding the cache contents. */
297 gdb_byte *buf;
298 /* The buffer's size. We try to read as much as fits into a packet
299 at a time. */
300 size_t bufsize;
301
302 /* Cache hit and miss counters. */
303 ULONGEST hit_count;
304 ULONGEST miss_count;
305 };
306
307 /* Description of the remote protocol state for the currently
308 connected target. This is per-target state, and independent of the
309 selected architecture. */
310
311 struct remote_state
312 {
313 /* A buffer to use for incoming packets, and its current size. The
314 buffer is grown dynamically for larger incoming packets.
315 Outgoing packets may also be constructed in this buffer.
316 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
317 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
318 packets. */
319 char *buf;
320 long buf_size;
321
322 /* True if we're going through initial connection setup (finding out
323 about the remote side's threads, relocating symbols, etc.). */
324 int starting_up;
325
326 /* If we negotiated packet size explicitly (and thus can bypass
327 heuristics for the largest packet size that will not overflow
328 a buffer in the stub), this will be set to that packet size.
329 Otherwise zero, meaning to use the guessed size. */
330 long explicit_packet_size;
331
332 /* remote_wait is normally called when the target is running and
333 waits for a stop reply packet. But sometimes we need to call it
334 when the target is already stopped. We can send a "?" packet
335 and have remote_wait read the response. Or, if we already have
336 the response, we can stash it in BUF and tell remote_wait to
337 skip calling getpkt. This flag is set when BUF contains a
338 stop reply packet and the target is not waiting. */
339 int cached_wait_status;
340
341 /* True, if in no ack mode. That is, neither GDB nor the stub will
342 expect acks from each other. The connection is assumed to be
343 reliable. */
344 int noack_mode;
345
346 /* True if we're connected in extended remote mode. */
347 int extended;
348
349 /* True if we resumed the target and we're waiting for the target to
350 stop. In the mean time, we can't start another command/query.
351 The remote server wouldn't be ready to process it, so we'd
352 timeout waiting for a reply that would never come and eventually
353 we'd close the connection. This can happen in asynchronous mode
354 because we allow GDB commands while the target is running. */
355 int waiting_for_stop_reply;
356
357 /* The status of the stub support for the various vCont actions. */
358 struct vCont_action_support supports_vCont;
359
360 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
361 responded to that. */
362 int ctrlc_pending_p;
363
364 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
365 remote_open knows that we don't have a file open when the program
366 starts. */
367 struct serial *remote_desc;
368
369 /* These are the threads which we last sent to the remote system. The
370 TID member will be -1 for all or -2 for not sent yet. */
371 ptid_t general_thread;
372 ptid_t continue_thread;
373
374 /* This is the traceframe which we last selected on the remote system.
375 It will be -1 if no traceframe is selected. */
376 int remote_traceframe_number;
377
378 char *last_pass_packet;
379
380 /* The last QProgramSignals packet sent to the target. We bypass
381 sending a new program signals list down to the target if the new
382 packet is exactly the same as the last we sent. IOW, we only let
383 the target know about program signals list changes. */
384 char *last_program_signals_packet;
385
386 enum gdb_signal last_sent_signal;
387
388 int last_sent_step;
389
390 char *finished_object;
391 char *finished_annex;
392 ULONGEST finished_offset;
393
394 /* Should we try the 'ThreadInfo' query packet?
395
396 This variable (NOT available to the user: auto-detect only!)
397 determines whether GDB will use the new, simpler "ThreadInfo"
398 query or the older, more complex syntax for thread queries.
399 This is an auto-detect variable (set to true at each connect,
400 and set to false when the target fails to recognize it). */
401 int use_threadinfo_query;
402 int use_threadextra_query;
403
404 threadref echo_nextthread;
405 threadref nextthread;
406 threadref resultthreadlist[MAXTHREADLISTRESULTS];
407
408 /* The state of remote notification. */
409 struct remote_notif_state *notif_state;
410
411 /* The branch trace configuration. */
412 struct btrace_config btrace_config;
413
414 /* The argument to the last "vFile:setfs:" packet we sent, used
415 to avoid sending repeated unnecessary "vFile:setfs:" packets.
416 Initialized to -1 to indicate that no "vFile:setfs:" packet
417 has yet been sent. */
418 int fs_pid;
419
420 /* A readahead cache for vFile:pread. Often, reading a binary
421 involves a sequence of small reads. E.g., when parsing an ELF
422 file. A readahead cache helps mostly the case of remote
423 debugging on a connection with higher latency, due to the
424 request/reply nature of the RSP. We only cache data for a single
425 file descriptor at a time. */
426 struct readahead_cache readahead_cache;
427 };
428
429 /* Private data that we'll store in (struct thread_info)->private. */
430 struct private_thread_info
431 {
432 char *extra;
433 char *name;
434 int core;
435
436 /* Whether the target stopped for a breakpoint/watchpoint. */
437 enum target_stop_reason stop_reason;
438
439 /* This is set to the data address of the access causing the target
440 to stop for a watchpoint. */
441 CORE_ADDR watch_data_address;
442 };
443
444 static void
445 free_private_thread_info (struct private_thread_info *info)
446 {
447 xfree (info->extra);
448 xfree (info->name);
449 xfree (info);
450 }
451
452 /* This data could be associated with a target, but we do not always
453 have access to the current target when we need it, so for now it is
454 static. This will be fine for as long as only one target is in use
455 at a time. */
456 static struct remote_state *remote_state;
457
458 static struct remote_state *
459 get_remote_state_raw (void)
460 {
461 return remote_state;
462 }
463
464 /* Allocate a new struct remote_state with xmalloc, initialize it, and
465 return it. */
466
467 static struct remote_state *
468 new_remote_state (void)
469 {
470 struct remote_state *result = XCNEW (struct remote_state);
471
472 /* The default buffer size is unimportant; it will be expanded
473 whenever a larger buffer is needed. */
474 result->buf_size = 400;
475 result->buf = (char *) xmalloc (result->buf_size);
476 result->remote_traceframe_number = -1;
477 result->last_sent_signal = GDB_SIGNAL_0;
478 result->fs_pid = -1;
479
480 return result;
481 }
482
483 /* Description of the remote protocol for a given architecture. */
484
485 struct packet_reg
486 {
487 long offset; /* Offset into G packet. */
488 long regnum; /* GDB's internal register number. */
489 LONGEST pnum; /* Remote protocol register number. */
490 int in_g_packet; /* Always part of G packet. */
491 /* long size in bytes; == register_size (target_gdbarch (), regnum);
492 at present. */
493 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
494 at present. */
495 };
496
497 struct remote_arch_state
498 {
499 /* Description of the remote protocol registers. */
500 long sizeof_g_packet;
501
502 /* Description of the remote protocol registers indexed by REGNUM
503 (making an array gdbarch_num_regs in size). */
504 struct packet_reg *regs;
505
506 /* This is the size (in chars) of the first response to the ``g''
507 packet. It is used as a heuristic when determining the maximum
508 size of memory-read and memory-write packets. A target will
509 typically only reserve a buffer large enough to hold the ``g''
510 packet. The size does not include packet overhead (headers and
511 trailers). */
512 long actual_register_packet_size;
513
514 /* This is the maximum size (in chars) of a non read/write packet.
515 It is also used as a cap on the size of read/write packets. */
516 long remote_packet_size;
517 };
518
519 /* Utility: generate error from an incoming stub packet. */
520 static void
521 trace_error (char *buf)
522 {
523 if (*buf++ != 'E')
524 return; /* not an error msg */
525 switch (*buf)
526 {
527 case '1': /* malformed packet error */
528 if (*++buf == '0') /* general case: */
529 error (_("remote.c: error in outgoing packet."));
530 else
531 error (_("remote.c: error in outgoing packet at field #%ld."),
532 strtol (buf, NULL, 16));
533 default:
534 error (_("Target returns error code '%s'."), buf);
535 }
536 }
537
538 /* Utility: wait for reply from stub, while accepting "O" packets. */
539 static char *
540 remote_get_noisy_reply (char **buf_p,
541 long *sizeof_buf)
542 {
543 do /* Loop on reply from remote stub. */
544 {
545 char *buf;
546
547 QUIT; /* Allow user to bail out with ^C. */
548 getpkt (buf_p, sizeof_buf, 0);
549 buf = *buf_p;
550 if (buf[0] == 'E')
551 trace_error (buf);
552 else if (startswith (buf, "qRelocInsn:"))
553 {
554 ULONGEST ul;
555 CORE_ADDR from, to, org_to;
556 char *p, *pp;
557 int adjusted_size = 0;
558 int relocated = 0;
559
560 p = buf + strlen ("qRelocInsn:");
561 pp = unpack_varlen_hex (p, &ul);
562 if (*pp != ';')
563 error (_("invalid qRelocInsn packet: %s"), buf);
564 from = ul;
565
566 p = pp + 1;
567 unpack_varlen_hex (p, &ul);
568 to = ul;
569
570 org_to = to;
571
572 TRY
573 {
574 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
575 relocated = 1;
576 }
577 CATCH (ex, RETURN_MASK_ALL)
578 {
579 if (ex.error == MEMORY_ERROR)
580 {
581 /* Propagate memory errors silently back to the
582 target. The stub may have limited the range of
583 addresses we can write to, for example. */
584 }
585 else
586 {
587 /* Something unexpectedly bad happened. Be verbose
588 so we can tell what, and propagate the error back
589 to the stub, so it doesn't get stuck waiting for
590 a response. */
591 exception_fprintf (gdb_stderr, ex,
592 _("warning: relocating instruction: "));
593 }
594 putpkt ("E01");
595 }
596 END_CATCH
597
598 if (relocated)
599 {
600 adjusted_size = to - org_to;
601
602 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
603 putpkt (buf);
604 }
605 }
606 else if (buf[0] == 'O' && buf[1] != 'K')
607 remote_console_output (buf + 1); /* 'O' message from stub */
608 else
609 return buf; /* Here's the actual reply. */
610 }
611 while (1);
612 }
613
614 /* Handle for retreving the remote protocol data from gdbarch. */
615 static struct gdbarch_data *remote_gdbarch_data_handle;
616
617 static struct remote_arch_state *
618 get_remote_arch_state (void)
619 {
620 gdb_assert (target_gdbarch () != NULL);
621 return ((struct remote_arch_state *)
622 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
623 }
624
625 /* Fetch the global remote target state. */
626
627 static struct remote_state *
628 get_remote_state (void)
629 {
630 /* Make sure that the remote architecture state has been
631 initialized, because doing so might reallocate rs->buf. Any
632 function which calls getpkt also needs to be mindful of changes
633 to rs->buf, but this call limits the number of places which run
634 into trouble. */
635 get_remote_arch_state ();
636
637 return get_remote_state_raw ();
638 }
639
640 /* Cleanup routine for the remote module's pspace data. */
641
642 static void
643 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
644 {
645 char *remote_exec_file = (char *) arg;
646
647 xfree (remote_exec_file);
648 }
649
650 /* Fetch the remote exec-file from the current program space. */
651
652 static const char *
653 get_remote_exec_file (void)
654 {
655 char *remote_exec_file;
656
657 remote_exec_file
658 = (char *) program_space_data (current_program_space,
659 remote_pspace_data);
660 if (remote_exec_file == NULL)
661 return "";
662
663 return remote_exec_file;
664 }
665
666 /* Set the remote exec file for PSPACE. */
667
668 static void
669 set_pspace_remote_exec_file (struct program_space *pspace,
670 char *remote_exec_file)
671 {
672 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
673
674 xfree (old_file);
675 set_program_space_data (pspace, remote_pspace_data,
676 xstrdup (remote_exec_file));
677 }
678
679 /* The "set/show remote exec-file" set command hook. */
680
681 static void
682 set_remote_exec_file (char *ignored, int from_tty,
683 struct cmd_list_element *c)
684 {
685 gdb_assert (remote_exec_file_var != NULL);
686 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
687 }
688
689 /* The "set/show remote exec-file" show command hook. */
690
691 static void
692 show_remote_exec_file (struct ui_file *file, int from_tty,
693 struct cmd_list_element *cmd, const char *value)
694 {
695 fprintf_filtered (file, "%s\n", remote_exec_file_var);
696 }
697
698 static int
699 compare_pnums (const void *lhs_, const void *rhs_)
700 {
701 const struct packet_reg * const *lhs
702 = (const struct packet_reg * const *) lhs_;
703 const struct packet_reg * const *rhs
704 = (const struct packet_reg * const *) rhs_;
705
706 if ((*lhs)->pnum < (*rhs)->pnum)
707 return -1;
708 else if ((*lhs)->pnum == (*rhs)->pnum)
709 return 0;
710 else
711 return 1;
712 }
713
714 static int
715 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
716 {
717 int regnum, num_remote_regs, offset;
718 struct packet_reg **remote_regs;
719
720 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
721 {
722 struct packet_reg *r = &regs[regnum];
723
724 if (register_size (gdbarch, regnum) == 0)
725 /* Do not try to fetch zero-sized (placeholder) registers. */
726 r->pnum = -1;
727 else
728 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
729
730 r->regnum = regnum;
731 }
732
733 /* Define the g/G packet format as the contents of each register
734 with a remote protocol number, in order of ascending protocol
735 number. */
736
737 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
738 for (num_remote_regs = 0, regnum = 0;
739 regnum < gdbarch_num_regs (gdbarch);
740 regnum++)
741 if (regs[regnum].pnum != -1)
742 remote_regs[num_remote_regs++] = &regs[regnum];
743
744 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
745 compare_pnums);
746
747 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
748 {
749 remote_regs[regnum]->in_g_packet = 1;
750 remote_regs[regnum]->offset = offset;
751 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
752 }
753
754 return offset;
755 }
756
757 /* Given the architecture described by GDBARCH, return the remote
758 protocol register's number and the register's offset in the g/G
759 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
760 If the target does not have a mapping for REGNUM, return false,
761 otherwise, return true. */
762
763 int
764 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
765 int *pnum, int *poffset)
766 {
767 int sizeof_g_packet;
768 struct packet_reg *regs;
769 struct cleanup *old_chain;
770
771 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
772
773 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
774 old_chain = make_cleanup (xfree, regs);
775
776 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
777
778 *pnum = regs[regnum].pnum;
779 *poffset = regs[regnum].offset;
780
781 do_cleanups (old_chain);
782
783 return *pnum != -1;
784 }
785
786 static void *
787 init_remote_state (struct gdbarch *gdbarch)
788 {
789 struct remote_state *rs = get_remote_state_raw ();
790 struct remote_arch_state *rsa;
791
792 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
793
794 /* Use the architecture to build a regnum<->pnum table, which will be
795 1:1 unless a feature set specifies otherwise. */
796 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
797 gdbarch_num_regs (gdbarch),
798 struct packet_reg);
799
800 /* Record the maximum possible size of the g packet - it may turn out
801 to be smaller. */
802 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
803
804 /* Default maximum number of characters in a packet body. Many
805 remote stubs have a hardwired buffer size of 400 bytes
806 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
807 as the maximum packet-size to ensure that the packet and an extra
808 NUL character can always fit in the buffer. This stops GDB
809 trashing stubs that try to squeeze an extra NUL into what is
810 already a full buffer (As of 1999-12-04 that was most stubs). */
811 rsa->remote_packet_size = 400 - 1;
812
813 /* This one is filled in when a ``g'' packet is received. */
814 rsa->actual_register_packet_size = 0;
815
816 /* Should rsa->sizeof_g_packet needs more space than the
817 default, adjust the size accordingly. Remember that each byte is
818 encoded as two characters. 32 is the overhead for the packet
819 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
820 (``$NN:G...#NN'') is a better guess, the below has been padded a
821 little. */
822 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
823 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
824
825 /* Make sure that the packet buffer is plenty big enough for
826 this architecture. */
827 if (rs->buf_size < rsa->remote_packet_size)
828 {
829 rs->buf_size = 2 * rsa->remote_packet_size;
830 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
831 }
832
833 return rsa;
834 }
835
836 /* Return the current allowed size of a remote packet. This is
837 inferred from the current architecture, and should be used to
838 limit the length of outgoing packets. */
839 static long
840 get_remote_packet_size (void)
841 {
842 struct remote_state *rs = get_remote_state ();
843 struct remote_arch_state *rsa = get_remote_arch_state ();
844
845 if (rs->explicit_packet_size)
846 return rs->explicit_packet_size;
847
848 return rsa->remote_packet_size;
849 }
850
851 static struct packet_reg *
852 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
853 {
854 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
855 return NULL;
856 else
857 {
858 struct packet_reg *r = &rsa->regs[regnum];
859
860 gdb_assert (r->regnum == regnum);
861 return r;
862 }
863 }
864
865 static struct packet_reg *
866 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
867 {
868 int i;
869
870 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
871 {
872 struct packet_reg *r = &rsa->regs[i];
873
874 if (r->pnum == pnum)
875 return r;
876 }
877 return NULL;
878 }
879
880 static struct target_ops remote_ops;
881
882 static struct target_ops extended_remote_ops;
883
884 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
885 ``forever'' still use the normal timeout mechanism. This is
886 currently used by the ASYNC code to guarentee that target reads
887 during the initial connect always time-out. Once getpkt has been
888 modified to return a timeout indication and, in turn
889 remote_wait()/wait_for_inferior() have gained a timeout parameter
890 this can go away. */
891 static int wait_forever_enabled_p = 1;
892
893 /* Allow the user to specify what sequence to send to the remote
894 when he requests a program interruption: Although ^C is usually
895 what remote systems expect (this is the default, here), it is
896 sometimes preferable to send a break. On other systems such
897 as the Linux kernel, a break followed by g, which is Magic SysRq g
898 is required in order to interrupt the execution. */
899 const char interrupt_sequence_control_c[] = "Ctrl-C";
900 const char interrupt_sequence_break[] = "BREAK";
901 const char interrupt_sequence_break_g[] = "BREAK-g";
902 static const char *const interrupt_sequence_modes[] =
903 {
904 interrupt_sequence_control_c,
905 interrupt_sequence_break,
906 interrupt_sequence_break_g,
907 NULL
908 };
909 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
910
911 static void
912 show_interrupt_sequence (struct ui_file *file, int from_tty,
913 struct cmd_list_element *c,
914 const char *value)
915 {
916 if (interrupt_sequence_mode == interrupt_sequence_control_c)
917 fprintf_filtered (file,
918 _("Send the ASCII ETX character (Ctrl-c) "
919 "to the remote target to interrupt the "
920 "execution of the program.\n"));
921 else if (interrupt_sequence_mode == interrupt_sequence_break)
922 fprintf_filtered (file,
923 _("send a break signal to the remote target "
924 "to interrupt the execution of the program.\n"));
925 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
926 fprintf_filtered (file,
927 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
928 "the remote target to interrupt the execution "
929 "of Linux kernel.\n"));
930 else
931 internal_error (__FILE__, __LINE__,
932 _("Invalid value for interrupt_sequence_mode: %s."),
933 interrupt_sequence_mode);
934 }
935
936 /* This boolean variable specifies whether interrupt_sequence is sent
937 to the remote target when gdb connects to it.
938 This is mostly needed when you debug the Linux kernel: The Linux kernel
939 expects BREAK g which is Magic SysRq g for connecting gdb. */
940 static int interrupt_on_connect = 0;
941
942 /* This variable is used to implement the "set/show remotebreak" commands.
943 Since these commands are now deprecated in favor of "set/show remote
944 interrupt-sequence", it no longer has any effect on the code. */
945 static int remote_break;
946
947 static void
948 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
949 {
950 if (remote_break)
951 interrupt_sequence_mode = interrupt_sequence_break;
952 else
953 interrupt_sequence_mode = interrupt_sequence_control_c;
954 }
955
956 static void
957 show_remotebreak (struct ui_file *file, int from_tty,
958 struct cmd_list_element *c,
959 const char *value)
960 {
961 }
962
963 /* This variable sets the number of bits in an address that are to be
964 sent in a memory ("M" or "m") packet. Normally, after stripping
965 leading zeros, the entire address would be sent. This variable
966 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
967 initial implementation of remote.c restricted the address sent in
968 memory packets to ``host::sizeof long'' bytes - (typically 32
969 bits). Consequently, for 64 bit targets, the upper 32 bits of an
970 address was never sent. Since fixing this bug may cause a break in
971 some remote targets this variable is principly provided to
972 facilitate backward compatibility. */
973
974 static unsigned int remote_address_size;
975
976 /* Temporary to track who currently owns the terminal. See
977 remote_terminal_* for more details. */
978
979 static int remote_async_terminal_ours_p;
980
981 \f
982 /* User configurable variables for the number of characters in a
983 memory read/write packet. MIN (rsa->remote_packet_size,
984 rsa->sizeof_g_packet) is the default. Some targets need smaller
985 values (fifo overruns, et.al.) and some users need larger values
986 (speed up transfers). The variables ``preferred_*'' (the user
987 request), ``current_*'' (what was actually set) and ``forced_*''
988 (Positive - a soft limit, negative - a hard limit). */
989
990 struct memory_packet_config
991 {
992 char *name;
993 long size;
994 int fixed_p;
995 };
996
997 /* The default max memory-write-packet-size. The 16k is historical.
998 (It came from older GDB's using alloca for buffers and the
999 knowledge (folklore?) that some hosts don't cope very well with
1000 large alloca calls.) */
1001 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1002
1003 /* The minimum remote packet size for memory transfers. Ensures we
1004 can write at least one byte. */
1005 #define MIN_MEMORY_PACKET_SIZE 20
1006
1007 /* Compute the current size of a read/write packet. Since this makes
1008 use of ``actual_register_packet_size'' the computation is dynamic. */
1009
1010 static long
1011 get_memory_packet_size (struct memory_packet_config *config)
1012 {
1013 struct remote_state *rs = get_remote_state ();
1014 struct remote_arch_state *rsa = get_remote_arch_state ();
1015
1016 long what_they_get;
1017 if (config->fixed_p)
1018 {
1019 if (config->size <= 0)
1020 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1021 else
1022 what_they_get = config->size;
1023 }
1024 else
1025 {
1026 what_they_get = get_remote_packet_size ();
1027 /* Limit the packet to the size specified by the user. */
1028 if (config->size > 0
1029 && what_they_get > config->size)
1030 what_they_get = config->size;
1031
1032 /* Limit it to the size of the targets ``g'' response unless we have
1033 permission from the stub to use a larger packet size. */
1034 if (rs->explicit_packet_size == 0
1035 && rsa->actual_register_packet_size > 0
1036 && what_they_get > rsa->actual_register_packet_size)
1037 what_they_get = rsa->actual_register_packet_size;
1038 }
1039 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1040 what_they_get = MIN_MEMORY_PACKET_SIZE;
1041
1042 /* Make sure there is room in the global buffer for this packet
1043 (including its trailing NUL byte). */
1044 if (rs->buf_size < what_they_get + 1)
1045 {
1046 rs->buf_size = 2 * what_they_get;
1047 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1048 }
1049
1050 return what_they_get;
1051 }
1052
1053 /* Update the size of a read/write packet. If they user wants
1054 something really big then do a sanity check. */
1055
1056 static void
1057 set_memory_packet_size (char *args, struct memory_packet_config *config)
1058 {
1059 int fixed_p = config->fixed_p;
1060 long size = config->size;
1061
1062 if (args == NULL)
1063 error (_("Argument required (integer, `fixed' or `limited')."));
1064 else if (strcmp (args, "hard") == 0
1065 || strcmp (args, "fixed") == 0)
1066 fixed_p = 1;
1067 else if (strcmp (args, "soft") == 0
1068 || strcmp (args, "limit") == 0)
1069 fixed_p = 0;
1070 else
1071 {
1072 char *end;
1073
1074 size = strtoul (args, &end, 0);
1075 if (args == end)
1076 error (_("Invalid %s (bad syntax)."), config->name);
1077
1078 /* Instead of explicitly capping the size of a packet to or
1079 disallowing it, the user is allowed to set the size to
1080 something arbitrarily large. */
1081 }
1082
1083 /* So that the query shows the correct value. */
1084 if (size <= 0)
1085 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1086
1087 /* Extra checks? */
1088 if (fixed_p && !config->fixed_p)
1089 {
1090 if (! query (_("The target may not be able to correctly handle a %s\n"
1091 "of %ld bytes. Change the packet size? "),
1092 config->name, size))
1093 error (_("Packet size not changed."));
1094 }
1095 /* Update the config. */
1096 config->fixed_p = fixed_p;
1097 config->size = size;
1098 }
1099
1100 static void
1101 show_memory_packet_size (struct memory_packet_config *config)
1102 {
1103 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1104 if (config->fixed_p)
1105 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1106 get_memory_packet_size (config));
1107 else
1108 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1109 get_memory_packet_size (config));
1110 }
1111
1112 static struct memory_packet_config memory_write_packet_config =
1113 {
1114 "memory-write-packet-size",
1115 };
1116
1117 static void
1118 set_memory_write_packet_size (char *args, int from_tty)
1119 {
1120 set_memory_packet_size (args, &memory_write_packet_config);
1121 }
1122
1123 static void
1124 show_memory_write_packet_size (char *args, int from_tty)
1125 {
1126 show_memory_packet_size (&memory_write_packet_config);
1127 }
1128
1129 static long
1130 get_memory_write_packet_size (void)
1131 {
1132 return get_memory_packet_size (&memory_write_packet_config);
1133 }
1134
1135 static struct memory_packet_config memory_read_packet_config =
1136 {
1137 "memory-read-packet-size",
1138 };
1139
1140 static void
1141 set_memory_read_packet_size (char *args, int from_tty)
1142 {
1143 set_memory_packet_size (args, &memory_read_packet_config);
1144 }
1145
1146 static void
1147 show_memory_read_packet_size (char *args, int from_tty)
1148 {
1149 show_memory_packet_size (&memory_read_packet_config);
1150 }
1151
1152 static long
1153 get_memory_read_packet_size (void)
1154 {
1155 long size = get_memory_packet_size (&memory_read_packet_config);
1156
1157 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1158 extra buffer size argument before the memory read size can be
1159 increased beyond this. */
1160 if (size > get_remote_packet_size ())
1161 size = get_remote_packet_size ();
1162 return size;
1163 }
1164
1165 \f
1166 /* Generic configuration support for packets the stub optionally
1167 supports. Allows the user to specify the use of the packet as well
1168 as allowing GDB to auto-detect support in the remote stub. */
1169
1170 enum packet_support
1171 {
1172 PACKET_SUPPORT_UNKNOWN = 0,
1173 PACKET_ENABLE,
1174 PACKET_DISABLE
1175 };
1176
1177 struct packet_config
1178 {
1179 const char *name;
1180 const char *title;
1181
1182 /* If auto, GDB auto-detects support for this packet or feature,
1183 either through qSupported, or by trying the packet and looking
1184 at the response. If true, GDB assumes the target supports this
1185 packet. If false, the packet is disabled. Configs that don't
1186 have an associated command always have this set to auto. */
1187 enum auto_boolean detect;
1188
1189 /* Does the target support this packet? */
1190 enum packet_support support;
1191 };
1192
1193 /* Analyze a packet's return value and update the packet config
1194 accordingly. */
1195
1196 enum packet_result
1197 {
1198 PACKET_ERROR,
1199 PACKET_OK,
1200 PACKET_UNKNOWN
1201 };
1202
1203 static enum packet_support packet_config_support (struct packet_config *config);
1204 static enum packet_support packet_support (int packet);
1205
1206 static void
1207 show_packet_config_cmd (struct packet_config *config)
1208 {
1209 char *support = "internal-error";
1210
1211 switch (packet_config_support (config))
1212 {
1213 case PACKET_ENABLE:
1214 support = "enabled";
1215 break;
1216 case PACKET_DISABLE:
1217 support = "disabled";
1218 break;
1219 case PACKET_SUPPORT_UNKNOWN:
1220 support = "unknown";
1221 break;
1222 }
1223 switch (config->detect)
1224 {
1225 case AUTO_BOOLEAN_AUTO:
1226 printf_filtered (_("Support for the `%s' packet "
1227 "is auto-detected, currently %s.\n"),
1228 config->name, support);
1229 break;
1230 case AUTO_BOOLEAN_TRUE:
1231 case AUTO_BOOLEAN_FALSE:
1232 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1233 config->name, support);
1234 break;
1235 }
1236 }
1237
1238 static void
1239 add_packet_config_cmd (struct packet_config *config, const char *name,
1240 const char *title, int legacy)
1241 {
1242 char *set_doc;
1243 char *show_doc;
1244 char *cmd_name;
1245
1246 config->name = name;
1247 config->title = title;
1248 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1249 name, title);
1250 show_doc = xstrprintf ("Show current use of remote "
1251 "protocol `%s' (%s) packet",
1252 name, title);
1253 /* set/show TITLE-packet {auto,on,off} */
1254 cmd_name = xstrprintf ("%s-packet", title);
1255 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1256 &config->detect, set_doc,
1257 show_doc, NULL, /* help_doc */
1258 NULL,
1259 show_remote_protocol_packet_cmd,
1260 &remote_set_cmdlist, &remote_show_cmdlist);
1261 /* The command code copies the documentation strings. */
1262 xfree (set_doc);
1263 xfree (show_doc);
1264 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1265 if (legacy)
1266 {
1267 char *legacy_name;
1268
1269 legacy_name = xstrprintf ("%s-packet", name);
1270 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1271 &remote_set_cmdlist);
1272 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1273 &remote_show_cmdlist);
1274 }
1275 }
1276
1277 static enum packet_result
1278 packet_check_result (const char *buf)
1279 {
1280 if (buf[0] != '\0')
1281 {
1282 /* The stub recognized the packet request. Check that the
1283 operation succeeded. */
1284 if (buf[0] == 'E'
1285 && isxdigit (buf[1]) && isxdigit (buf[2])
1286 && buf[3] == '\0')
1287 /* "Enn" - definitly an error. */
1288 return PACKET_ERROR;
1289
1290 /* Always treat "E." as an error. This will be used for
1291 more verbose error messages, such as E.memtypes. */
1292 if (buf[0] == 'E' && buf[1] == '.')
1293 return PACKET_ERROR;
1294
1295 /* The packet may or may not be OK. Just assume it is. */
1296 return PACKET_OK;
1297 }
1298 else
1299 /* The stub does not support the packet. */
1300 return PACKET_UNKNOWN;
1301 }
1302
1303 static enum packet_result
1304 packet_ok (const char *buf, struct packet_config *config)
1305 {
1306 enum packet_result result;
1307
1308 if (config->detect != AUTO_BOOLEAN_TRUE
1309 && config->support == PACKET_DISABLE)
1310 internal_error (__FILE__, __LINE__,
1311 _("packet_ok: attempt to use a disabled packet"));
1312
1313 result = packet_check_result (buf);
1314 switch (result)
1315 {
1316 case PACKET_OK:
1317 case PACKET_ERROR:
1318 /* The stub recognized the packet request. */
1319 if (config->support == PACKET_SUPPORT_UNKNOWN)
1320 {
1321 if (remote_debug)
1322 fprintf_unfiltered (gdb_stdlog,
1323 "Packet %s (%s) is supported\n",
1324 config->name, config->title);
1325 config->support = PACKET_ENABLE;
1326 }
1327 break;
1328 case PACKET_UNKNOWN:
1329 /* The stub does not support the packet. */
1330 if (config->detect == AUTO_BOOLEAN_AUTO
1331 && config->support == PACKET_ENABLE)
1332 {
1333 /* If the stub previously indicated that the packet was
1334 supported then there is a protocol error. */
1335 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1336 config->name, config->title);
1337 }
1338 else if (config->detect == AUTO_BOOLEAN_TRUE)
1339 {
1340 /* The user set it wrong. */
1341 error (_("Enabled packet %s (%s) not recognized by stub"),
1342 config->name, config->title);
1343 }
1344
1345 if (remote_debug)
1346 fprintf_unfiltered (gdb_stdlog,
1347 "Packet %s (%s) is NOT supported\n",
1348 config->name, config->title);
1349 config->support = PACKET_DISABLE;
1350 break;
1351 }
1352
1353 return result;
1354 }
1355
1356 enum {
1357 PACKET_vCont = 0,
1358 PACKET_X,
1359 PACKET_qSymbol,
1360 PACKET_P,
1361 PACKET_p,
1362 PACKET_Z0,
1363 PACKET_Z1,
1364 PACKET_Z2,
1365 PACKET_Z3,
1366 PACKET_Z4,
1367 PACKET_vFile_setfs,
1368 PACKET_vFile_open,
1369 PACKET_vFile_pread,
1370 PACKET_vFile_pwrite,
1371 PACKET_vFile_close,
1372 PACKET_vFile_unlink,
1373 PACKET_vFile_readlink,
1374 PACKET_vFile_fstat,
1375 PACKET_qXfer_auxv,
1376 PACKET_qXfer_features,
1377 PACKET_qXfer_exec_file,
1378 PACKET_qXfer_libraries,
1379 PACKET_qXfer_libraries_svr4,
1380 PACKET_qXfer_memory_map,
1381 PACKET_qXfer_spu_read,
1382 PACKET_qXfer_spu_write,
1383 PACKET_qXfer_osdata,
1384 PACKET_qXfer_threads,
1385 PACKET_qXfer_statictrace_read,
1386 PACKET_qXfer_traceframe_info,
1387 PACKET_qXfer_uib,
1388 PACKET_qGetTIBAddr,
1389 PACKET_qGetTLSAddr,
1390 PACKET_qSupported,
1391 PACKET_qTStatus,
1392 PACKET_QPassSignals,
1393 PACKET_QProgramSignals,
1394 PACKET_qCRC,
1395 PACKET_qSearch_memory,
1396 PACKET_vAttach,
1397 PACKET_vRun,
1398 PACKET_QStartNoAckMode,
1399 PACKET_vKill,
1400 PACKET_qXfer_siginfo_read,
1401 PACKET_qXfer_siginfo_write,
1402 PACKET_qAttached,
1403
1404 /* Support for conditional tracepoints. */
1405 PACKET_ConditionalTracepoints,
1406
1407 /* Support for target-side breakpoint conditions. */
1408 PACKET_ConditionalBreakpoints,
1409
1410 /* Support for target-side breakpoint commands. */
1411 PACKET_BreakpointCommands,
1412
1413 /* Support for fast tracepoints. */
1414 PACKET_FastTracepoints,
1415
1416 /* Support for static tracepoints. */
1417 PACKET_StaticTracepoints,
1418
1419 /* Support for installing tracepoints while a trace experiment is
1420 running. */
1421 PACKET_InstallInTrace,
1422
1423 PACKET_bc,
1424 PACKET_bs,
1425 PACKET_TracepointSource,
1426 PACKET_QAllow,
1427 PACKET_qXfer_fdpic,
1428 PACKET_QDisableRandomization,
1429 PACKET_QAgent,
1430 PACKET_QTBuffer_size,
1431 PACKET_Qbtrace_off,
1432 PACKET_Qbtrace_bts,
1433 PACKET_Qbtrace_pt,
1434 PACKET_qXfer_btrace,
1435
1436 /* Support for the QNonStop packet. */
1437 PACKET_QNonStop,
1438
1439 /* Support for multi-process extensions. */
1440 PACKET_multiprocess_feature,
1441
1442 /* Support for enabling and disabling tracepoints while a trace
1443 experiment is running. */
1444 PACKET_EnableDisableTracepoints_feature,
1445
1446 /* Support for collecting strings using the tracenz bytecode. */
1447 PACKET_tracenz_feature,
1448
1449 /* Support for continuing to run a trace experiment while GDB is
1450 disconnected. */
1451 PACKET_DisconnectedTracing_feature,
1452
1453 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1454 PACKET_augmented_libraries_svr4_read_feature,
1455
1456 /* Support for the qXfer:btrace-conf:read packet. */
1457 PACKET_qXfer_btrace_conf,
1458
1459 /* Support for the Qbtrace-conf:bts:size packet. */
1460 PACKET_Qbtrace_conf_bts_size,
1461
1462 /* Support for swbreak+ feature. */
1463 PACKET_swbreak_feature,
1464
1465 /* Support for hwbreak+ feature. */
1466 PACKET_hwbreak_feature,
1467
1468 /* Support for fork events. */
1469 PACKET_fork_event_feature,
1470
1471 /* Support for vfork events. */
1472 PACKET_vfork_event_feature,
1473
1474 /* Support for the Qbtrace-conf:pt:size packet. */
1475 PACKET_Qbtrace_conf_pt_size,
1476
1477 /* Support for exec events. */
1478 PACKET_exec_event_feature,
1479
1480 /* Support for query supported vCont actions. */
1481 PACKET_vContSupported,
1482
1483 /* Support remote CTRL-C. */
1484 PACKET_vCtrlC,
1485
1486 PACKET_MAX
1487 };
1488
1489 static struct packet_config remote_protocol_packets[PACKET_MAX];
1490
1491 /* Returns the packet's corresponding "set remote foo-packet" command
1492 state. See struct packet_config for more details. */
1493
1494 static enum auto_boolean
1495 packet_set_cmd_state (int packet)
1496 {
1497 return remote_protocol_packets[packet].detect;
1498 }
1499
1500 /* Returns whether a given packet or feature is supported. This takes
1501 into account the state of the corresponding "set remote foo-packet"
1502 command, which may be used to bypass auto-detection. */
1503
1504 static enum packet_support
1505 packet_config_support (struct packet_config *config)
1506 {
1507 switch (config->detect)
1508 {
1509 case AUTO_BOOLEAN_TRUE:
1510 return PACKET_ENABLE;
1511 case AUTO_BOOLEAN_FALSE:
1512 return PACKET_DISABLE;
1513 case AUTO_BOOLEAN_AUTO:
1514 return config->support;
1515 default:
1516 gdb_assert_not_reached (_("bad switch"));
1517 }
1518 }
1519
1520 /* Same as packet_config_support, but takes the packet's enum value as
1521 argument. */
1522
1523 static enum packet_support
1524 packet_support (int packet)
1525 {
1526 struct packet_config *config = &remote_protocol_packets[packet];
1527
1528 return packet_config_support (config);
1529 }
1530
1531 static void
1532 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1533 struct cmd_list_element *c,
1534 const char *value)
1535 {
1536 struct packet_config *packet;
1537
1538 for (packet = remote_protocol_packets;
1539 packet < &remote_protocol_packets[PACKET_MAX];
1540 packet++)
1541 {
1542 if (&packet->detect == c->var)
1543 {
1544 show_packet_config_cmd (packet);
1545 return;
1546 }
1547 }
1548 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1549 c->name);
1550 }
1551
1552 /* Should we try one of the 'Z' requests? */
1553
1554 enum Z_packet_type
1555 {
1556 Z_PACKET_SOFTWARE_BP,
1557 Z_PACKET_HARDWARE_BP,
1558 Z_PACKET_WRITE_WP,
1559 Z_PACKET_READ_WP,
1560 Z_PACKET_ACCESS_WP,
1561 NR_Z_PACKET_TYPES
1562 };
1563
1564 /* For compatibility with older distributions. Provide a ``set remote
1565 Z-packet ...'' command that updates all the Z packet types. */
1566
1567 static enum auto_boolean remote_Z_packet_detect;
1568
1569 static void
1570 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1571 struct cmd_list_element *c)
1572 {
1573 int i;
1574
1575 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1576 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1577 }
1578
1579 static void
1580 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1581 struct cmd_list_element *c,
1582 const char *value)
1583 {
1584 int i;
1585
1586 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1587 {
1588 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1589 }
1590 }
1591
1592 /* Returns true if the multi-process extensions are in effect. */
1593
1594 static int
1595 remote_multi_process_p (struct remote_state *rs)
1596 {
1597 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1598 }
1599
1600 /* Returns true if fork events are supported. */
1601
1602 static int
1603 remote_fork_event_p (struct remote_state *rs)
1604 {
1605 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1606 }
1607
1608 /* Returns true if vfork events are supported. */
1609
1610 static int
1611 remote_vfork_event_p (struct remote_state *rs)
1612 {
1613 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1614 }
1615
1616 /* Returns true if exec events are supported. */
1617
1618 static int
1619 remote_exec_event_p (struct remote_state *rs)
1620 {
1621 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1622 }
1623
1624 /* Insert fork catchpoint target routine. If fork events are enabled
1625 then return success, nothing more to do. */
1626
1627 static int
1628 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1629 {
1630 struct remote_state *rs = get_remote_state ();
1631
1632 return !remote_fork_event_p (rs);
1633 }
1634
1635 /* Remove fork catchpoint target routine. Nothing to do, just
1636 return success. */
1637
1638 static int
1639 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1640 {
1641 return 0;
1642 }
1643
1644 /* Insert vfork catchpoint target routine. If vfork events are enabled
1645 then return success, nothing more to do. */
1646
1647 static int
1648 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1649 {
1650 struct remote_state *rs = get_remote_state ();
1651
1652 return !remote_vfork_event_p (rs);
1653 }
1654
1655 /* Remove vfork catchpoint target routine. Nothing to do, just
1656 return success. */
1657
1658 static int
1659 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1660 {
1661 return 0;
1662 }
1663
1664 /* Insert exec catchpoint target routine. If exec events are
1665 enabled, just return success. */
1666
1667 static int
1668 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1669 {
1670 struct remote_state *rs = get_remote_state ();
1671
1672 return !remote_exec_event_p (rs);
1673 }
1674
1675 /* Remove exec catchpoint target routine. Nothing to do, just
1676 return success. */
1677
1678 static int
1679 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1680 {
1681 return 0;
1682 }
1683
1684 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1685 static struct async_signal_handler *async_sigint_remote_twice_token;
1686 static struct async_signal_handler *async_sigint_remote_token;
1687
1688 \f
1689 /* Asynchronous signal handle registered as event loop source for
1690 when we have pending events ready to be passed to the core. */
1691
1692 static struct async_event_handler *remote_async_inferior_event_token;
1693
1694 \f
1695
1696 static ptid_t magic_null_ptid;
1697 static ptid_t not_sent_ptid;
1698 static ptid_t any_thread_ptid;
1699
1700 /* Find out if the stub attached to PID (and hence GDB should offer to
1701 detach instead of killing it when bailing out). */
1702
1703 static int
1704 remote_query_attached (int pid)
1705 {
1706 struct remote_state *rs = get_remote_state ();
1707 size_t size = get_remote_packet_size ();
1708
1709 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1710 return 0;
1711
1712 if (remote_multi_process_p (rs))
1713 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1714 else
1715 xsnprintf (rs->buf, size, "qAttached");
1716
1717 putpkt (rs->buf);
1718 getpkt (&rs->buf, &rs->buf_size, 0);
1719
1720 switch (packet_ok (rs->buf,
1721 &remote_protocol_packets[PACKET_qAttached]))
1722 {
1723 case PACKET_OK:
1724 if (strcmp (rs->buf, "1") == 0)
1725 return 1;
1726 break;
1727 case PACKET_ERROR:
1728 warning (_("Remote failure reply: %s"), rs->buf);
1729 break;
1730 case PACKET_UNKNOWN:
1731 break;
1732 }
1733
1734 return 0;
1735 }
1736
1737 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1738 has been invented by GDB, instead of reported by the target. Since
1739 we can be connected to a remote system before before knowing about
1740 any inferior, mark the target with execution when we find the first
1741 inferior. If ATTACHED is 1, then we had just attached to this
1742 inferior. If it is 0, then we just created this inferior. If it
1743 is -1, then try querying the remote stub to find out if it had
1744 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1745 attempt to open this inferior's executable as the main executable
1746 if no main executable is open already. */
1747
1748 static struct inferior *
1749 remote_add_inferior (int fake_pid_p, int pid, int attached,
1750 int try_open_exec)
1751 {
1752 struct inferior *inf;
1753
1754 /* Check whether this process we're learning about is to be
1755 considered attached, or if is to be considered to have been
1756 spawned by the stub. */
1757 if (attached == -1)
1758 attached = remote_query_attached (pid);
1759
1760 if (gdbarch_has_global_solist (target_gdbarch ()))
1761 {
1762 /* If the target shares code across all inferiors, then every
1763 attach adds a new inferior. */
1764 inf = add_inferior (pid);
1765
1766 /* ... and every inferior is bound to the same program space.
1767 However, each inferior may still have its own address
1768 space. */
1769 inf->aspace = maybe_new_address_space ();
1770 inf->pspace = current_program_space;
1771 }
1772 else
1773 {
1774 /* In the traditional debugging scenario, there's a 1-1 match
1775 between program/address spaces. We simply bind the inferior
1776 to the program space's address space. */
1777 inf = current_inferior ();
1778 inferior_appeared (inf, pid);
1779 }
1780
1781 inf->attach_flag = attached;
1782 inf->fake_pid_p = fake_pid_p;
1783
1784 /* If no main executable is currently open then attempt to
1785 open the file that was executed to create this inferior. */
1786 if (try_open_exec && get_exec_file (0) == NULL)
1787 exec_file_locate_attach (pid, 1);
1788
1789 return inf;
1790 }
1791
1792 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1793 according to RUNNING. */
1794
1795 static void
1796 remote_add_thread (ptid_t ptid, int running)
1797 {
1798 struct remote_state *rs = get_remote_state ();
1799
1800 /* GDB historically didn't pull threads in the initial connection
1801 setup. If the remote target doesn't even have a concept of
1802 threads (e.g., a bare-metal target), even if internally we
1803 consider that a single-threaded target, mentioning a new thread
1804 might be confusing to the user. Be silent then, preserving the
1805 age old behavior. */
1806 if (rs->starting_up)
1807 add_thread_silent (ptid);
1808 else
1809 add_thread (ptid);
1810
1811 set_executing (ptid, running);
1812 set_running (ptid, running);
1813 }
1814
1815 /* Come here when we learn about a thread id from the remote target.
1816 It may be the first time we hear about such thread, so take the
1817 opportunity to add it to GDB's thread list. In case this is the
1818 first time we're noticing its corresponding inferior, add it to
1819 GDB's inferior list as well. */
1820
1821 static void
1822 remote_notice_new_inferior (ptid_t currthread, int running)
1823 {
1824 /* If this is a new thread, add it to GDB's thread list.
1825 If we leave it up to WFI to do this, bad things will happen. */
1826
1827 if (in_thread_list (currthread) && is_exited (currthread))
1828 {
1829 /* We're seeing an event on a thread id we knew had exited.
1830 This has to be a new thread reusing the old id. Add it. */
1831 remote_add_thread (currthread, running);
1832 return;
1833 }
1834
1835 if (!in_thread_list (currthread))
1836 {
1837 struct inferior *inf = NULL;
1838 int pid = ptid_get_pid (currthread);
1839
1840 if (ptid_is_pid (inferior_ptid)
1841 && pid == ptid_get_pid (inferior_ptid))
1842 {
1843 /* inferior_ptid has no thread member yet. This can happen
1844 with the vAttach -> remote_wait,"TAAthread:" path if the
1845 stub doesn't support qC. This is the first stop reported
1846 after an attach, so this is the main thread. Update the
1847 ptid in the thread list. */
1848 if (in_thread_list (pid_to_ptid (pid)))
1849 thread_change_ptid (inferior_ptid, currthread);
1850 else
1851 {
1852 remote_add_thread (currthread, running);
1853 inferior_ptid = currthread;
1854 }
1855 return;
1856 }
1857
1858 if (ptid_equal (magic_null_ptid, inferior_ptid))
1859 {
1860 /* inferior_ptid is not set yet. This can happen with the
1861 vRun -> remote_wait,"TAAthread:" path if the stub
1862 doesn't support qC. This is the first stop reported
1863 after an attach, so this is the main thread. Update the
1864 ptid in the thread list. */
1865 thread_change_ptid (inferior_ptid, currthread);
1866 return;
1867 }
1868
1869 /* When connecting to a target remote, or to a target
1870 extended-remote which already was debugging an inferior, we
1871 may not know about it yet. Add it before adding its child
1872 thread, so notifications are emitted in a sensible order. */
1873 if (!in_inferior_list (ptid_get_pid (currthread)))
1874 {
1875 struct remote_state *rs = get_remote_state ();
1876 int fake_pid_p = !remote_multi_process_p (rs);
1877
1878 inf = remote_add_inferior (fake_pid_p,
1879 ptid_get_pid (currthread), -1, 1);
1880 }
1881
1882 /* This is really a new thread. Add it. */
1883 remote_add_thread (currthread, running);
1884
1885 /* If we found a new inferior, let the common code do whatever
1886 it needs to with it (e.g., read shared libraries, insert
1887 breakpoints), unless we're just setting up an all-stop
1888 connection. */
1889 if (inf != NULL)
1890 {
1891 struct remote_state *rs = get_remote_state ();
1892
1893 if (!rs->starting_up)
1894 notice_new_inferior (currthread, running, 0);
1895 }
1896 }
1897 }
1898
1899 /* Return the private thread data, creating it if necessary. */
1900
1901 static struct private_thread_info *
1902 demand_private_info (ptid_t ptid)
1903 {
1904 struct thread_info *info = find_thread_ptid (ptid);
1905
1906 gdb_assert (info);
1907
1908 if (!info->priv)
1909 {
1910 info->priv = XNEW (struct private_thread_info);
1911 info->private_dtor = free_private_thread_info;
1912 info->priv->core = -1;
1913 info->priv->extra = 0;
1914 }
1915
1916 return info->priv;
1917 }
1918
1919 /* Call this function as a result of
1920 1) A halt indication (T packet) containing a thread id
1921 2) A direct query of currthread
1922 3) Successful execution of set thread */
1923
1924 static void
1925 record_currthread (struct remote_state *rs, ptid_t currthread)
1926 {
1927 rs->general_thread = currthread;
1928 }
1929
1930 /* If 'QPassSignals' is supported, tell the remote stub what signals
1931 it can simply pass through to the inferior without reporting. */
1932
1933 static void
1934 remote_pass_signals (struct target_ops *self,
1935 int numsigs, unsigned char *pass_signals)
1936 {
1937 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1938 {
1939 char *pass_packet, *p;
1940 int count = 0, i;
1941 struct remote_state *rs = get_remote_state ();
1942
1943 gdb_assert (numsigs < 256);
1944 for (i = 0; i < numsigs; i++)
1945 {
1946 if (pass_signals[i])
1947 count++;
1948 }
1949 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1950 strcpy (pass_packet, "QPassSignals:");
1951 p = pass_packet + strlen (pass_packet);
1952 for (i = 0; i < numsigs; i++)
1953 {
1954 if (pass_signals[i])
1955 {
1956 if (i >= 16)
1957 *p++ = tohex (i >> 4);
1958 *p++ = tohex (i & 15);
1959 if (count)
1960 *p++ = ';';
1961 else
1962 break;
1963 count--;
1964 }
1965 }
1966 *p = 0;
1967 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1968 {
1969 putpkt (pass_packet);
1970 getpkt (&rs->buf, &rs->buf_size, 0);
1971 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1972 if (rs->last_pass_packet)
1973 xfree (rs->last_pass_packet);
1974 rs->last_pass_packet = pass_packet;
1975 }
1976 else
1977 xfree (pass_packet);
1978 }
1979 }
1980
1981 /* If 'QProgramSignals' is supported, tell the remote stub what
1982 signals it should pass through to the inferior when detaching. */
1983
1984 static void
1985 remote_program_signals (struct target_ops *self,
1986 int numsigs, unsigned char *signals)
1987 {
1988 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1989 {
1990 char *packet, *p;
1991 int count = 0, i;
1992 struct remote_state *rs = get_remote_state ();
1993
1994 gdb_assert (numsigs < 256);
1995 for (i = 0; i < numsigs; i++)
1996 {
1997 if (signals[i])
1998 count++;
1999 }
2000 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2001 strcpy (packet, "QProgramSignals:");
2002 p = packet + strlen (packet);
2003 for (i = 0; i < numsigs; i++)
2004 {
2005 if (signal_pass_state (i))
2006 {
2007 if (i >= 16)
2008 *p++ = tohex (i >> 4);
2009 *p++ = tohex (i & 15);
2010 if (count)
2011 *p++ = ';';
2012 else
2013 break;
2014 count--;
2015 }
2016 }
2017 *p = 0;
2018 if (!rs->last_program_signals_packet
2019 || strcmp (rs->last_program_signals_packet, packet) != 0)
2020 {
2021 putpkt (packet);
2022 getpkt (&rs->buf, &rs->buf_size, 0);
2023 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2024 xfree (rs->last_program_signals_packet);
2025 rs->last_program_signals_packet = packet;
2026 }
2027 else
2028 xfree (packet);
2029 }
2030 }
2031
2032 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2033 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2034 thread. If GEN is set, set the general thread, if not, then set
2035 the step/continue thread. */
2036 static void
2037 set_thread (struct ptid ptid, int gen)
2038 {
2039 struct remote_state *rs = get_remote_state ();
2040 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2041 char *buf = rs->buf;
2042 char *endbuf = rs->buf + get_remote_packet_size ();
2043
2044 if (ptid_equal (state, ptid))
2045 return;
2046
2047 *buf++ = 'H';
2048 *buf++ = gen ? 'g' : 'c';
2049 if (ptid_equal (ptid, magic_null_ptid))
2050 xsnprintf (buf, endbuf - buf, "0");
2051 else if (ptid_equal (ptid, any_thread_ptid))
2052 xsnprintf (buf, endbuf - buf, "0");
2053 else if (ptid_equal (ptid, minus_one_ptid))
2054 xsnprintf (buf, endbuf - buf, "-1");
2055 else
2056 write_ptid (buf, endbuf, ptid);
2057 putpkt (rs->buf);
2058 getpkt (&rs->buf, &rs->buf_size, 0);
2059 if (gen)
2060 rs->general_thread = ptid;
2061 else
2062 rs->continue_thread = ptid;
2063 }
2064
2065 static void
2066 set_general_thread (struct ptid ptid)
2067 {
2068 set_thread (ptid, 1);
2069 }
2070
2071 static void
2072 set_continue_thread (struct ptid ptid)
2073 {
2074 set_thread (ptid, 0);
2075 }
2076
2077 /* Change the remote current process. Which thread within the process
2078 ends up selected isn't important, as long as it is the same process
2079 as what INFERIOR_PTID points to.
2080
2081 This comes from that fact that there is no explicit notion of
2082 "selected process" in the protocol. The selected process for
2083 general operations is the process the selected general thread
2084 belongs to. */
2085
2086 static void
2087 set_general_process (void)
2088 {
2089 struct remote_state *rs = get_remote_state ();
2090
2091 /* If the remote can't handle multiple processes, don't bother. */
2092 if (!rs->extended || !remote_multi_process_p (rs))
2093 return;
2094
2095 /* We only need to change the remote current thread if it's pointing
2096 at some other process. */
2097 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2098 set_general_thread (inferior_ptid);
2099 }
2100
2101 \f
2102 /* Return nonzero if this is the main thread that we made up ourselves
2103 to model non-threaded targets as single-threaded. */
2104
2105 static int
2106 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2107 {
2108 struct remote_state *rs = get_remote_state ();
2109 char *p, *endp;
2110
2111 if (ptid_equal (ptid, magic_null_ptid))
2112 /* The main thread is always alive. */
2113 return 1;
2114
2115 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2116 /* The main thread is always alive. This can happen after a
2117 vAttach, if the remote side doesn't support
2118 multi-threading. */
2119 return 1;
2120
2121 return 0;
2122 }
2123
2124 /* Return nonzero if the thread PTID is still alive on the remote
2125 system. */
2126
2127 static int
2128 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2129 {
2130 struct remote_state *rs = get_remote_state ();
2131 char *p, *endp;
2132
2133 /* Check if this is a thread that we made up ourselves to model
2134 non-threaded targets as single-threaded. */
2135 if (remote_thread_always_alive (ops, ptid))
2136 return 1;
2137
2138 p = rs->buf;
2139 endp = rs->buf + get_remote_packet_size ();
2140
2141 *p++ = 'T';
2142 write_ptid (p, endp, ptid);
2143
2144 putpkt (rs->buf);
2145 getpkt (&rs->buf, &rs->buf_size, 0);
2146 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2147 }
2148
2149 /* Return a pointer to a thread name if we know it and NULL otherwise.
2150 The thread_info object owns the memory for the name. */
2151
2152 static const char *
2153 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2154 {
2155 if (info->priv != NULL)
2156 return info->priv->name;
2157
2158 return NULL;
2159 }
2160
2161 /* About these extended threadlist and threadinfo packets. They are
2162 variable length packets but, the fields within them are often fixed
2163 length. They are redundent enough to send over UDP as is the
2164 remote protocol in general. There is a matching unit test module
2165 in libstub. */
2166
2167 /* WARNING: This threadref data structure comes from the remote O.S.,
2168 libstub protocol encoding, and remote.c. It is not particularly
2169 changable. */
2170
2171 /* Right now, the internal structure is int. We want it to be bigger.
2172 Plan to fix this. */
2173
2174 typedef int gdb_threadref; /* Internal GDB thread reference. */
2175
2176 /* gdb_ext_thread_info is an internal GDB data structure which is
2177 equivalent to the reply of the remote threadinfo packet. */
2178
2179 struct gdb_ext_thread_info
2180 {
2181 threadref threadid; /* External form of thread reference. */
2182 int active; /* Has state interesting to GDB?
2183 regs, stack. */
2184 char display[256]; /* Brief state display, name,
2185 blocked/suspended. */
2186 char shortname[32]; /* To be used to name threads. */
2187 char more_display[256]; /* Long info, statistics, queue depth,
2188 whatever. */
2189 };
2190
2191 /* The volume of remote transfers can be limited by submitting
2192 a mask containing bits specifying the desired information.
2193 Use a union of these values as the 'selection' parameter to
2194 get_thread_info. FIXME: Make these TAG names more thread specific. */
2195
2196 #define TAG_THREADID 1
2197 #define TAG_EXISTS 2
2198 #define TAG_DISPLAY 4
2199 #define TAG_THREADNAME 8
2200 #define TAG_MOREDISPLAY 16
2201
2202 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2203
2204 static char *unpack_nibble (char *buf, int *val);
2205
2206 static char *unpack_byte (char *buf, int *value);
2207
2208 static char *pack_int (char *buf, int value);
2209
2210 static char *unpack_int (char *buf, int *value);
2211
2212 static char *unpack_string (char *src, char *dest, int length);
2213
2214 static char *pack_threadid (char *pkt, threadref *id);
2215
2216 static char *unpack_threadid (char *inbuf, threadref *id);
2217
2218 void int_to_threadref (threadref *id, int value);
2219
2220 static int threadref_to_int (threadref *ref);
2221
2222 static void copy_threadref (threadref *dest, threadref *src);
2223
2224 static int threadmatch (threadref *dest, threadref *src);
2225
2226 static char *pack_threadinfo_request (char *pkt, int mode,
2227 threadref *id);
2228
2229 static int remote_unpack_thread_info_response (char *pkt,
2230 threadref *expectedref,
2231 struct gdb_ext_thread_info
2232 *info);
2233
2234
2235 static int remote_get_threadinfo (threadref *threadid,
2236 int fieldset, /*TAG mask */
2237 struct gdb_ext_thread_info *info);
2238
2239 static char *pack_threadlist_request (char *pkt, int startflag,
2240 int threadcount,
2241 threadref *nextthread);
2242
2243 static int parse_threadlist_response (char *pkt,
2244 int result_limit,
2245 threadref *original_echo,
2246 threadref *resultlist,
2247 int *doneflag);
2248
2249 static int remote_get_threadlist (int startflag,
2250 threadref *nextthread,
2251 int result_limit,
2252 int *done,
2253 int *result_count,
2254 threadref *threadlist);
2255
2256 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2257
2258 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2259 void *context, int looplimit);
2260
2261 static int remote_newthread_step (threadref *ref, void *context);
2262
2263
2264 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2265 buffer we're allowed to write to. Returns
2266 BUF+CHARACTERS_WRITTEN. */
2267
2268 static char *
2269 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2270 {
2271 int pid, tid;
2272 struct remote_state *rs = get_remote_state ();
2273
2274 if (remote_multi_process_p (rs))
2275 {
2276 pid = ptid_get_pid (ptid);
2277 if (pid < 0)
2278 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2279 else
2280 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2281 }
2282 tid = ptid_get_lwp (ptid);
2283 if (tid < 0)
2284 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2285 else
2286 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2287
2288 return buf;
2289 }
2290
2291 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2292 passed the last parsed char. Returns null_ptid on error. */
2293
2294 static ptid_t
2295 read_ptid (char *buf, char **obuf)
2296 {
2297 char *p = buf;
2298 char *pp;
2299 ULONGEST pid = 0, tid = 0;
2300
2301 if (*p == 'p')
2302 {
2303 /* Multi-process ptid. */
2304 pp = unpack_varlen_hex (p + 1, &pid);
2305 if (*pp != '.')
2306 error (_("invalid remote ptid: %s"), p);
2307
2308 p = pp;
2309 pp = unpack_varlen_hex (p + 1, &tid);
2310 if (obuf)
2311 *obuf = pp;
2312 return ptid_build (pid, tid, 0);
2313 }
2314
2315 /* No multi-process. Just a tid. */
2316 pp = unpack_varlen_hex (p, &tid);
2317
2318 /* Return null_ptid when no thread id is found. */
2319 if (p == pp)
2320 {
2321 if (obuf)
2322 *obuf = pp;
2323 return null_ptid;
2324 }
2325
2326 /* Since the stub is not sending a process id, then default to
2327 what's in inferior_ptid, unless it's null at this point. If so,
2328 then since there's no way to know the pid of the reported
2329 threads, use the magic number. */
2330 if (ptid_equal (inferior_ptid, null_ptid))
2331 pid = ptid_get_pid (magic_null_ptid);
2332 else
2333 pid = ptid_get_pid (inferior_ptid);
2334
2335 if (obuf)
2336 *obuf = pp;
2337 return ptid_build (pid, tid, 0);
2338 }
2339
2340 static int
2341 stubhex (int ch)
2342 {
2343 if (ch >= 'a' && ch <= 'f')
2344 return ch - 'a' + 10;
2345 if (ch >= '0' && ch <= '9')
2346 return ch - '0';
2347 if (ch >= 'A' && ch <= 'F')
2348 return ch - 'A' + 10;
2349 return -1;
2350 }
2351
2352 static int
2353 stub_unpack_int (char *buff, int fieldlength)
2354 {
2355 int nibble;
2356 int retval = 0;
2357
2358 while (fieldlength)
2359 {
2360 nibble = stubhex (*buff++);
2361 retval |= nibble;
2362 fieldlength--;
2363 if (fieldlength)
2364 retval = retval << 4;
2365 }
2366 return retval;
2367 }
2368
2369 static char *
2370 unpack_nibble (char *buf, int *val)
2371 {
2372 *val = fromhex (*buf++);
2373 return buf;
2374 }
2375
2376 static char *
2377 unpack_byte (char *buf, int *value)
2378 {
2379 *value = stub_unpack_int (buf, 2);
2380 return buf + 2;
2381 }
2382
2383 static char *
2384 pack_int (char *buf, int value)
2385 {
2386 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2387 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2388 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2389 buf = pack_hex_byte (buf, (value & 0xff));
2390 return buf;
2391 }
2392
2393 static char *
2394 unpack_int (char *buf, int *value)
2395 {
2396 *value = stub_unpack_int (buf, 8);
2397 return buf + 8;
2398 }
2399
2400 #if 0 /* Currently unused, uncomment when needed. */
2401 static char *pack_string (char *pkt, char *string);
2402
2403 static char *
2404 pack_string (char *pkt, char *string)
2405 {
2406 char ch;
2407 int len;
2408
2409 len = strlen (string);
2410 if (len > 200)
2411 len = 200; /* Bigger than most GDB packets, junk??? */
2412 pkt = pack_hex_byte (pkt, len);
2413 while (len-- > 0)
2414 {
2415 ch = *string++;
2416 if ((ch == '\0') || (ch == '#'))
2417 ch = '*'; /* Protect encapsulation. */
2418 *pkt++ = ch;
2419 }
2420 return pkt;
2421 }
2422 #endif /* 0 (unused) */
2423
2424 static char *
2425 unpack_string (char *src, char *dest, int length)
2426 {
2427 while (length--)
2428 *dest++ = *src++;
2429 *dest = '\0';
2430 return src;
2431 }
2432
2433 static char *
2434 pack_threadid (char *pkt, threadref *id)
2435 {
2436 char *limit;
2437 unsigned char *altid;
2438
2439 altid = (unsigned char *) id;
2440 limit = pkt + BUF_THREAD_ID_SIZE;
2441 while (pkt < limit)
2442 pkt = pack_hex_byte (pkt, *altid++);
2443 return pkt;
2444 }
2445
2446
2447 static char *
2448 unpack_threadid (char *inbuf, threadref *id)
2449 {
2450 char *altref;
2451 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2452 int x, y;
2453
2454 altref = (char *) id;
2455
2456 while (inbuf < limit)
2457 {
2458 x = stubhex (*inbuf++);
2459 y = stubhex (*inbuf++);
2460 *altref++ = (x << 4) | y;
2461 }
2462 return inbuf;
2463 }
2464
2465 /* Externally, threadrefs are 64 bits but internally, they are still
2466 ints. This is due to a mismatch of specifications. We would like
2467 to use 64bit thread references internally. This is an adapter
2468 function. */
2469
2470 void
2471 int_to_threadref (threadref *id, int value)
2472 {
2473 unsigned char *scan;
2474
2475 scan = (unsigned char *) id;
2476 {
2477 int i = 4;
2478 while (i--)
2479 *scan++ = 0;
2480 }
2481 *scan++ = (value >> 24) & 0xff;
2482 *scan++ = (value >> 16) & 0xff;
2483 *scan++ = (value >> 8) & 0xff;
2484 *scan++ = (value & 0xff);
2485 }
2486
2487 static int
2488 threadref_to_int (threadref *ref)
2489 {
2490 int i, value = 0;
2491 unsigned char *scan;
2492
2493 scan = *ref;
2494 scan += 4;
2495 i = 4;
2496 while (i-- > 0)
2497 value = (value << 8) | ((*scan++) & 0xff);
2498 return value;
2499 }
2500
2501 static void
2502 copy_threadref (threadref *dest, threadref *src)
2503 {
2504 int i;
2505 unsigned char *csrc, *cdest;
2506
2507 csrc = (unsigned char *) src;
2508 cdest = (unsigned char *) dest;
2509 i = 8;
2510 while (i--)
2511 *cdest++ = *csrc++;
2512 }
2513
2514 static int
2515 threadmatch (threadref *dest, threadref *src)
2516 {
2517 /* Things are broken right now, so just assume we got a match. */
2518 #if 0
2519 unsigned char *srcp, *destp;
2520 int i, result;
2521 srcp = (char *) src;
2522 destp = (char *) dest;
2523
2524 result = 1;
2525 while (i-- > 0)
2526 result &= (*srcp++ == *destp++) ? 1 : 0;
2527 return result;
2528 #endif
2529 return 1;
2530 }
2531
2532 /*
2533 threadid:1, # always request threadid
2534 context_exists:2,
2535 display:4,
2536 unique_name:8,
2537 more_display:16
2538 */
2539
2540 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2541
2542 static char *
2543 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2544 {
2545 *pkt++ = 'q'; /* Info Query */
2546 *pkt++ = 'P'; /* process or thread info */
2547 pkt = pack_int (pkt, mode); /* mode */
2548 pkt = pack_threadid (pkt, id); /* threadid */
2549 *pkt = '\0'; /* terminate */
2550 return pkt;
2551 }
2552
2553 /* These values tag the fields in a thread info response packet. */
2554 /* Tagging the fields allows us to request specific fields and to
2555 add more fields as time goes by. */
2556
2557 #define TAG_THREADID 1 /* Echo the thread identifier. */
2558 #define TAG_EXISTS 2 /* Is this process defined enough to
2559 fetch registers and its stack? */
2560 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2561 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2562 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2563 the process. */
2564
2565 static int
2566 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2567 struct gdb_ext_thread_info *info)
2568 {
2569 struct remote_state *rs = get_remote_state ();
2570 int mask, length;
2571 int tag;
2572 threadref ref;
2573 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2574 int retval = 1;
2575
2576 /* info->threadid = 0; FIXME: implement zero_threadref. */
2577 info->active = 0;
2578 info->display[0] = '\0';
2579 info->shortname[0] = '\0';
2580 info->more_display[0] = '\0';
2581
2582 /* Assume the characters indicating the packet type have been
2583 stripped. */
2584 pkt = unpack_int (pkt, &mask); /* arg mask */
2585 pkt = unpack_threadid (pkt, &ref);
2586
2587 if (mask == 0)
2588 warning (_("Incomplete response to threadinfo request."));
2589 if (!threadmatch (&ref, expectedref))
2590 { /* This is an answer to a different request. */
2591 warning (_("ERROR RMT Thread info mismatch."));
2592 return 0;
2593 }
2594 copy_threadref (&info->threadid, &ref);
2595
2596 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2597
2598 /* Packets are terminated with nulls. */
2599 while ((pkt < limit) && mask && *pkt)
2600 {
2601 pkt = unpack_int (pkt, &tag); /* tag */
2602 pkt = unpack_byte (pkt, &length); /* length */
2603 if (!(tag & mask)) /* Tags out of synch with mask. */
2604 {
2605 warning (_("ERROR RMT: threadinfo tag mismatch."));
2606 retval = 0;
2607 break;
2608 }
2609 if (tag == TAG_THREADID)
2610 {
2611 if (length != 16)
2612 {
2613 warning (_("ERROR RMT: length of threadid is not 16."));
2614 retval = 0;
2615 break;
2616 }
2617 pkt = unpack_threadid (pkt, &ref);
2618 mask = mask & ~TAG_THREADID;
2619 continue;
2620 }
2621 if (tag == TAG_EXISTS)
2622 {
2623 info->active = stub_unpack_int (pkt, length);
2624 pkt += length;
2625 mask = mask & ~(TAG_EXISTS);
2626 if (length > 8)
2627 {
2628 warning (_("ERROR RMT: 'exists' length too long."));
2629 retval = 0;
2630 break;
2631 }
2632 continue;
2633 }
2634 if (tag == TAG_THREADNAME)
2635 {
2636 pkt = unpack_string (pkt, &info->shortname[0], length);
2637 mask = mask & ~TAG_THREADNAME;
2638 continue;
2639 }
2640 if (tag == TAG_DISPLAY)
2641 {
2642 pkt = unpack_string (pkt, &info->display[0], length);
2643 mask = mask & ~TAG_DISPLAY;
2644 continue;
2645 }
2646 if (tag == TAG_MOREDISPLAY)
2647 {
2648 pkt = unpack_string (pkt, &info->more_display[0], length);
2649 mask = mask & ~TAG_MOREDISPLAY;
2650 continue;
2651 }
2652 warning (_("ERROR RMT: unknown thread info tag."));
2653 break; /* Not a tag we know about. */
2654 }
2655 return retval;
2656 }
2657
2658 static int
2659 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2660 struct gdb_ext_thread_info *info)
2661 {
2662 struct remote_state *rs = get_remote_state ();
2663 int result;
2664
2665 pack_threadinfo_request (rs->buf, fieldset, threadid);
2666 putpkt (rs->buf);
2667 getpkt (&rs->buf, &rs->buf_size, 0);
2668
2669 if (rs->buf[0] == '\0')
2670 return 0;
2671
2672 result = remote_unpack_thread_info_response (rs->buf + 2,
2673 threadid, info);
2674 return result;
2675 }
2676
2677 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2678
2679 static char *
2680 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2681 threadref *nextthread)
2682 {
2683 *pkt++ = 'q'; /* info query packet */
2684 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2685 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2686 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2687 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2688 *pkt = '\0';
2689 return pkt;
2690 }
2691
2692 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2693
2694 static int
2695 parse_threadlist_response (char *pkt, int result_limit,
2696 threadref *original_echo, threadref *resultlist,
2697 int *doneflag)
2698 {
2699 struct remote_state *rs = get_remote_state ();
2700 char *limit;
2701 int count, resultcount, done;
2702
2703 resultcount = 0;
2704 /* Assume the 'q' and 'M chars have been stripped. */
2705 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2706 /* done parse past here */
2707 pkt = unpack_byte (pkt, &count); /* count field */
2708 pkt = unpack_nibble (pkt, &done);
2709 /* The first threadid is the argument threadid. */
2710 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2711 while ((count-- > 0) && (pkt < limit))
2712 {
2713 pkt = unpack_threadid (pkt, resultlist++);
2714 if (resultcount++ >= result_limit)
2715 break;
2716 }
2717 if (doneflag)
2718 *doneflag = done;
2719 return resultcount;
2720 }
2721
2722 /* Fetch the next batch of threads from the remote. Returns -1 if the
2723 qL packet is not supported, 0 on error and 1 on success. */
2724
2725 static int
2726 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2727 int *done, int *result_count, threadref *threadlist)
2728 {
2729 struct remote_state *rs = get_remote_state ();
2730 int result = 1;
2731
2732 /* Trancate result limit to be smaller than the packet size. */
2733 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2734 >= get_remote_packet_size ())
2735 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2736
2737 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2738 putpkt (rs->buf);
2739 getpkt (&rs->buf, &rs->buf_size, 0);
2740 if (*rs->buf == '\0')
2741 {
2742 /* Packet not supported. */
2743 return -1;
2744 }
2745
2746 *result_count =
2747 parse_threadlist_response (rs->buf + 2, result_limit,
2748 &rs->echo_nextthread, threadlist, done);
2749
2750 if (!threadmatch (&rs->echo_nextthread, nextthread))
2751 {
2752 /* FIXME: This is a good reason to drop the packet. */
2753 /* Possably, there is a duplicate response. */
2754 /* Possabilities :
2755 retransmit immediatly - race conditions
2756 retransmit after timeout - yes
2757 exit
2758 wait for packet, then exit
2759 */
2760 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2761 return 0; /* I choose simply exiting. */
2762 }
2763 if (*result_count <= 0)
2764 {
2765 if (*done != 1)
2766 {
2767 warning (_("RMT ERROR : failed to get remote thread list."));
2768 result = 0;
2769 }
2770 return result; /* break; */
2771 }
2772 if (*result_count > result_limit)
2773 {
2774 *result_count = 0;
2775 warning (_("RMT ERROR: threadlist response longer than requested."));
2776 return 0;
2777 }
2778 return result;
2779 }
2780
2781 /* Fetch the list of remote threads, with the qL packet, and call
2782 STEPFUNCTION for each thread found. Stops iterating and returns 1
2783 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2784 STEPFUNCTION returns false. If the packet is not supported,
2785 returns -1. */
2786
2787 static int
2788 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2789 int looplimit)
2790 {
2791 struct remote_state *rs = get_remote_state ();
2792 int done, i, result_count;
2793 int startflag = 1;
2794 int result = 1;
2795 int loopcount = 0;
2796
2797 done = 0;
2798 while (!done)
2799 {
2800 if (loopcount++ > looplimit)
2801 {
2802 result = 0;
2803 warning (_("Remote fetch threadlist -infinite loop-."));
2804 break;
2805 }
2806 result = remote_get_threadlist (startflag, &rs->nextthread,
2807 MAXTHREADLISTRESULTS,
2808 &done, &result_count,
2809 rs->resultthreadlist);
2810 if (result <= 0)
2811 break;
2812 /* Clear for later iterations. */
2813 startflag = 0;
2814 /* Setup to resume next batch of thread references, set nextthread. */
2815 if (result_count >= 1)
2816 copy_threadref (&rs->nextthread,
2817 &rs->resultthreadlist[result_count - 1]);
2818 i = 0;
2819 while (result_count--)
2820 {
2821 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2822 {
2823 result = 0;
2824 break;
2825 }
2826 }
2827 }
2828 return result;
2829 }
2830
2831 /* A thread found on the remote target. */
2832
2833 typedef struct thread_item
2834 {
2835 /* The thread's PTID. */
2836 ptid_t ptid;
2837
2838 /* The thread's extra info. May be NULL. */
2839 char *extra;
2840
2841 /* The thread's name. May be NULL. */
2842 char *name;
2843
2844 /* The core the thread was running on. -1 if not known. */
2845 int core;
2846 } thread_item_t;
2847 DEF_VEC_O(thread_item_t);
2848
2849 /* Context passed around to the various methods listing remote
2850 threads. As new threads are found, they're added to the ITEMS
2851 vector. */
2852
2853 struct threads_listing_context
2854 {
2855 /* The threads found on the remote target. */
2856 VEC (thread_item_t) *items;
2857 };
2858
2859 /* Discard the contents of the constructed thread listing context. */
2860
2861 static void
2862 clear_threads_listing_context (void *p)
2863 {
2864 struct threads_listing_context *context
2865 = (struct threads_listing_context *) p;
2866 int i;
2867 struct thread_item *item;
2868
2869 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2870 {
2871 xfree (item->extra);
2872 xfree (item->name);
2873 }
2874
2875 VEC_free (thread_item_t, context->items);
2876 }
2877
2878 /* Remove the thread specified as the related_pid field of WS
2879 from the CONTEXT list. */
2880
2881 static void
2882 threads_listing_context_remove (struct target_waitstatus *ws,
2883 struct threads_listing_context *context)
2884 {
2885 struct thread_item *item;
2886 int i;
2887 ptid_t child_ptid = ws->value.related_pid;
2888
2889 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2890 {
2891 if (ptid_equal (item->ptid, child_ptid))
2892 {
2893 VEC_ordered_remove (thread_item_t, context->items, i);
2894 break;
2895 }
2896 }
2897 }
2898
2899 static int
2900 remote_newthread_step (threadref *ref, void *data)
2901 {
2902 struct threads_listing_context *context
2903 = (struct threads_listing_context *) data;
2904 struct thread_item item;
2905 int pid = ptid_get_pid (inferior_ptid);
2906
2907 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2908 item.core = -1;
2909 item.extra = NULL;
2910
2911 VEC_safe_push (thread_item_t, context->items, &item);
2912
2913 return 1; /* continue iterator */
2914 }
2915
2916 #define CRAZY_MAX_THREADS 1000
2917
2918 static ptid_t
2919 remote_current_thread (ptid_t oldpid)
2920 {
2921 struct remote_state *rs = get_remote_state ();
2922
2923 putpkt ("qC");
2924 getpkt (&rs->buf, &rs->buf_size, 0);
2925 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2926 {
2927 char *obuf;
2928 ptid_t result;
2929
2930 result = read_ptid (&rs->buf[2], &obuf);
2931 if (*obuf != '\0' && remote_debug)
2932 fprintf_unfiltered (gdb_stdlog,
2933 "warning: garbage in qC reply\n");
2934
2935 return result;
2936 }
2937 else
2938 return oldpid;
2939 }
2940
2941 /* List remote threads using the deprecated qL packet. */
2942
2943 static int
2944 remote_get_threads_with_ql (struct target_ops *ops,
2945 struct threads_listing_context *context)
2946 {
2947 if (remote_threadlist_iterator (remote_newthread_step, context,
2948 CRAZY_MAX_THREADS) >= 0)
2949 return 1;
2950
2951 return 0;
2952 }
2953
2954 #if defined(HAVE_LIBEXPAT)
2955
2956 static void
2957 start_thread (struct gdb_xml_parser *parser,
2958 const struct gdb_xml_element *element,
2959 void *user_data, VEC(gdb_xml_value_s) *attributes)
2960 {
2961 struct threads_listing_context *data
2962 = (struct threads_listing_context *) user_data;
2963
2964 struct thread_item item;
2965 char *id;
2966 struct gdb_xml_value *attr;
2967
2968 id = (char *) xml_find_attribute (attributes, "id")->value;
2969 item.ptid = read_ptid (id, NULL);
2970
2971 attr = xml_find_attribute (attributes, "core");
2972 if (attr != NULL)
2973 item.core = *(ULONGEST *) attr->value;
2974 else
2975 item.core = -1;
2976
2977 attr = xml_find_attribute (attributes, "name");
2978 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
2979
2980 item.extra = 0;
2981
2982 VEC_safe_push (thread_item_t, data->items, &item);
2983 }
2984
2985 static void
2986 end_thread (struct gdb_xml_parser *parser,
2987 const struct gdb_xml_element *element,
2988 void *user_data, const char *body_text)
2989 {
2990 struct threads_listing_context *data
2991 = (struct threads_listing_context *) user_data;
2992
2993 if (body_text && *body_text)
2994 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2995 }
2996
2997 const struct gdb_xml_attribute thread_attributes[] = {
2998 { "id", GDB_XML_AF_NONE, NULL, NULL },
2999 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3000 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3001 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3002 };
3003
3004 const struct gdb_xml_element thread_children[] = {
3005 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3006 };
3007
3008 const struct gdb_xml_element threads_children[] = {
3009 { "thread", thread_attributes, thread_children,
3010 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3011 start_thread, end_thread },
3012 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3013 };
3014
3015 const struct gdb_xml_element threads_elements[] = {
3016 { "threads", NULL, threads_children,
3017 GDB_XML_EF_NONE, NULL, NULL },
3018 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3019 };
3020
3021 #endif
3022
3023 /* List remote threads using qXfer:threads:read. */
3024
3025 static int
3026 remote_get_threads_with_qxfer (struct target_ops *ops,
3027 struct threads_listing_context *context)
3028 {
3029 #if defined(HAVE_LIBEXPAT)
3030 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3031 {
3032 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3033 struct cleanup *back_to = make_cleanup (xfree, xml);
3034
3035 if (xml != NULL && *xml != '\0')
3036 {
3037 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3038 threads_elements, xml, context);
3039 }
3040
3041 do_cleanups (back_to);
3042 return 1;
3043 }
3044 #endif
3045
3046 return 0;
3047 }
3048
3049 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3050
3051 static int
3052 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3053 struct threads_listing_context *context)
3054 {
3055 struct remote_state *rs = get_remote_state ();
3056
3057 if (rs->use_threadinfo_query)
3058 {
3059 char *bufp;
3060
3061 putpkt ("qfThreadInfo");
3062 getpkt (&rs->buf, &rs->buf_size, 0);
3063 bufp = rs->buf;
3064 if (bufp[0] != '\0') /* q packet recognized */
3065 {
3066 while (*bufp++ == 'm') /* reply contains one or more TID */
3067 {
3068 do
3069 {
3070 struct thread_item item;
3071
3072 item.ptid = read_ptid (bufp, &bufp);
3073 item.core = -1;
3074 item.extra = NULL;
3075
3076 VEC_safe_push (thread_item_t, context->items, &item);
3077 }
3078 while (*bufp++ == ','); /* comma-separated list */
3079 putpkt ("qsThreadInfo");
3080 getpkt (&rs->buf, &rs->buf_size, 0);
3081 bufp = rs->buf;
3082 }
3083 return 1;
3084 }
3085 else
3086 {
3087 /* Packet not recognized. */
3088 rs->use_threadinfo_query = 0;
3089 }
3090 }
3091
3092 return 0;
3093 }
3094
3095 /* Implement the to_update_thread_list function for the remote
3096 targets. */
3097
3098 static void
3099 remote_update_thread_list (struct target_ops *ops)
3100 {
3101 struct remote_state *rs = get_remote_state ();
3102 struct threads_listing_context context;
3103 struct cleanup *old_chain;
3104 int got_list = 0;
3105
3106 context.items = NULL;
3107 old_chain = make_cleanup (clear_threads_listing_context, &context);
3108
3109 /* We have a few different mechanisms to fetch the thread list. Try
3110 them all, starting with the most preferred one first, falling
3111 back to older methods. */
3112 if (remote_get_threads_with_qxfer (ops, &context)
3113 || remote_get_threads_with_qthreadinfo (ops, &context)
3114 || remote_get_threads_with_ql (ops, &context))
3115 {
3116 int i;
3117 struct thread_item *item;
3118 struct thread_info *tp, *tmp;
3119
3120 got_list = 1;
3121
3122 if (VEC_empty (thread_item_t, context.items)
3123 && remote_thread_always_alive (ops, inferior_ptid))
3124 {
3125 /* Some targets don't really support threads, but still
3126 reply an (empty) thread list in response to the thread
3127 listing packets, instead of replying "packet not
3128 supported". Exit early so we don't delete the main
3129 thread. */
3130 do_cleanups (old_chain);
3131 return;
3132 }
3133
3134 /* CONTEXT now holds the current thread list on the remote
3135 target end. Delete GDB-side threads no longer found on the
3136 target. */
3137 ALL_THREADS_SAFE (tp, tmp)
3138 {
3139 for (i = 0;
3140 VEC_iterate (thread_item_t, context.items, i, item);
3141 ++i)
3142 {
3143 if (ptid_equal (item->ptid, tp->ptid))
3144 break;
3145 }
3146
3147 if (i == VEC_length (thread_item_t, context.items))
3148 {
3149 /* Not found. */
3150 delete_thread (tp->ptid);
3151 }
3152 }
3153
3154 /* Remove any unreported fork child threads from CONTEXT so
3155 that we don't interfere with follow fork, which is where
3156 creation of such threads is handled. */
3157 remove_new_fork_children (&context);
3158
3159 /* And now add threads we don't know about yet to our list. */
3160 for (i = 0;
3161 VEC_iterate (thread_item_t, context.items, i, item);
3162 ++i)
3163 {
3164 if (!ptid_equal (item->ptid, null_ptid))
3165 {
3166 struct private_thread_info *info;
3167 /* In non-stop mode, we assume new found threads are
3168 running until proven otherwise with a stop reply. In
3169 all-stop, we can only get here if all threads are
3170 stopped. */
3171 int running = target_is_non_stop_p () ? 1 : 0;
3172
3173 remote_notice_new_inferior (item->ptid, running);
3174
3175 info = demand_private_info (item->ptid);
3176 info->core = item->core;
3177 info->extra = item->extra;
3178 item->extra = NULL;
3179 info->name = item->name;
3180 item->name = NULL;
3181 }
3182 }
3183 }
3184
3185 if (!got_list)
3186 {
3187 /* If no thread listing method is supported, then query whether
3188 each known thread is alive, one by one, with the T packet.
3189 If the target doesn't support threads at all, then this is a
3190 no-op. See remote_thread_alive. */
3191 prune_threads ();
3192 }
3193
3194 do_cleanups (old_chain);
3195 }
3196
3197 /*
3198 * Collect a descriptive string about the given thread.
3199 * The target may say anything it wants to about the thread
3200 * (typically info about its blocked / runnable state, name, etc.).
3201 * This string will appear in the info threads display.
3202 *
3203 * Optional: targets are not required to implement this function.
3204 */
3205
3206 static char *
3207 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3208 {
3209 struct remote_state *rs = get_remote_state ();
3210 int result;
3211 int set;
3212 threadref id;
3213 struct gdb_ext_thread_info threadinfo;
3214 static char display_buf[100]; /* arbitrary... */
3215 int n = 0; /* position in display_buf */
3216
3217 if (rs->remote_desc == 0) /* paranoia */
3218 internal_error (__FILE__, __LINE__,
3219 _("remote_threads_extra_info"));
3220
3221 if (ptid_equal (tp->ptid, magic_null_ptid)
3222 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3223 /* This is the main thread which was added by GDB. The remote
3224 server doesn't know about it. */
3225 return NULL;
3226
3227 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3228 {
3229 struct thread_info *info = find_thread_ptid (tp->ptid);
3230
3231 if (info && info->priv)
3232 return info->priv->extra;
3233 else
3234 return NULL;
3235 }
3236
3237 if (rs->use_threadextra_query)
3238 {
3239 char *b = rs->buf;
3240 char *endb = rs->buf + get_remote_packet_size ();
3241
3242 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3243 b += strlen (b);
3244 write_ptid (b, endb, tp->ptid);
3245
3246 putpkt (rs->buf);
3247 getpkt (&rs->buf, &rs->buf_size, 0);
3248 if (rs->buf[0] != 0)
3249 {
3250 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3251 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3252 display_buf [result] = '\0';
3253 return display_buf;
3254 }
3255 }
3256
3257 /* If the above query fails, fall back to the old method. */
3258 rs->use_threadextra_query = 0;
3259 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3260 | TAG_MOREDISPLAY | TAG_DISPLAY;
3261 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3262 if (remote_get_threadinfo (&id, set, &threadinfo))
3263 if (threadinfo.active)
3264 {
3265 if (*threadinfo.shortname)
3266 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3267 " Name: %s,", threadinfo.shortname);
3268 if (*threadinfo.display)
3269 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3270 " State: %s,", threadinfo.display);
3271 if (*threadinfo.more_display)
3272 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3273 " Priority: %s", threadinfo.more_display);
3274
3275 if (n > 0)
3276 {
3277 /* For purely cosmetic reasons, clear up trailing commas. */
3278 if (',' == display_buf[n-1])
3279 display_buf[n-1] = ' ';
3280 return display_buf;
3281 }
3282 }
3283 return NULL;
3284 }
3285 \f
3286
3287 static int
3288 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3289 struct static_tracepoint_marker *marker)
3290 {
3291 struct remote_state *rs = get_remote_state ();
3292 char *p = rs->buf;
3293
3294 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3295 p += strlen (p);
3296 p += hexnumstr (p, addr);
3297 putpkt (rs->buf);
3298 getpkt (&rs->buf, &rs->buf_size, 0);
3299 p = rs->buf;
3300
3301 if (*p == 'E')
3302 error (_("Remote failure reply: %s"), p);
3303
3304 if (*p++ == 'm')
3305 {
3306 parse_static_tracepoint_marker_definition (p, &p, marker);
3307 return 1;
3308 }
3309
3310 return 0;
3311 }
3312
3313 static VEC(static_tracepoint_marker_p) *
3314 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3315 const char *strid)
3316 {
3317 struct remote_state *rs = get_remote_state ();
3318 VEC(static_tracepoint_marker_p) *markers = NULL;
3319 struct static_tracepoint_marker *marker = NULL;
3320 struct cleanup *old_chain;
3321 char *p;
3322
3323 /* Ask for a first packet of static tracepoint marker
3324 definition. */
3325 putpkt ("qTfSTM");
3326 getpkt (&rs->buf, &rs->buf_size, 0);
3327 p = rs->buf;
3328 if (*p == 'E')
3329 error (_("Remote failure reply: %s"), p);
3330
3331 old_chain = make_cleanup (free_current_marker, &marker);
3332
3333 while (*p++ == 'm')
3334 {
3335 if (marker == NULL)
3336 marker = XCNEW (struct static_tracepoint_marker);
3337
3338 do
3339 {
3340 parse_static_tracepoint_marker_definition (p, &p, marker);
3341
3342 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3343 {
3344 VEC_safe_push (static_tracepoint_marker_p,
3345 markers, marker);
3346 marker = NULL;
3347 }
3348 else
3349 {
3350 release_static_tracepoint_marker (marker);
3351 memset (marker, 0, sizeof (*marker));
3352 }
3353 }
3354 while (*p++ == ','); /* comma-separated list */
3355 /* Ask for another packet of static tracepoint definition. */
3356 putpkt ("qTsSTM");
3357 getpkt (&rs->buf, &rs->buf_size, 0);
3358 p = rs->buf;
3359 }
3360
3361 do_cleanups (old_chain);
3362 return markers;
3363 }
3364
3365 \f
3366 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3367
3368 static ptid_t
3369 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3370 {
3371 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3372 }
3373 \f
3374
3375 /* Restart the remote side; this is an extended protocol operation. */
3376
3377 static void
3378 extended_remote_restart (void)
3379 {
3380 struct remote_state *rs = get_remote_state ();
3381
3382 /* Send the restart command; for reasons I don't understand the
3383 remote side really expects a number after the "R". */
3384 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3385 putpkt (rs->buf);
3386
3387 remote_fileio_reset ();
3388 }
3389 \f
3390 /* Clean up connection to a remote debugger. */
3391
3392 static void
3393 remote_close (struct target_ops *self)
3394 {
3395 struct remote_state *rs = get_remote_state ();
3396
3397 if (rs->remote_desc == NULL)
3398 return; /* already closed */
3399
3400 /* Make sure we leave stdin registered in the event loop, and we
3401 don't leave the async SIGINT signal handler installed. */
3402 remote_terminal_ours (self);
3403
3404 serial_close (rs->remote_desc);
3405 rs->remote_desc = NULL;
3406
3407 /* We don't have a connection to the remote stub anymore. Get rid
3408 of all the inferiors and their threads we were controlling.
3409 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3410 will be unable to find the thread corresponding to (pid, 0, 0). */
3411 inferior_ptid = null_ptid;
3412 discard_all_inferiors ();
3413
3414 /* We are closing the remote target, so we should discard
3415 everything of this target. */
3416 discard_pending_stop_replies_in_queue (rs);
3417
3418 if (remote_async_inferior_event_token)
3419 delete_async_event_handler (&remote_async_inferior_event_token);
3420
3421 remote_notif_state_xfree (rs->notif_state);
3422
3423 trace_reset_local_state ();
3424 }
3425
3426 /* Query the remote side for the text, data and bss offsets. */
3427
3428 static void
3429 get_offsets (void)
3430 {
3431 struct remote_state *rs = get_remote_state ();
3432 char *buf;
3433 char *ptr;
3434 int lose, num_segments = 0, do_sections, do_segments;
3435 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3436 struct section_offsets *offs;
3437 struct symfile_segment_data *data;
3438
3439 if (symfile_objfile == NULL)
3440 return;
3441
3442 putpkt ("qOffsets");
3443 getpkt (&rs->buf, &rs->buf_size, 0);
3444 buf = rs->buf;
3445
3446 if (buf[0] == '\000')
3447 return; /* Return silently. Stub doesn't support
3448 this command. */
3449 if (buf[0] == 'E')
3450 {
3451 warning (_("Remote failure reply: %s"), buf);
3452 return;
3453 }
3454
3455 /* Pick up each field in turn. This used to be done with scanf, but
3456 scanf will make trouble if CORE_ADDR size doesn't match
3457 conversion directives correctly. The following code will work
3458 with any size of CORE_ADDR. */
3459 text_addr = data_addr = bss_addr = 0;
3460 ptr = buf;
3461 lose = 0;
3462
3463 if (startswith (ptr, "Text="))
3464 {
3465 ptr += 5;
3466 /* Don't use strtol, could lose on big values. */
3467 while (*ptr && *ptr != ';')
3468 text_addr = (text_addr << 4) + fromhex (*ptr++);
3469
3470 if (startswith (ptr, ";Data="))
3471 {
3472 ptr += 6;
3473 while (*ptr && *ptr != ';')
3474 data_addr = (data_addr << 4) + fromhex (*ptr++);
3475 }
3476 else
3477 lose = 1;
3478
3479 if (!lose && startswith (ptr, ";Bss="))
3480 {
3481 ptr += 5;
3482 while (*ptr && *ptr != ';')
3483 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3484
3485 if (bss_addr != data_addr)
3486 warning (_("Target reported unsupported offsets: %s"), buf);
3487 }
3488 else
3489 lose = 1;
3490 }
3491 else if (startswith (ptr, "TextSeg="))
3492 {
3493 ptr += 8;
3494 /* Don't use strtol, could lose on big values. */
3495 while (*ptr && *ptr != ';')
3496 text_addr = (text_addr << 4) + fromhex (*ptr++);
3497 num_segments = 1;
3498
3499 if (startswith (ptr, ";DataSeg="))
3500 {
3501 ptr += 9;
3502 while (*ptr && *ptr != ';')
3503 data_addr = (data_addr << 4) + fromhex (*ptr++);
3504 num_segments++;
3505 }
3506 }
3507 else
3508 lose = 1;
3509
3510 if (lose)
3511 error (_("Malformed response to offset query, %s"), buf);
3512 else if (*ptr != '\0')
3513 warning (_("Target reported unsupported offsets: %s"), buf);
3514
3515 offs = ((struct section_offsets *)
3516 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3517 memcpy (offs, symfile_objfile->section_offsets,
3518 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3519
3520 data = get_symfile_segment_data (symfile_objfile->obfd);
3521 do_segments = (data != NULL);
3522 do_sections = num_segments == 0;
3523
3524 if (num_segments > 0)
3525 {
3526 segments[0] = text_addr;
3527 segments[1] = data_addr;
3528 }
3529 /* If we have two segments, we can still try to relocate everything
3530 by assuming that the .text and .data offsets apply to the whole
3531 text and data segments. Convert the offsets given in the packet
3532 to base addresses for symfile_map_offsets_to_segments. */
3533 else if (data && data->num_segments == 2)
3534 {
3535 segments[0] = data->segment_bases[0] + text_addr;
3536 segments[1] = data->segment_bases[1] + data_addr;
3537 num_segments = 2;
3538 }
3539 /* If the object file has only one segment, assume that it is text
3540 rather than data; main programs with no writable data are rare,
3541 but programs with no code are useless. Of course the code might
3542 have ended up in the data segment... to detect that we would need
3543 the permissions here. */
3544 else if (data && data->num_segments == 1)
3545 {
3546 segments[0] = data->segment_bases[0] + text_addr;
3547 num_segments = 1;
3548 }
3549 /* There's no way to relocate by segment. */
3550 else
3551 do_segments = 0;
3552
3553 if (do_segments)
3554 {
3555 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3556 offs, num_segments, segments);
3557
3558 if (ret == 0 && !do_sections)
3559 error (_("Can not handle qOffsets TextSeg "
3560 "response with this symbol file"));
3561
3562 if (ret > 0)
3563 do_sections = 0;
3564 }
3565
3566 if (data)
3567 free_symfile_segment_data (data);
3568
3569 if (do_sections)
3570 {
3571 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3572
3573 /* This is a temporary kludge to force data and bss to use the
3574 same offsets because that's what nlmconv does now. The real
3575 solution requires changes to the stub and remote.c that I
3576 don't have time to do right now. */
3577
3578 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3579 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3580 }
3581
3582 objfile_relocate (symfile_objfile, offs);
3583 }
3584
3585 /* Send interrupt_sequence to remote target. */
3586 static void
3587 send_interrupt_sequence (void)
3588 {
3589 struct remote_state *rs = get_remote_state ();
3590
3591 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3592 remote_serial_write ("\x03", 1);
3593 else if (interrupt_sequence_mode == interrupt_sequence_break)
3594 serial_send_break (rs->remote_desc);
3595 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3596 {
3597 serial_send_break (rs->remote_desc);
3598 remote_serial_write ("g", 1);
3599 }
3600 else
3601 internal_error (__FILE__, __LINE__,
3602 _("Invalid value for interrupt_sequence_mode: %s."),
3603 interrupt_sequence_mode);
3604 }
3605
3606
3607 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3608 and extract the PTID. Returns NULL_PTID if not found. */
3609
3610 static ptid_t
3611 stop_reply_extract_thread (char *stop_reply)
3612 {
3613 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3614 {
3615 char *p;
3616
3617 /* Txx r:val ; r:val (...) */
3618 p = &stop_reply[3];
3619
3620 /* Look for "register" named "thread". */
3621 while (*p != '\0')
3622 {
3623 char *p1;
3624
3625 p1 = strchr (p, ':');
3626 if (p1 == NULL)
3627 return null_ptid;
3628
3629 if (strncmp (p, "thread", p1 - p) == 0)
3630 return read_ptid (++p1, &p);
3631
3632 p1 = strchr (p, ';');
3633 if (p1 == NULL)
3634 return null_ptid;
3635 p1++;
3636
3637 p = p1;
3638 }
3639 }
3640
3641 return null_ptid;
3642 }
3643
3644 /* Determine the remote side's current thread. If we have a stop
3645 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3646 "thread" register we can extract the current thread from. If not,
3647 ask the remote which is the current thread with qC. The former
3648 method avoids a roundtrip. */
3649
3650 static ptid_t
3651 get_current_thread (char *wait_status)
3652 {
3653 ptid_t ptid = null_ptid;
3654
3655 /* Note we don't use remote_parse_stop_reply as that makes use of
3656 the target architecture, which we haven't yet fully determined at
3657 this point. */
3658 if (wait_status != NULL)
3659 ptid = stop_reply_extract_thread (wait_status);
3660 if (ptid_equal (ptid, null_ptid))
3661 ptid = remote_current_thread (inferior_ptid);
3662
3663 return ptid;
3664 }
3665
3666 /* Query the remote target for which is the current thread/process,
3667 add it to our tables, and update INFERIOR_PTID. The caller is
3668 responsible for setting the state such that the remote end is ready
3669 to return the current thread.
3670
3671 This function is called after handling the '?' or 'vRun' packets,
3672 whose response is a stop reply from which we can also try
3673 extracting the thread. If the target doesn't support the explicit
3674 qC query, we infer the current thread from that stop reply, passed
3675 in in WAIT_STATUS, which may be NULL. */
3676
3677 static void
3678 add_current_inferior_and_thread (char *wait_status)
3679 {
3680 struct remote_state *rs = get_remote_state ();
3681 int fake_pid_p = 0;
3682 ptid_t ptid;
3683
3684 inferior_ptid = null_ptid;
3685
3686 /* Now, if we have thread information, update inferior_ptid. */
3687 ptid = get_current_thread (wait_status);
3688
3689 if (!ptid_equal (ptid, null_ptid))
3690 {
3691 if (!remote_multi_process_p (rs))
3692 fake_pid_p = 1;
3693
3694 inferior_ptid = ptid;
3695 }
3696 else
3697 {
3698 /* Without this, some commands which require an active target
3699 (such as kill) won't work. This variable serves (at least)
3700 double duty as both the pid of the target process (if it has
3701 such), and as a flag indicating that a target is active. */
3702 inferior_ptid = magic_null_ptid;
3703 fake_pid_p = 1;
3704 }
3705
3706 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3707
3708 /* Add the main thread. */
3709 add_thread_silent (inferior_ptid);
3710 }
3711
3712 /* Print info about a thread that was found already stopped on
3713 connection. */
3714
3715 static void
3716 print_one_stopped_thread (struct thread_info *thread)
3717 {
3718 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3719
3720 switch_to_thread (thread->ptid);
3721 stop_pc = get_frame_pc (get_current_frame ());
3722 set_current_sal_from_frame (get_current_frame ());
3723
3724 thread->suspend.waitstatus_pending_p = 0;
3725
3726 if (ws->kind == TARGET_WAITKIND_STOPPED)
3727 {
3728 enum gdb_signal sig = ws->value.sig;
3729
3730 if (signal_print_state (sig))
3731 observer_notify_signal_received (sig);
3732 }
3733 observer_notify_normal_stop (NULL, 1);
3734 }
3735
3736 /* Process all initial stop replies the remote side sent in response
3737 to the ? packet. These indicate threads that were already stopped
3738 on initial connection. We mark these threads as stopped and print
3739 their current frame before giving the user the prompt. */
3740
3741 static void
3742 process_initial_stop_replies (int from_tty)
3743 {
3744 int pending_stop_replies = stop_reply_queue_length ();
3745 struct inferior *inf;
3746 struct thread_info *thread;
3747 struct thread_info *selected = NULL;
3748 struct thread_info *lowest_stopped = NULL;
3749 struct thread_info *first = NULL;
3750
3751 /* Consume the initial pending events. */
3752 while (pending_stop_replies-- > 0)
3753 {
3754 ptid_t waiton_ptid = minus_one_ptid;
3755 ptid_t event_ptid;
3756 struct target_waitstatus ws;
3757 int ignore_event = 0;
3758 struct thread_info *thread;
3759
3760 memset (&ws, 0, sizeof (ws));
3761 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3762 if (remote_debug)
3763 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3764
3765 switch (ws.kind)
3766 {
3767 case TARGET_WAITKIND_IGNORE:
3768 case TARGET_WAITKIND_NO_RESUMED:
3769 case TARGET_WAITKIND_SIGNALLED:
3770 case TARGET_WAITKIND_EXITED:
3771 /* We shouldn't see these, but if we do, just ignore. */
3772 if (remote_debug)
3773 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3774 ignore_event = 1;
3775 break;
3776
3777 case TARGET_WAITKIND_EXECD:
3778 xfree (ws.value.execd_pathname);
3779 break;
3780 default:
3781 break;
3782 }
3783
3784 if (ignore_event)
3785 continue;
3786
3787 thread = find_thread_ptid (event_ptid);
3788
3789 if (ws.kind == TARGET_WAITKIND_STOPPED)
3790 {
3791 enum gdb_signal sig = ws.value.sig;
3792
3793 /* Stubs traditionally report SIGTRAP as initial signal,
3794 instead of signal 0. Suppress it. */
3795 if (sig == GDB_SIGNAL_TRAP)
3796 sig = GDB_SIGNAL_0;
3797 thread->suspend.stop_signal = sig;
3798 ws.value.sig = sig;
3799 }
3800
3801 thread->suspend.waitstatus = ws;
3802
3803 if (ws.kind != TARGET_WAITKIND_STOPPED
3804 || ws.value.sig != GDB_SIGNAL_0)
3805 thread->suspend.waitstatus_pending_p = 1;
3806
3807 set_executing (event_ptid, 0);
3808 set_running (event_ptid, 0);
3809 }
3810
3811 /* "Notice" the new inferiors before anything related to
3812 registers/memory. */
3813 ALL_INFERIORS (inf)
3814 {
3815 if (inf->pid == 0)
3816 continue;
3817
3818 inf->needs_setup = 1;
3819
3820 if (non_stop)
3821 {
3822 thread = any_live_thread_of_process (inf->pid);
3823 notice_new_inferior (thread->ptid,
3824 thread->state == THREAD_RUNNING,
3825 from_tty);
3826 }
3827 }
3828
3829 /* If all-stop on top of non-stop, pause all threads. Note this
3830 records the threads' stop pc, so must be done after "noticing"
3831 the inferiors. */
3832 if (!non_stop)
3833 {
3834 stop_all_threads ();
3835
3836 /* If all threads of an inferior were already stopped, we
3837 haven't setup the inferior yet. */
3838 ALL_INFERIORS (inf)
3839 {
3840 if (inf->pid == 0)
3841 continue;
3842
3843 if (inf->needs_setup)
3844 {
3845 thread = any_live_thread_of_process (inf->pid);
3846 switch_to_thread_no_regs (thread);
3847 setup_inferior (0);
3848 }
3849 }
3850 }
3851
3852 /* Now go over all threads that are stopped, and print their current
3853 frame. If all-stop, then if there's a signalled thread, pick
3854 that as current. */
3855 ALL_NON_EXITED_THREADS (thread)
3856 {
3857 struct target_waitstatus *ws;
3858
3859 if (first == NULL)
3860 first = thread;
3861
3862 if (!non_stop)
3863 set_running (thread->ptid, 0);
3864 else if (thread->state != THREAD_STOPPED)
3865 continue;
3866
3867 ws = &thread->suspend.waitstatus;
3868
3869 if (selected == NULL
3870 && thread->suspend.waitstatus_pending_p)
3871 selected = thread;
3872
3873 if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3874 lowest_stopped = thread;
3875
3876 if (non_stop)
3877 print_one_stopped_thread (thread);
3878 }
3879
3880 /* In all-stop, we only print the status of one thread, and leave
3881 others with their status pending. */
3882 if (!non_stop)
3883 {
3884 thread = selected;
3885 if (thread == NULL)
3886 thread = lowest_stopped;
3887 if (thread == NULL)
3888 thread = first;
3889
3890 print_one_stopped_thread (thread);
3891 }
3892
3893 /* For "info program". */
3894 thread = inferior_thread ();
3895 if (thread->state == THREAD_STOPPED)
3896 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3897 }
3898
3899 static void
3900 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3901 {
3902 struct remote_state *rs = get_remote_state ();
3903 struct packet_config *noack_config;
3904 char *wait_status = NULL;
3905
3906 immediate_quit++; /* Allow user to interrupt it. */
3907 QUIT;
3908
3909 if (interrupt_on_connect)
3910 send_interrupt_sequence ();
3911
3912 /* Ack any packet which the remote side has already sent. */
3913 serial_write (rs->remote_desc, "+", 1);
3914
3915 /* Signal other parts that we're going through the initial setup,
3916 and so things may not be stable yet. */
3917 rs->starting_up = 1;
3918
3919 /* The first packet we send to the target is the optional "supported
3920 packets" request. If the target can answer this, it will tell us
3921 which later probes to skip. */
3922 remote_query_supported ();
3923
3924 /* If the stub wants to get a QAllow, compose one and send it. */
3925 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3926 remote_set_permissions (target);
3927
3928 /* Next, we possibly activate noack mode.
3929
3930 If the QStartNoAckMode packet configuration is set to AUTO,
3931 enable noack mode if the stub reported a wish for it with
3932 qSupported.
3933
3934 If set to TRUE, then enable noack mode even if the stub didn't
3935 report it in qSupported. If the stub doesn't reply OK, the
3936 session ends with an error.
3937
3938 If FALSE, then don't activate noack mode, regardless of what the
3939 stub claimed should be the default with qSupported. */
3940
3941 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3942 if (packet_config_support (noack_config) != PACKET_DISABLE)
3943 {
3944 putpkt ("QStartNoAckMode");
3945 getpkt (&rs->buf, &rs->buf_size, 0);
3946 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3947 rs->noack_mode = 1;
3948 }
3949
3950 if (extended_p)
3951 {
3952 /* Tell the remote that we are using the extended protocol. */
3953 putpkt ("!");
3954 getpkt (&rs->buf, &rs->buf_size, 0);
3955 }
3956
3957 /* Let the target know which signals it is allowed to pass down to
3958 the program. */
3959 update_signals_program_target ();
3960
3961 /* Next, if the target can specify a description, read it. We do
3962 this before anything involving memory or registers. */
3963 target_find_description ();
3964
3965 /* Next, now that we know something about the target, update the
3966 address spaces in the program spaces. */
3967 update_address_spaces ();
3968
3969 /* On OSs where the list of libraries is global to all
3970 processes, we fetch them early. */
3971 if (gdbarch_has_global_solist (target_gdbarch ()))
3972 solib_add (NULL, from_tty, target, auto_solib_add);
3973
3974 if (target_is_non_stop_p ())
3975 {
3976 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3977 error (_("Non-stop mode requested, but remote "
3978 "does not support non-stop"));
3979
3980 putpkt ("QNonStop:1");
3981 getpkt (&rs->buf, &rs->buf_size, 0);
3982
3983 if (strcmp (rs->buf, "OK") != 0)
3984 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3985
3986 /* Find about threads and processes the stub is already
3987 controlling. We default to adding them in the running state.
3988 The '?' query below will then tell us about which threads are
3989 stopped. */
3990 remote_update_thread_list (target);
3991 }
3992 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3993 {
3994 /* Don't assume that the stub can operate in all-stop mode.
3995 Request it explicitly. */
3996 putpkt ("QNonStop:0");
3997 getpkt (&rs->buf, &rs->buf_size, 0);
3998
3999 if (strcmp (rs->buf, "OK") != 0)
4000 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4001 }
4002
4003 /* Upload TSVs regardless of whether the target is running or not. The
4004 remote stub, such as GDBserver, may have some predefined or builtin
4005 TSVs, even if the target is not running. */
4006 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4007 {
4008 struct uploaded_tsv *uploaded_tsvs = NULL;
4009
4010 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4011 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4012 }
4013
4014 /* Check whether the target is running now. */
4015 putpkt ("?");
4016 getpkt (&rs->buf, &rs->buf_size, 0);
4017
4018 if (!target_is_non_stop_p ())
4019 {
4020 ptid_t ptid;
4021 int fake_pid_p = 0;
4022 struct inferior *inf;
4023
4024 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4025 {
4026 if (!extended_p)
4027 error (_("The target is not running (try extended-remote?)"));
4028
4029 /* We're connected, but not running. Drop out before we
4030 call start_remote. */
4031 rs->starting_up = 0;
4032 return;
4033 }
4034 else
4035 {
4036 /* Save the reply for later. */
4037 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4038 strcpy (wait_status, rs->buf);
4039 }
4040
4041 /* Fetch thread list. */
4042 target_update_thread_list ();
4043
4044 /* Let the stub know that we want it to return the thread. */
4045 set_continue_thread (minus_one_ptid);
4046
4047 if (thread_count () == 0)
4048 {
4049 /* Target has no concept of threads at all. GDB treats
4050 non-threaded target as single-threaded; add a main
4051 thread. */
4052 add_current_inferior_and_thread (wait_status);
4053 }
4054 else
4055 {
4056 /* We have thread information; select the thread the target
4057 says should be current. If we're reconnecting to a
4058 multi-threaded program, this will ideally be the thread
4059 that last reported an event before GDB disconnected. */
4060 inferior_ptid = get_current_thread (wait_status);
4061 if (ptid_equal (inferior_ptid, null_ptid))
4062 {
4063 /* Odd... The target was able to list threads, but not
4064 tell us which thread was current (no "thread"
4065 register in T stop reply?). Just pick the first
4066 thread in the thread list then. */
4067
4068 if (remote_debug)
4069 fprintf_unfiltered (gdb_stdlog,
4070 "warning: couldn't determine remote "
4071 "current thread; picking first in list.\n");
4072
4073 inferior_ptid = thread_list->ptid;
4074 }
4075 }
4076
4077 /* init_wait_for_inferior should be called before get_offsets in order
4078 to manage `inserted' flag in bp loc in a correct state.
4079 breakpoint_init_inferior, called from init_wait_for_inferior, set
4080 `inserted' flag to 0, while before breakpoint_re_set, called from
4081 start_remote, set `inserted' flag to 1. In the initialization of
4082 inferior, breakpoint_init_inferior should be called first, and then
4083 breakpoint_re_set can be called. If this order is broken, state of
4084 `inserted' flag is wrong, and cause some problems on breakpoint
4085 manipulation. */
4086 init_wait_for_inferior ();
4087
4088 get_offsets (); /* Get text, data & bss offsets. */
4089
4090 /* If we could not find a description using qXfer, and we know
4091 how to do it some other way, try again. This is not
4092 supported for non-stop; it could be, but it is tricky if
4093 there are no stopped threads when we connect. */
4094 if (remote_read_description_p (target)
4095 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4096 {
4097 target_clear_description ();
4098 target_find_description ();
4099 }
4100
4101 /* Use the previously fetched status. */
4102 gdb_assert (wait_status != NULL);
4103 strcpy (rs->buf, wait_status);
4104 rs->cached_wait_status = 1;
4105
4106 immediate_quit--;
4107 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4108 }
4109 else
4110 {
4111 /* Clear WFI global state. Do this before finding about new
4112 threads and inferiors, and setting the current inferior.
4113 Otherwise we would clear the proceed status of the current
4114 inferior when we want its stop_soon state to be preserved
4115 (see notice_new_inferior). */
4116 init_wait_for_inferior ();
4117
4118 /* In non-stop, we will either get an "OK", meaning that there
4119 are no stopped threads at this time; or, a regular stop
4120 reply. In the latter case, there may be more than one thread
4121 stopped --- we pull them all out using the vStopped
4122 mechanism. */
4123 if (strcmp (rs->buf, "OK") != 0)
4124 {
4125 struct notif_client *notif = &notif_client_stop;
4126
4127 /* remote_notif_get_pending_replies acks this one, and gets
4128 the rest out. */
4129 rs->notif_state->pending_event[notif_client_stop.id]
4130 = remote_notif_parse (notif, rs->buf);
4131 remote_notif_get_pending_events (notif);
4132 }
4133
4134 if (thread_count () == 0)
4135 {
4136 if (!extended_p)
4137 error (_("The target is not running (try extended-remote?)"));
4138
4139 /* We're connected, but not running. Drop out before we
4140 call start_remote. */
4141 rs->starting_up = 0;
4142 return;
4143 }
4144
4145 /* In non-stop mode, any cached wait status will be stored in
4146 the stop reply queue. */
4147 gdb_assert (wait_status == NULL);
4148
4149 /* Report all signals during attach/startup. */
4150 remote_pass_signals (target, 0, NULL);
4151
4152 /* If there are already stopped threads, mark them stopped and
4153 report their stops before giving the prompt to the user. */
4154 process_initial_stop_replies (from_tty);
4155
4156 if (target_can_async_p ())
4157 target_async (1);
4158 }
4159
4160 /* If we connected to a live target, do some additional setup. */
4161 if (target_has_execution)
4162 {
4163 if (symfile_objfile) /* No use without a symbol-file. */
4164 remote_check_symbols ();
4165 }
4166
4167 /* Possibly the target has been engaged in a trace run started
4168 previously; find out where things are at. */
4169 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4170 {
4171 struct uploaded_tp *uploaded_tps = NULL;
4172
4173 if (current_trace_status ()->running)
4174 printf_filtered (_("Trace is already running on the target.\n"));
4175
4176 remote_upload_tracepoints (target, &uploaded_tps);
4177
4178 merge_uploaded_tracepoints (&uploaded_tps);
4179 }
4180
4181 /* The thread and inferior lists are now synchronized with the
4182 target, our symbols have been relocated, and we're merged the
4183 target's tracepoints with ours. We're done with basic start
4184 up. */
4185 rs->starting_up = 0;
4186
4187 /* Maybe breakpoints are global and need to be inserted now. */
4188 if (breakpoints_should_be_inserted_now ())
4189 insert_breakpoints ();
4190 }
4191
4192 /* Open a connection to a remote debugger.
4193 NAME is the filename used for communication. */
4194
4195 static void
4196 remote_open (const char *name, int from_tty)
4197 {
4198 remote_open_1 (name, from_tty, &remote_ops, 0);
4199 }
4200
4201 /* Open a connection to a remote debugger using the extended
4202 remote gdb protocol. NAME is the filename used for communication. */
4203
4204 static void
4205 extended_remote_open (const char *name, int from_tty)
4206 {
4207 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4208 }
4209
4210 /* Reset all packets back to "unknown support". Called when opening a
4211 new connection to a remote target. */
4212
4213 static void
4214 reset_all_packet_configs_support (void)
4215 {
4216 int i;
4217
4218 for (i = 0; i < PACKET_MAX; i++)
4219 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4220 }
4221
4222 /* Initialize all packet configs. */
4223
4224 static void
4225 init_all_packet_configs (void)
4226 {
4227 int i;
4228
4229 for (i = 0; i < PACKET_MAX; i++)
4230 {
4231 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4232 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4233 }
4234 }
4235
4236 /* Symbol look-up. */
4237
4238 static void
4239 remote_check_symbols (void)
4240 {
4241 struct remote_state *rs = get_remote_state ();
4242 char *msg, *reply, *tmp;
4243 struct bound_minimal_symbol sym;
4244 int end;
4245 struct cleanup *old_chain;
4246
4247 /* The remote side has no concept of inferiors that aren't running
4248 yet, it only knows about running processes. If we're connected
4249 but our current inferior is not running, we should not invite the
4250 remote target to request symbol lookups related to its
4251 (unrelated) current process. */
4252 if (!target_has_execution)
4253 return;
4254
4255 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4256 return;
4257
4258 /* Make sure the remote is pointing at the right process. Note
4259 there's no way to select "no process". */
4260 set_general_process ();
4261
4262 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4263 because we need both at the same time. */
4264 msg = (char *) xmalloc (get_remote_packet_size ());
4265 old_chain = make_cleanup (xfree, msg);
4266
4267 /* Invite target to request symbol lookups. */
4268
4269 putpkt ("qSymbol::");
4270 getpkt (&rs->buf, &rs->buf_size, 0);
4271 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4272 reply = rs->buf;
4273
4274 while (startswith (reply, "qSymbol:"))
4275 {
4276 struct bound_minimal_symbol sym;
4277
4278 tmp = &reply[8];
4279 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4280 msg[end] = '\0';
4281 sym = lookup_minimal_symbol (msg, NULL, NULL);
4282 if (sym.minsym == NULL)
4283 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4284 else
4285 {
4286 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4287 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4288
4289 /* If this is a function address, return the start of code
4290 instead of any data function descriptor. */
4291 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4292 sym_addr,
4293 &current_target);
4294
4295 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4296 phex_nz (sym_addr, addr_size), &reply[8]);
4297 }
4298
4299 putpkt (msg);
4300 getpkt (&rs->buf, &rs->buf_size, 0);
4301 reply = rs->buf;
4302 }
4303
4304 do_cleanups (old_chain);
4305 }
4306
4307 static struct serial *
4308 remote_serial_open (const char *name)
4309 {
4310 static int udp_warning = 0;
4311
4312 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4313 of in ser-tcp.c, because it is the remote protocol assuming that the
4314 serial connection is reliable and not the serial connection promising
4315 to be. */
4316 if (!udp_warning && startswith (name, "udp:"))
4317 {
4318 warning (_("The remote protocol may be unreliable over UDP.\n"
4319 "Some events may be lost, rendering further debugging "
4320 "impossible."));
4321 udp_warning = 1;
4322 }
4323
4324 return serial_open (name);
4325 }
4326
4327 /* Inform the target of our permission settings. The permission flags
4328 work without this, but if the target knows the settings, it can do
4329 a couple things. First, it can add its own check, to catch cases
4330 that somehow manage to get by the permissions checks in target
4331 methods. Second, if the target is wired to disallow particular
4332 settings (for instance, a system in the field that is not set up to
4333 be able to stop at a breakpoint), it can object to any unavailable
4334 permissions. */
4335
4336 void
4337 remote_set_permissions (struct target_ops *self)
4338 {
4339 struct remote_state *rs = get_remote_state ();
4340
4341 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4342 "WriteReg:%x;WriteMem:%x;"
4343 "InsertBreak:%x;InsertTrace:%x;"
4344 "InsertFastTrace:%x;Stop:%x",
4345 may_write_registers, may_write_memory,
4346 may_insert_breakpoints, may_insert_tracepoints,
4347 may_insert_fast_tracepoints, may_stop);
4348 putpkt (rs->buf);
4349 getpkt (&rs->buf, &rs->buf_size, 0);
4350
4351 /* If the target didn't like the packet, warn the user. Do not try
4352 to undo the user's settings, that would just be maddening. */
4353 if (strcmp (rs->buf, "OK") != 0)
4354 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4355 }
4356
4357 /* This type describes each known response to the qSupported
4358 packet. */
4359 struct protocol_feature
4360 {
4361 /* The name of this protocol feature. */
4362 const char *name;
4363
4364 /* The default for this protocol feature. */
4365 enum packet_support default_support;
4366
4367 /* The function to call when this feature is reported, or after
4368 qSupported processing if the feature is not supported.
4369 The first argument points to this structure. The second
4370 argument indicates whether the packet requested support be
4371 enabled, disabled, or probed (or the default, if this function
4372 is being called at the end of processing and this feature was
4373 not reported). The third argument may be NULL; if not NULL, it
4374 is a NUL-terminated string taken from the packet following
4375 this feature's name and an equals sign. */
4376 void (*func) (const struct protocol_feature *, enum packet_support,
4377 const char *);
4378
4379 /* The corresponding packet for this feature. Only used if
4380 FUNC is remote_supported_packet. */
4381 int packet;
4382 };
4383
4384 static void
4385 remote_supported_packet (const struct protocol_feature *feature,
4386 enum packet_support support,
4387 const char *argument)
4388 {
4389 if (argument)
4390 {
4391 warning (_("Remote qSupported response supplied an unexpected value for"
4392 " \"%s\"."), feature->name);
4393 return;
4394 }
4395
4396 remote_protocol_packets[feature->packet].support = support;
4397 }
4398
4399 static void
4400 remote_packet_size (const struct protocol_feature *feature,
4401 enum packet_support support, const char *value)
4402 {
4403 struct remote_state *rs = get_remote_state ();
4404
4405 int packet_size;
4406 char *value_end;
4407
4408 if (support != PACKET_ENABLE)
4409 return;
4410
4411 if (value == NULL || *value == '\0')
4412 {
4413 warning (_("Remote target reported \"%s\" without a size."),
4414 feature->name);
4415 return;
4416 }
4417
4418 errno = 0;
4419 packet_size = strtol (value, &value_end, 16);
4420 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4421 {
4422 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4423 feature->name, value);
4424 return;
4425 }
4426
4427 /* Record the new maximum packet size. */
4428 rs->explicit_packet_size = packet_size;
4429 }
4430
4431 static const struct protocol_feature remote_protocol_features[] = {
4432 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4433 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4434 PACKET_qXfer_auxv },
4435 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4436 PACKET_qXfer_exec_file },
4437 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4438 PACKET_qXfer_features },
4439 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4440 PACKET_qXfer_libraries },
4441 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4442 PACKET_qXfer_libraries_svr4 },
4443 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4444 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4445 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4446 PACKET_qXfer_memory_map },
4447 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4448 PACKET_qXfer_spu_read },
4449 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4450 PACKET_qXfer_spu_write },
4451 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4452 PACKET_qXfer_osdata },
4453 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4454 PACKET_qXfer_threads },
4455 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4456 PACKET_qXfer_traceframe_info },
4457 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4458 PACKET_QPassSignals },
4459 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4460 PACKET_QProgramSignals },
4461 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4462 PACKET_QStartNoAckMode },
4463 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4464 PACKET_multiprocess_feature },
4465 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4466 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4467 PACKET_qXfer_siginfo_read },
4468 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4469 PACKET_qXfer_siginfo_write },
4470 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4471 PACKET_ConditionalTracepoints },
4472 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4473 PACKET_ConditionalBreakpoints },
4474 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4475 PACKET_BreakpointCommands },
4476 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4477 PACKET_FastTracepoints },
4478 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4479 PACKET_StaticTracepoints },
4480 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4481 PACKET_InstallInTrace},
4482 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4483 PACKET_DisconnectedTracing_feature },
4484 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4485 PACKET_bc },
4486 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4487 PACKET_bs },
4488 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4489 PACKET_TracepointSource },
4490 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4491 PACKET_QAllow },
4492 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4493 PACKET_EnableDisableTracepoints_feature },
4494 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4495 PACKET_qXfer_fdpic },
4496 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4497 PACKET_qXfer_uib },
4498 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4499 PACKET_QDisableRandomization },
4500 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4501 { "QTBuffer:size", PACKET_DISABLE,
4502 remote_supported_packet, PACKET_QTBuffer_size},
4503 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4504 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4505 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4506 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4507 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4508 PACKET_qXfer_btrace },
4509 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4510 PACKET_qXfer_btrace_conf },
4511 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4512 PACKET_Qbtrace_conf_bts_size },
4513 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4514 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4515 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4516 PACKET_fork_event_feature },
4517 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4518 PACKET_vfork_event_feature },
4519 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4520 PACKET_exec_event_feature },
4521 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4522 PACKET_Qbtrace_conf_pt_size },
4523 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported }
4524 };
4525
4526 static char *remote_support_xml;
4527
4528 /* Register string appended to "xmlRegisters=" in qSupported query. */
4529
4530 void
4531 register_remote_support_xml (const char *xml)
4532 {
4533 #if defined(HAVE_LIBEXPAT)
4534 if (remote_support_xml == NULL)
4535 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4536 else
4537 {
4538 char *copy = xstrdup (remote_support_xml + 13);
4539 char *p = strtok (copy, ",");
4540
4541 do
4542 {
4543 if (strcmp (p, xml) == 0)
4544 {
4545 /* already there */
4546 xfree (copy);
4547 return;
4548 }
4549 }
4550 while ((p = strtok (NULL, ",")) != NULL);
4551 xfree (copy);
4552
4553 remote_support_xml = reconcat (remote_support_xml,
4554 remote_support_xml, ",", xml,
4555 (char *) NULL);
4556 }
4557 #endif
4558 }
4559
4560 static char *
4561 remote_query_supported_append (char *msg, const char *append)
4562 {
4563 if (msg)
4564 return reconcat (msg, msg, ";", append, (char *) NULL);
4565 else
4566 return xstrdup (append);
4567 }
4568
4569 static void
4570 remote_query_supported (void)
4571 {
4572 struct remote_state *rs = get_remote_state ();
4573 char *next;
4574 int i;
4575 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4576
4577 /* The packet support flags are handled differently for this packet
4578 than for most others. We treat an error, a disabled packet, and
4579 an empty response identically: any features which must be reported
4580 to be used will be automatically disabled. An empty buffer
4581 accomplishes this, since that is also the representation for a list
4582 containing no features. */
4583
4584 rs->buf[0] = 0;
4585 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4586 {
4587 char *q = NULL;
4588 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4589
4590 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4591 q = remote_query_supported_append (q, "multiprocess+");
4592
4593 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4594 q = remote_query_supported_append (q, "swbreak+");
4595 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4596 q = remote_query_supported_append (q, "hwbreak+");
4597
4598 q = remote_query_supported_append (q, "qRelocInsn+");
4599
4600 if (rs->extended)
4601 {
4602 if (packet_set_cmd_state (PACKET_fork_event_feature)
4603 != AUTO_BOOLEAN_FALSE)
4604 q = remote_query_supported_append (q, "fork-events+");
4605 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4606 != AUTO_BOOLEAN_FALSE)
4607 q = remote_query_supported_append (q, "vfork-events+");
4608 if (packet_set_cmd_state (PACKET_exec_event_feature)
4609 != AUTO_BOOLEAN_FALSE)
4610 q = remote_query_supported_append (q, "exec-events+");
4611 }
4612
4613 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4614 q = remote_query_supported_append (q, "vContSupported+");
4615
4616 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4617 the qSupported:xmlRegisters=i386 handling. */
4618 if (remote_support_xml != NULL)
4619 q = remote_query_supported_append (q, remote_support_xml);
4620
4621 q = reconcat (q, "qSupported:", q, (char *) NULL);
4622 putpkt (q);
4623
4624 do_cleanups (old_chain);
4625
4626 getpkt (&rs->buf, &rs->buf_size, 0);
4627
4628 /* If an error occured, warn, but do not return - just reset the
4629 buffer to empty and go on to disable features. */
4630 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4631 == PACKET_ERROR)
4632 {
4633 warning (_("Remote failure reply: %s"), rs->buf);
4634 rs->buf[0] = 0;
4635 }
4636 }
4637
4638 memset (seen, 0, sizeof (seen));
4639
4640 next = rs->buf;
4641 while (*next)
4642 {
4643 enum packet_support is_supported;
4644 char *p, *end, *name_end, *value;
4645
4646 /* First separate out this item from the rest of the packet. If
4647 there's another item after this, we overwrite the separator
4648 (terminated strings are much easier to work with). */
4649 p = next;
4650 end = strchr (p, ';');
4651 if (end == NULL)
4652 {
4653 end = p + strlen (p);
4654 next = end;
4655 }
4656 else
4657 {
4658 *end = '\0';
4659 next = end + 1;
4660
4661 if (end == p)
4662 {
4663 warning (_("empty item in \"qSupported\" response"));
4664 continue;
4665 }
4666 }
4667
4668 name_end = strchr (p, '=');
4669 if (name_end)
4670 {
4671 /* This is a name=value entry. */
4672 is_supported = PACKET_ENABLE;
4673 value = name_end + 1;
4674 *name_end = '\0';
4675 }
4676 else
4677 {
4678 value = NULL;
4679 switch (end[-1])
4680 {
4681 case '+':
4682 is_supported = PACKET_ENABLE;
4683 break;
4684
4685 case '-':
4686 is_supported = PACKET_DISABLE;
4687 break;
4688
4689 case '?':
4690 is_supported = PACKET_SUPPORT_UNKNOWN;
4691 break;
4692
4693 default:
4694 warning (_("unrecognized item \"%s\" "
4695 "in \"qSupported\" response"), p);
4696 continue;
4697 }
4698 end[-1] = '\0';
4699 }
4700
4701 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4702 if (strcmp (remote_protocol_features[i].name, p) == 0)
4703 {
4704 const struct protocol_feature *feature;
4705
4706 seen[i] = 1;
4707 feature = &remote_protocol_features[i];
4708 feature->func (feature, is_supported, value);
4709 break;
4710 }
4711 }
4712
4713 /* If we increased the packet size, make sure to increase the global
4714 buffer size also. We delay this until after parsing the entire
4715 qSupported packet, because this is the same buffer we were
4716 parsing. */
4717 if (rs->buf_size < rs->explicit_packet_size)
4718 {
4719 rs->buf_size = rs->explicit_packet_size;
4720 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4721 }
4722
4723 /* Handle the defaults for unmentioned features. */
4724 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4725 if (!seen[i])
4726 {
4727 const struct protocol_feature *feature;
4728
4729 feature = &remote_protocol_features[i];
4730 feature->func (feature, feature->default_support, NULL);
4731 }
4732 }
4733
4734 /* Remove any of the remote.c targets from target stack. Upper targets depend
4735 on it so remove them first. */
4736
4737 static void
4738 remote_unpush_target (void)
4739 {
4740 pop_all_targets_at_and_above (process_stratum);
4741 }
4742
4743 static void
4744 remote_open_1 (const char *name, int from_tty,
4745 struct target_ops *target, int extended_p)
4746 {
4747 struct remote_state *rs = get_remote_state ();
4748
4749 if (name == 0)
4750 error (_("To open a remote debug connection, you need to specify what\n"
4751 "serial device is attached to the remote system\n"
4752 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4753
4754 /* See FIXME above. */
4755 if (!target_async_permitted)
4756 wait_forever_enabled_p = 1;
4757
4758 /* If we're connected to a running target, target_preopen will kill it.
4759 Ask this question first, before target_preopen has a chance to kill
4760 anything. */
4761 if (rs->remote_desc != NULL && !have_inferiors ())
4762 {
4763 if (from_tty
4764 && !query (_("Already connected to a remote target. Disconnect? ")))
4765 error (_("Still connected."));
4766 }
4767
4768 /* Here the possibly existing remote target gets unpushed. */
4769 target_preopen (from_tty);
4770
4771 /* Make sure we send the passed signals list the next time we resume. */
4772 xfree (rs->last_pass_packet);
4773 rs->last_pass_packet = NULL;
4774
4775 /* Make sure we send the program signals list the next time we
4776 resume. */
4777 xfree (rs->last_program_signals_packet);
4778 rs->last_program_signals_packet = NULL;
4779
4780 remote_fileio_reset ();
4781 reopen_exec_file ();
4782 reread_symbols ();
4783
4784 rs->remote_desc = remote_serial_open (name);
4785 if (!rs->remote_desc)
4786 perror_with_name (name);
4787
4788 if (baud_rate != -1)
4789 {
4790 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4791 {
4792 /* The requested speed could not be set. Error out to
4793 top level after closing remote_desc. Take care to
4794 set remote_desc to NULL to avoid closing remote_desc
4795 more than once. */
4796 serial_close (rs->remote_desc);
4797 rs->remote_desc = NULL;
4798 perror_with_name (name);
4799 }
4800 }
4801
4802 serial_setparity (rs->remote_desc, serial_parity);
4803 serial_raw (rs->remote_desc);
4804
4805 /* If there is something sitting in the buffer we might take it as a
4806 response to a command, which would be bad. */
4807 serial_flush_input (rs->remote_desc);
4808
4809 if (from_tty)
4810 {
4811 puts_filtered ("Remote debugging using ");
4812 puts_filtered (name);
4813 puts_filtered ("\n");
4814 }
4815 push_target (target); /* Switch to using remote target now. */
4816
4817 /* Register extra event sources in the event loop. */
4818 remote_async_inferior_event_token
4819 = create_async_event_handler (remote_async_inferior_event_handler,
4820 NULL);
4821 rs->notif_state = remote_notif_state_allocate ();
4822
4823 /* Reset the target state; these things will be queried either by
4824 remote_query_supported or as they are needed. */
4825 reset_all_packet_configs_support ();
4826 rs->cached_wait_status = 0;
4827 rs->explicit_packet_size = 0;
4828 rs->noack_mode = 0;
4829 rs->extended = extended_p;
4830 rs->waiting_for_stop_reply = 0;
4831 rs->ctrlc_pending_p = 0;
4832
4833 rs->general_thread = not_sent_ptid;
4834 rs->continue_thread = not_sent_ptid;
4835 rs->remote_traceframe_number = -1;
4836
4837 /* Probe for ability to use "ThreadInfo" query, as required. */
4838 rs->use_threadinfo_query = 1;
4839 rs->use_threadextra_query = 1;
4840
4841 readahead_cache_invalidate ();
4842
4843 if (target_async_permitted)
4844 {
4845 /* With this target we start out by owning the terminal. */
4846 remote_async_terminal_ours_p = 1;
4847
4848 /* FIXME: cagney/1999-09-23: During the initial connection it is
4849 assumed that the target is already ready and able to respond to
4850 requests. Unfortunately remote_start_remote() eventually calls
4851 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4852 around this. Eventually a mechanism that allows
4853 wait_for_inferior() to expect/get timeouts will be
4854 implemented. */
4855 wait_forever_enabled_p = 0;
4856 }
4857
4858 /* First delete any symbols previously loaded from shared libraries. */
4859 no_shared_libraries (NULL, 0);
4860
4861 /* Start afresh. */
4862 init_thread_list ();
4863
4864 /* Start the remote connection. If error() or QUIT, discard this
4865 target (we'd otherwise be in an inconsistent state) and then
4866 propogate the error on up the exception chain. This ensures that
4867 the caller doesn't stumble along blindly assuming that the
4868 function succeeded. The CLI doesn't have this problem but other
4869 UI's, such as MI do.
4870
4871 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4872 this function should return an error indication letting the
4873 caller restore the previous state. Unfortunately the command
4874 ``target remote'' is directly wired to this function making that
4875 impossible. On a positive note, the CLI side of this problem has
4876 been fixed - the function set_cmd_context() makes it possible for
4877 all the ``target ....'' commands to share a common callback
4878 function. See cli-dump.c. */
4879 {
4880
4881 TRY
4882 {
4883 remote_start_remote (from_tty, target, extended_p);
4884 }
4885 CATCH (ex, RETURN_MASK_ALL)
4886 {
4887 /* Pop the partially set up target - unless something else did
4888 already before throwing the exception. */
4889 if (rs->remote_desc != NULL)
4890 remote_unpush_target ();
4891 if (target_async_permitted)
4892 wait_forever_enabled_p = 1;
4893 throw_exception (ex);
4894 }
4895 END_CATCH
4896 }
4897
4898 remote_btrace_reset ();
4899
4900 if (target_async_permitted)
4901 wait_forever_enabled_p = 1;
4902 }
4903
4904 /* Detach the specified process. */
4905
4906 static void
4907 remote_detach_pid (int pid)
4908 {
4909 struct remote_state *rs = get_remote_state ();
4910
4911 if (remote_multi_process_p (rs))
4912 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4913 else
4914 strcpy (rs->buf, "D");
4915
4916 putpkt (rs->buf);
4917 getpkt (&rs->buf, &rs->buf_size, 0);
4918
4919 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4920 ;
4921 else if (rs->buf[0] == '\0')
4922 error (_("Remote doesn't know how to detach"));
4923 else
4924 error (_("Can't detach process."));
4925 }
4926
4927 /* This detaches a program to which we previously attached, using
4928 inferior_ptid to identify the process. After this is done, GDB
4929 can be used to debug some other program. We better not have left
4930 any breakpoints in the target program or it'll die when it hits
4931 one. */
4932
4933 static void
4934 remote_detach_1 (const char *args, int from_tty)
4935 {
4936 int pid = ptid_get_pid (inferior_ptid);
4937 struct remote_state *rs = get_remote_state ();
4938 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4939 int is_fork_parent;
4940
4941 if (args)
4942 error (_("Argument given to \"detach\" when remotely debugging."));
4943
4944 if (!target_has_execution)
4945 error (_("No process to detach from."));
4946
4947 if (from_tty)
4948 {
4949 char *exec_file = get_exec_file (0);
4950 if (exec_file == NULL)
4951 exec_file = "";
4952 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4953 target_pid_to_str (pid_to_ptid (pid)));
4954 gdb_flush (gdb_stdout);
4955 }
4956
4957 /* Tell the remote target to detach. */
4958 remote_detach_pid (pid);
4959
4960 if (from_tty && !rs->extended)
4961 puts_filtered (_("Ending remote debugging.\n"));
4962
4963 /* Check to see if we are detaching a fork parent. Note that if we
4964 are detaching a fork child, tp == NULL. */
4965 is_fork_parent = (tp != NULL
4966 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4967
4968 /* If doing detach-on-fork, we don't mourn, because that will delete
4969 breakpoints that should be available for the followed inferior. */
4970 if (!is_fork_parent)
4971 target_mourn_inferior ();
4972 else
4973 {
4974 inferior_ptid = null_ptid;
4975 detach_inferior (pid);
4976 }
4977 }
4978
4979 static void
4980 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4981 {
4982 remote_detach_1 (args, from_tty);
4983 }
4984
4985 static void
4986 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4987 {
4988 remote_detach_1 (args, from_tty);
4989 }
4990
4991 /* Target follow-fork function for remote targets. On entry, and
4992 at return, the current inferior is the fork parent.
4993
4994 Note that although this is currently only used for extended-remote,
4995 it is named remote_follow_fork in anticipation of using it for the
4996 remote target as well. */
4997
4998 static int
4999 remote_follow_fork (struct target_ops *ops, int follow_child,
5000 int detach_fork)
5001 {
5002 struct remote_state *rs = get_remote_state ();
5003 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5004
5005 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5006 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5007 {
5008 /* When following the parent and detaching the child, we detach
5009 the child here. For the case of following the child and
5010 detaching the parent, the detach is done in the target-
5011 independent follow fork code in infrun.c. We can't use
5012 target_detach when detaching an unfollowed child because
5013 the client side doesn't know anything about the child. */
5014 if (detach_fork && !follow_child)
5015 {
5016 /* Detach the fork child. */
5017 ptid_t child_ptid;
5018 pid_t child_pid;
5019
5020 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5021 child_pid = ptid_get_pid (child_ptid);
5022
5023 remote_detach_pid (child_pid);
5024 detach_inferior (child_pid);
5025 }
5026 }
5027 return 0;
5028 }
5029
5030 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5031 in the program space of the new inferior. On entry and at return the
5032 current inferior is the exec'ing inferior. INF is the new exec'd
5033 inferior, which may be the same as the exec'ing inferior unless
5034 follow-exec-mode is "new". */
5035
5036 static void
5037 remote_follow_exec (struct target_ops *ops,
5038 struct inferior *inf, char *execd_pathname)
5039 {
5040 /* We know that this is a target file name, so if it has the "target:"
5041 prefix we strip it off before saving it in the program space. */
5042 if (is_target_filename (execd_pathname))
5043 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5044
5045 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5046 }
5047
5048 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5049
5050 static void
5051 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5052 {
5053 if (args)
5054 error (_("Argument given to \"disconnect\" when remotely debugging."));
5055
5056 /* Make sure we unpush even the extended remote targets; mourn
5057 won't do it. So call remote_mourn directly instead of
5058 target_mourn_inferior. */
5059 remote_mourn (target);
5060
5061 if (from_tty)
5062 puts_filtered ("Ending remote debugging.\n");
5063 }
5064
5065 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5066 be chatty about it. */
5067
5068 static void
5069 extended_remote_attach (struct target_ops *target, const char *args,
5070 int from_tty)
5071 {
5072 struct remote_state *rs = get_remote_state ();
5073 int pid;
5074 char *wait_status = NULL;
5075
5076 pid = parse_pid_to_attach (args);
5077
5078 /* Remote PID can be freely equal to getpid, do not check it here the same
5079 way as in other targets. */
5080
5081 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5082 error (_("This target does not support attaching to a process"));
5083
5084 if (from_tty)
5085 {
5086 char *exec_file = get_exec_file (0);
5087
5088 if (exec_file)
5089 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5090 target_pid_to_str (pid_to_ptid (pid)));
5091 else
5092 printf_unfiltered (_("Attaching to %s\n"),
5093 target_pid_to_str (pid_to_ptid (pid)));
5094
5095 gdb_flush (gdb_stdout);
5096 }
5097
5098 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5099 putpkt (rs->buf);
5100 getpkt (&rs->buf, &rs->buf_size, 0);
5101
5102 switch (packet_ok (rs->buf,
5103 &remote_protocol_packets[PACKET_vAttach]))
5104 {
5105 case PACKET_OK:
5106 if (!target_is_non_stop_p ())
5107 {
5108 /* Save the reply for later. */
5109 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5110 strcpy (wait_status, rs->buf);
5111 }
5112 else if (strcmp (rs->buf, "OK") != 0)
5113 error (_("Attaching to %s failed with: %s"),
5114 target_pid_to_str (pid_to_ptid (pid)),
5115 rs->buf);
5116 break;
5117 case PACKET_UNKNOWN:
5118 error (_("This target does not support attaching to a process"));
5119 default:
5120 error (_("Attaching to %s failed"),
5121 target_pid_to_str (pid_to_ptid (pid)));
5122 }
5123
5124 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5125
5126 inferior_ptid = pid_to_ptid (pid);
5127
5128 if (target_is_non_stop_p ())
5129 {
5130 struct thread_info *thread;
5131
5132 /* Get list of threads. */
5133 remote_update_thread_list (target);
5134
5135 thread = first_thread_of_process (pid);
5136 if (thread)
5137 inferior_ptid = thread->ptid;
5138 else
5139 inferior_ptid = pid_to_ptid (pid);
5140
5141 /* Invalidate our notion of the remote current thread. */
5142 record_currthread (rs, minus_one_ptid);
5143 }
5144 else
5145 {
5146 /* Now, if we have thread information, update inferior_ptid. */
5147 inferior_ptid = remote_current_thread (inferior_ptid);
5148
5149 /* Add the main thread to the thread list. */
5150 add_thread_silent (inferior_ptid);
5151 }
5152
5153 /* Next, if the target can specify a description, read it. We do
5154 this before anything involving memory or registers. */
5155 target_find_description ();
5156
5157 if (!target_is_non_stop_p ())
5158 {
5159 /* Use the previously fetched status. */
5160 gdb_assert (wait_status != NULL);
5161
5162 if (target_can_async_p ())
5163 {
5164 struct notif_event *reply
5165 = remote_notif_parse (&notif_client_stop, wait_status);
5166
5167 push_stop_reply ((struct stop_reply *) reply);
5168
5169 target_async (1);
5170 }
5171 else
5172 {
5173 gdb_assert (wait_status != NULL);
5174 strcpy (rs->buf, wait_status);
5175 rs->cached_wait_status = 1;
5176 }
5177 }
5178 else
5179 gdb_assert (wait_status == NULL);
5180 }
5181
5182 /* Implementation of the to_post_attach method. */
5183
5184 static void
5185 extended_remote_post_attach (struct target_ops *ops, int pid)
5186 {
5187 /* Get text, data & bss offsets. */
5188 get_offsets ();
5189
5190 /* In certain cases GDB might not have had the chance to start
5191 symbol lookup up until now. This could happen if the debugged
5192 binary is not using shared libraries, the vsyscall page is not
5193 present (on Linux) and the binary itself hadn't changed since the
5194 debugging process was started. */
5195 if (symfile_objfile != NULL)
5196 remote_check_symbols();
5197 }
5198
5199 \f
5200 /* Check for the availability of vCont. This function should also check
5201 the response. */
5202
5203 static void
5204 remote_vcont_probe (struct remote_state *rs)
5205 {
5206 char *buf;
5207
5208 strcpy (rs->buf, "vCont?");
5209 putpkt (rs->buf);
5210 getpkt (&rs->buf, &rs->buf_size, 0);
5211 buf = rs->buf;
5212
5213 /* Make sure that the features we assume are supported. */
5214 if (startswith (buf, "vCont"))
5215 {
5216 char *p = &buf[5];
5217 int support_c, support_C;
5218
5219 rs->supports_vCont.s = 0;
5220 rs->supports_vCont.S = 0;
5221 support_c = 0;
5222 support_C = 0;
5223 rs->supports_vCont.t = 0;
5224 rs->supports_vCont.r = 0;
5225 while (p && *p == ';')
5226 {
5227 p++;
5228 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5229 rs->supports_vCont.s = 1;
5230 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5231 rs->supports_vCont.S = 1;
5232 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5233 support_c = 1;
5234 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5235 support_C = 1;
5236 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5237 rs->supports_vCont.t = 1;
5238 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5239 rs->supports_vCont.r = 1;
5240
5241 p = strchr (p, ';');
5242 }
5243
5244 /* If c, and C are not all supported, we can't use vCont. Clearing
5245 BUF will make packet_ok disable the packet. */
5246 if (!support_c || !support_C)
5247 buf[0] = 0;
5248 }
5249
5250 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5251 }
5252
5253 /* Helper function for building "vCont" resumptions. Write a
5254 resumption to P. ENDP points to one-passed-the-end of the buffer
5255 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5256 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5257 resumed thread should be single-stepped and/or signalled. If PTID
5258 equals minus_one_ptid, then all threads are resumed; if PTID
5259 represents a process, then all threads of the process are resumed;
5260 the thread to be stepped and/or signalled is given in the global
5261 INFERIOR_PTID. */
5262
5263 static char *
5264 append_resumption (char *p, char *endp,
5265 ptid_t ptid, int step, enum gdb_signal siggnal)
5266 {
5267 struct remote_state *rs = get_remote_state ();
5268
5269 if (step && siggnal != GDB_SIGNAL_0)
5270 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5271 else if (step
5272 /* GDB is willing to range step. */
5273 && use_range_stepping
5274 /* Target supports range stepping. */
5275 && rs->supports_vCont.r
5276 /* We don't currently support range stepping multiple
5277 threads with a wildcard (though the protocol allows it,
5278 so stubs shouldn't make an active effort to forbid
5279 it). */
5280 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5281 {
5282 struct thread_info *tp;
5283
5284 if (ptid_equal (ptid, minus_one_ptid))
5285 {
5286 /* If we don't know about the target thread's tid, then
5287 we're resuming magic_null_ptid (see caller). */
5288 tp = find_thread_ptid (magic_null_ptid);
5289 }
5290 else
5291 tp = find_thread_ptid (ptid);
5292 gdb_assert (tp != NULL);
5293
5294 if (tp->control.may_range_step)
5295 {
5296 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5297
5298 p += xsnprintf (p, endp - p, ";r%s,%s",
5299 phex_nz (tp->control.step_range_start,
5300 addr_size),
5301 phex_nz (tp->control.step_range_end,
5302 addr_size));
5303 }
5304 else
5305 p += xsnprintf (p, endp - p, ";s");
5306 }
5307 else if (step)
5308 p += xsnprintf (p, endp - p, ";s");
5309 else if (siggnal != GDB_SIGNAL_0)
5310 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5311 else
5312 p += xsnprintf (p, endp - p, ";c");
5313
5314 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5315 {
5316 ptid_t nptid;
5317
5318 /* All (-1) threads of process. */
5319 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5320
5321 p += xsnprintf (p, endp - p, ":");
5322 p = write_ptid (p, endp, nptid);
5323 }
5324 else if (!ptid_equal (ptid, minus_one_ptid))
5325 {
5326 p += xsnprintf (p, endp - p, ":");
5327 p = write_ptid (p, endp, ptid);
5328 }
5329
5330 return p;
5331 }
5332
5333 /* Clear the thread's private info on resume. */
5334
5335 static void
5336 resume_clear_thread_private_info (struct thread_info *thread)
5337 {
5338 if (thread->priv != NULL)
5339 {
5340 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5341 thread->priv->watch_data_address = 0;
5342 }
5343 }
5344
5345 /* Append a vCont continue-with-signal action for threads that have a
5346 non-zero stop signal. */
5347
5348 static char *
5349 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5350 {
5351 struct thread_info *thread;
5352
5353 ALL_NON_EXITED_THREADS (thread)
5354 if (ptid_match (thread->ptid, ptid)
5355 && !ptid_equal (inferior_ptid, thread->ptid)
5356 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5357 {
5358 p = append_resumption (p, endp, thread->ptid,
5359 0, thread->suspend.stop_signal);
5360 thread->suspend.stop_signal = GDB_SIGNAL_0;
5361 resume_clear_thread_private_info (thread);
5362 }
5363
5364 return p;
5365 }
5366
5367 /* Resume the remote inferior by using a "vCont" packet. The thread
5368 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5369 resumed thread should be single-stepped and/or signalled. If PTID
5370 equals minus_one_ptid, then all threads are resumed; the thread to
5371 be stepped and/or signalled is given in the global INFERIOR_PTID.
5372 This function returns non-zero iff it resumes the inferior.
5373
5374 This function issues a strict subset of all possible vCont commands at the
5375 moment. */
5376
5377 static int
5378 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5379 {
5380 struct remote_state *rs = get_remote_state ();
5381 char *p;
5382 char *endp;
5383
5384 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5385 remote_vcont_probe (rs);
5386
5387 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5388 return 0;
5389
5390 p = rs->buf;
5391 endp = rs->buf + get_remote_packet_size ();
5392
5393 /* If we could generate a wider range of packets, we'd have to worry
5394 about overflowing BUF. Should there be a generic
5395 "multi-part-packet" packet? */
5396
5397 p += xsnprintf (p, endp - p, "vCont");
5398
5399 if (ptid_equal (ptid, magic_null_ptid))
5400 {
5401 /* MAGIC_NULL_PTID means that we don't have any active threads,
5402 so we don't have any TID numbers the inferior will
5403 understand. Make sure to only send forms that do not specify
5404 a TID. */
5405 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5406 }
5407 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5408 {
5409 /* Resume all threads (of all processes, or of a single
5410 process), with preference for INFERIOR_PTID. This assumes
5411 inferior_ptid belongs to the set of all threads we are about
5412 to resume. */
5413 if (step || siggnal != GDB_SIGNAL_0)
5414 {
5415 /* Step inferior_ptid, with or without signal. */
5416 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5417 }
5418
5419 /* Also pass down any pending signaled resumption for other
5420 threads not the current. */
5421 p = append_pending_thread_resumptions (p, endp, ptid);
5422
5423 /* And continue others without a signal. */
5424 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5425 }
5426 else
5427 {
5428 /* Scheduler locking; resume only PTID. */
5429 append_resumption (p, endp, ptid, step, siggnal);
5430 }
5431
5432 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5433 putpkt (rs->buf);
5434
5435 if (target_is_non_stop_p ())
5436 {
5437 /* In non-stop, the stub replies to vCont with "OK". The stop
5438 reply will be reported asynchronously by means of a `%Stop'
5439 notification. */
5440 getpkt (&rs->buf, &rs->buf_size, 0);
5441 if (strcmp (rs->buf, "OK") != 0)
5442 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5443 }
5444
5445 return 1;
5446 }
5447
5448 /* Tell the remote machine to resume. */
5449
5450 static void
5451 remote_resume (struct target_ops *ops,
5452 ptid_t ptid, int step, enum gdb_signal siggnal)
5453 {
5454 struct remote_state *rs = get_remote_state ();
5455 char *buf;
5456 struct thread_info *thread;
5457
5458 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5459 (explained in remote-notif.c:handle_notification) so
5460 remote_notif_process is not called. We need find a place where
5461 it is safe to start a 'vNotif' sequence. It is good to do it
5462 before resuming inferior, because inferior was stopped and no RSP
5463 traffic at that moment. */
5464 if (!target_is_non_stop_p ())
5465 remote_notif_process (rs->notif_state, &notif_client_stop);
5466
5467 rs->last_sent_signal = siggnal;
5468 rs->last_sent_step = step;
5469
5470 /* The vCont packet doesn't need to specify threads via Hc. */
5471 /* No reverse support (yet) for vCont. */
5472 if (execution_direction != EXEC_REVERSE)
5473 if (remote_vcont_resume (ptid, step, siggnal))
5474 goto done;
5475
5476 /* All other supported resume packets do use Hc, so set the continue
5477 thread. */
5478 if (ptid_equal (ptid, minus_one_ptid))
5479 set_continue_thread (any_thread_ptid);
5480 else
5481 set_continue_thread (ptid);
5482
5483 ALL_NON_EXITED_THREADS (thread)
5484 resume_clear_thread_private_info (thread);
5485
5486 buf = rs->buf;
5487 if (execution_direction == EXEC_REVERSE)
5488 {
5489 /* We don't pass signals to the target in reverse exec mode. */
5490 if (info_verbose && siggnal != GDB_SIGNAL_0)
5491 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5492 siggnal);
5493
5494 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5495 error (_("Remote reverse-step not supported."));
5496 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5497 error (_("Remote reverse-continue not supported."));
5498
5499 strcpy (buf, step ? "bs" : "bc");
5500 }
5501 else if (siggnal != GDB_SIGNAL_0)
5502 {
5503 buf[0] = step ? 'S' : 'C';
5504 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5505 buf[2] = tohex (((int) siggnal) & 0xf);
5506 buf[3] = '\0';
5507 }
5508 else
5509 strcpy (buf, step ? "s" : "c");
5510
5511 putpkt (buf);
5512
5513 done:
5514 /* We are about to start executing the inferior, let's register it
5515 with the event loop. NOTE: this is the one place where all the
5516 execution commands end up. We could alternatively do this in each
5517 of the execution commands in infcmd.c. */
5518 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5519 into infcmd.c in order to allow inferior function calls to work
5520 NOT asynchronously. */
5521 if (target_can_async_p ())
5522 target_async (1);
5523
5524 /* We've just told the target to resume. The remote server will
5525 wait for the inferior to stop, and then send a stop reply. In
5526 the mean time, we can't start another command/query ourselves
5527 because the stub wouldn't be ready to process it. This applies
5528 only to the base all-stop protocol, however. In non-stop (which
5529 only supports vCont), the stub replies with an "OK", and is
5530 immediate able to process further serial input. */
5531 if (!target_is_non_stop_p ())
5532 rs->waiting_for_stop_reply = 1;
5533 }
5534 \f
5535
5536 /* Set up the signal handler for SIGINT, while the target is
5537 executing, ovewriting the 'regular' SIGINT signal handler. */
5538 static void
5539 async_initialize_sigint_signal_handler (void)
5540 {
5541 signal (SIGINT, async_handle_remote_sigint);
5542 }
5543
5544 /* Signal handler for SIGINT, while the target is executing. */
5545 static void
5546 async_handle_remote_sigint (int sig)
5547 {
5548 signal (sig, async_handle_remote_sigint_twice);
5549 /* Note we need to go through gdb_call_async_signal_handler in order
5550 to wake up the event loop on Windows. */
5551 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5552 }
5553
5554 /* Signal handler for SIGINT, installed after SIGINT has already been
5555 sent once. It will take effect the second time that the user sends
5556 a ^C. */
5557 static void
5558 async_handle_remote_sigint_twice (int sig)
5559 {
5560 signal (sig, async_handle_remote_sigint);
5561 /* See note in async_handle_remote_sigint. */
5562 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5563 }
5564
5565 /* Implementation of to_check_pending_interrupt. */
5566
5567 static void
5568 remote_check_pending_interrupt (struct target_ops *self)
5569 {
5570 struct async_signal_handler *token = async_sigint_remote_twice_token;
5571
5572 if (async_signal_handler_is_marked (token))
5573 {
5574 clear_async_signal_handler (token);
5575 call_async_signal_handler (token);
5576 }
5577 }
5578
5579 /* Perform the real interruption of the target execution, in response
5580 to a ^C. */
5581 static void
5582 async_remote_interrupt (gdb_client_data arg)
5583 {
5584 if (remote_debug)
5585 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5586
5587 target_interrupt (inferior_ptid);
5588 }
5589
5590 /* Perform interrupt, if the first attempt did not succeed. Just give
5591 up on the target alltogether. */
5592 static void
5593 async_remote_interrupt_twice (gdb_client_data arg)
5594 {
5595 if (remote_debug)
5596 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5597
5598 interrupt_query ();
5599 }
5600
5601 /* Reinstall the usual SIGINT handlers, after the target has
5602 stopped. */
5603 static void
5604 async_cleanup_sigint_signal_handler (void *dummy)
5605 {
5606 signal (SIGINT, handle_sigint);
5607 }
5608
5609 /* Send ^C to target to halt it. Target will respond, and send us a
5610 packet. */
5611 static void (*ofunc) (int);
5612
5613 /* The command line interface's interrupt routine. This function is installed
5614 as a signal handler for SIGINT. The first time a user requests an
5615 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5616 response from the target (it didn't stop when the user requested it),
5617 we ask the user if he'd like to detach from the target. */
5618
5619 static void
5620 sync_remote_interrupt (int signo)
5621 {
5622 /* If this doesn't work, try more severe steps. */
5623 signal (signo, sync_remote_interrupt_twice);
5624
5625 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5626 }
5627
5628 /* The user typed ^C twice. */
5629
5630 static void
5631 sync_remote_interrupt_twice (int signo)
5632 {
5633 signal (signo, ofunc);
5634 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5635 signal (signo, sync_remote_interrupt);
5636 }
5637
5638 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5639 thread, all threads of a remote process, or all threads of all
5640 processes. */
5641
5642 static void
5643 remote_stop_ns (ptid_t ptid)
5644 {
5645 struct remote_state *rs = get_remote_state ();
5646 char *p = rs->buf;
5647 char *endp = rs->buf + get_remote_packet_size ();
5648
5649 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5650 remote_vcont_probe (rs);
5651
5652 if (!rs->supports_vCont.t)
5653 error (_("Remote server does not support stopping threads"));
5654
5655 if (ptid_equal (ptid, minus_one_ptid)
5656 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5657 p += xsnprintf (p, endp - p, "vCont;t");
5658 else
5659 {
5660 ptid_t nptid;
5661
5662 p += xsnprintf (p, endp - p, "vCont;t:");
5663
5664 if (ptid_is_pid (ptid))
5665 /* All (-1) threads of process. */
5666 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5667 else
5668 {
5669 /* Small optimization: if we already have a stop reply for
5670 this thread, no use in telling the stub we want this
5671 stopped. */
5672 if (peek_stop_reply (ptid))
5673 return;
5674
5675 nptid = ptid;
5676 }
5677
5678 write_ptid (p, endp, nptid);
5679 }
5680
5681 /* In non-stop, we get an immediate OK reply. The stop reply will
5682 come in asynchronously by notification. */
5683 putpkt (rs->buf);
5684 getpkt (&rs->buf, &rs->buf_size, 0);
5685 if (strcmp (rs->buf, "OK") != 0)
5686 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5687 }
5688
5689 /* All-stop version of target_interrupt. Sends a break or a ^C to
5690 interrupt the remote target. It is undefined which thread of which
5691 process reports the interrupt. */
5692
5693 static void
5694 remote_interrupt_as (void)
5695 {
5696 struct remote_state *rs = get_remote_state ();
5697
5698 rs->ctrlc_pending_p = 1;
5699
5700 /* If the inferior is stopped already, but the core didn't know
5701 about it yet, just ignore the request. The cached wait status
5702 will be collected in remote_wait. */
5703 if (rs->cached_wait_status)
5704 return;
5705
5706 /* Send interrupt_sequence to remote target. */
5707 send_interrupt_sequence ();
5708 }
5709
5710 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5711 the remote target. It is undefined which thread of which process
5712 reports the interrupt. Returns true if the packet is supported by
5713 the server, false otherwise. */
5714
5715 static int
5716 remote_interrupt_ns (void)
5717 {
5718 struct remote_state *rs = get_remote_state ();
5719 char *p = rs->buf;
5720 char *endp = rs->buf + get_remote_packet_size ();
5721
5722 xsnprintf (p, endp - p, "vCtrlC");
5723
5724 /* In non-stop, we get an immediate OK reply. The stop reply will
5725 come in asynchronously by notification. */
5726 putpkt (rs->buf);
5727 getpkt (&rs->buf, &rs->buf_size, 0);
5728
5729 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5730 {
5731 case PACKET_OK:
5732 break;
5733 case PACKET_UNKNOWN:
5734 return 0;
5735 case PACKET_ERROR:
5736 error (_("Interrupting target failed: %s"), rs->buf);
5737 }
5738
5739 return 1;
5740 }
5741
5742 /* Implement the to_stop function for the remote targets. */
5743
5744 static void
5745 remote_stop (struct target_ops *self, ptid_t ptid)
5746 {
5747 if (remote_debug)
5748 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5749
5750 if (target_is_non_stop_p ())
5751 remote_stop_ns (ptid);
5752 else
5753 {
5754 /* We don't currently have a way to transparently pause the
5755 remote target in all-stop mode. Interrupt it instead. */
5756 remote_interrupt_as ();
5757 }
5758 }
5759
5760 /* Implement the to_interrupt function for the remote targets. */
5761
5762 static void
5763 remote_interrupt (struct target_ops *self, ptid_t ptid)
5764 {
5765 if (remote_debug)
5766 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5767
5768 if (non_stop)
5769 {
5770 /* In non-stop mode, we always stop with no signal instead. */
5771 remote_stop_ns (ptid);
5772 }
5773 else
5774 {
5775 /* In all-stop, we emulate ^C-ing the remote target's
5776 terminal. */
5777 if (target_is_non_stop_p ())
5778 {
5779 if (!remote_interrupt_ns ())
5780 {
5781 /* No support for ^C-ing the remote target. Stop it
5782 (with no signal) instead. */
5783 remote_stop_ns (ptid);
5784 }
5785 }
5786 else
5787 remote_interrupt_as ();
5788 }
5789 }
5790
5791 /* Ask the user what to do when an interrupt is received. */
5792
5793 static void
5794 interrupt_query (void)
5795 {
5796 struct remote_state *rs = get_remote_state ();
5797 struct cleanup *old_chain;
5798
5799 old_chain = make_cleanup_restore_target_terminal ();
5800 target_terminal_ours ();
5801
5802 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5803 {
5804 if (query (_("The target is not responding to interrupt requests.\n"
5805 "Stop debugging it? ")))
5806 {
5807 remote_unpush_target ();
5808 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5809 }
5810 }
5811 else
5812 {
5813 if (query (_("Interrupted while waiting for the program.\n"
5814 "Give up waiting? ")))
5815 quit ();
5816 }
5817
5818 do_cleanups (old_chain);
5819 }
5820
5821 /* Enable/disable target terminal ownership. Most targets can use
5822 terminal groups to control terminal ownership. Remote targets are
5823 different in that explicit transfer of ownership to/from GDB/target
5824 is required. */
5825
5826 static void
5827 remote_terminal_inferior (struct target_ops *self)
5828 {
5829 if (!target_async_permitted)
5830 /* Nothing to do. */
5831 return;
5832
5833 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5834 idempotent. The event-loop GDB talking to an asynchronous target
5835 with a synchronous command calls this function from both
5836 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5837 transfer the terminal to the target when it shouldn't this guard
5838 can go away. */
5839 if (!remote_async_terminal_ours_p)
5840 return;
5841 delete_file_handler (input_fd);
5842 remote_async_terminal_ours_p = 0;
5843 async_initialize_sigint_signal_handler ();
5844 /* NOTE: At this point we could also register our selves as the
5845 recipient of all input. Any characters typed could then be
5846 passed on down to the target. */
5847 }
5848
5849 static void
5850 remote_terminal_ours (struct target_ops *self)
5851 {
5852 if (!target_async_permitted)
5853 /* Nothing to do. */
5854 return;
5855
5856 /* See FIXME in remote_terminal_inferior. */
5857 if (remote_async_terminal_ours_p)
5858 return;
5859 async_cleanup_sigint_signal_handler (NULL);
5860 add_file_handler (input_fd, stdin_event_handler, 0);
5861 remote_async_terminal_ours_p = 1;
5862 }
5863
5864 static void
5865 remote_console_output (char *msg)
5866 {
5867 char *p;
5868
5869 for (p = msg; p[0] && p[1]; p += 2)
5870 {
5871 char tb[2];
5872 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5873
5874 tb[0] = c;
5875 tb[1] = 0;
5876 fputs_unfiltered (tb, gdb_stdtarg);
5877 }
5878 gdb_flush (gdb_stdtarg);
5879 }
5880
5881 typedef struct cached_reg
5882 {
5883 int num;
5884 gdb_byte data[MAX_REGISTER_SIZE];
5885 } cached_reg_t;
5886
5887 DEF_VEC_O(cached_reg_t);
5888
5889 typedef struct stop_reply
5890 {
5891 struct notif_event base;
5892
5893 /* The identifier of the thread about this event */
5894 ptid_t ptid;
5895
5896 /* The remote state this event is associated with. When the remote
5897 connection, represented by a remote_state object, is closed,
5898 all the associated stop_reply events should be released. */
5899 struct remote_state *rs;
5900
5901 struct target_waitstatus ws;
5902
5903 /* Expedited registers. This makes remote debugging a bit more
5904 efficient for those targets that provide critical registers as
5905 part of their normal status mechanism (as another roundtrip to
5906 fetch them is avoided). */
5907 VEC(cached_reg_t) *regcache;
5908
5909 enum target_stop_reason stop_reason;
5910
5911 CORE_ADDR watch_data_address;
5912
5913 int core;
5914 } *stop_reply_p;
5915
5916 DECLARE_QUEUE_P (stop_reply_p);
5917 DEFINE_QUEUE_P (stop_reply_p);
5918 /* The list of already fetched and acknowledged stop events. This
5919 queue is used for notification Stop, and other notifications
5920 don't need queue for their events, because the notification events
5921 of Stop can't be consumed immediately, so that events should be
5922 queued first, and be consumed by remote_wait_{ns,as} one per
5923 time. Other notifications can consume their events immediately,
5924 so queue is not needed for them. */
5925 static QUEUE (stop_reply_p) *stop_reply_queue;
5926
5927 static void
5928 stop_reply_xfree (struct stop_reply *r)
5929 {
5930 notif_event_xfree ((struct notif_event *) r);
5931 }
5932
5933 /* Return the length of the stop reply queue. */
5934
5935 static int
5936 stop_reply_queue_length (void)
5937 {
5938 return QUEUE_length (stop_reply_p, stop_reply_queue);
5939 }
5940
5941 static void
5942 remote_notif_stop_parse (struct notif_client *self, char *buf,
5943 struct notif_event *event)
5944 {
5945 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5946 }
5947
5948 static void
5949 remote_notif_stop_ack (struct notif_client *self, char *buf,
5950 struct notif_event *event)
5951 {
5952 struct stop_reply *stop_reply = (struct stop_reply *) event;
5953
5954 /* acknowledge */
5955 putpkt ((char *) self->ack_command);
5956
5957 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5958 /* We got an unknown stop reply. */
5959 error (_("Unknown stop reply"));
5960
5961 push_stop_reply (stop_reply);
5962 }
5963
5964 static int
5965 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5966 {
5967 /* We can't get pending events in remote_notif_process for
5968 notification stop, and we have to do this in remote_wait_ns
5969 instead. If we fetch all queued events from stub, remote stub
5970 may exit and we have no chance to process them back in
5971 remote_wait_ns. */
5972 mark_async_event_handler (remote_async_inferior_event_token);
5973 return 0;
5974 }
5975
5976 static void
5977 stop_reply_dtr (struct notif_event *event)
5978 {
5979 struct stop_reply *r = (struct stop_reply *) event;
5980
5981 VEC_free (cached_reg_t, r->regcache);
5982 }
5983
5984 static struct notif_event *
5985 remote_notif_stop_alloc_reply (void)
5986 {
5987 /* We cast to a pointer to the "base class". */
5988 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5989
5990 r->dtr = stop_reply_dtr;
5991
5992 return r;
5993 }
5994
5995 /* A client of notification Stop. */
5996
5997 struct notif_client notif_client_stop =
5998 {
5999 "Stop",
6000 "vStopped",
6001 remote_notif_stop_parse,
6002 remote_notif_stop_ack,
6003 remote_notif_stop_can_get_pending_events,
6004 remote_notif_stop_alloc_reply,
6005 REMOTE_NOTIF_STOP,
6006 };
6007
6008 /* A parameter to pass data in and out. */
6009
6010 struct queue_iter_param
6011 {
6012 void *input;
6013 struct stop_reply *output;
6014 };
6015
6016 /* Determine if THREAD is a pending fork parent thread. ARG contains
6017 the pid of the process that owns the threads we want to check, or
6018 -1 if we want to check all threads. */
6019
6020 static int
6021 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6022 ptid_t thread_ptid)
6023 {
6024 if (ws->kind == TARGET_WAITKIND_FORKED
6025 || ws->kind == TARGET_WAITKIND_VFORKED)
6026 {
6027 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6028 return 1;
6029 }
6030
6031 return 0;
6032 }
6033
6034 /* Check whether EVENT is a fork event, and if it is, remove the
6035 fork child from the context list passed in DATA. */
6036
6037 static int
6038 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6039 QUEUE_ITER (stop_reply_p) *iter,
6040 stop_reply_p event,
6041 void *data)
6042 {
6043 struct queue_iter_param *param = (struct queue_iter_param *) data;
6044 struct threads_listing_context *context
6045 = (struct threads_listing_context *) param->input;
6046
6047 if (event->ws.kind == TARGET_WAITKIND_FORKED
6048 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6049 {
6050 threads_listing_context_remove (&event->ws, context);
6051 }
6052
6053 return 1;
6054 }
6055
6056 /* If CONTEXT contains any fork child threads that have not been
6057 reported yet, remove them from the CONTEXT list. If such a
6058 thread exists it is because we are stopped at a fork catchpoint
6059 and have not yet called follow_fork, which will set up the
6060 host-side data structures for the new process. */
6061
6062 static void
6063 remove_new_fork_children (struct threads_listing_context *context)
6064 {
6065 struct thread_info * thread;
6066 int pid = -1;
6067 struct notif_client *notif = &notif_client_stop;
6068 struct queue_iter_param param;
6069
6070 /* For any threads stopped at a fork event, remove the corresponding
6071 fork child threads from the CONTEXT list. */
6072 ALL_NON_EXITED_THREADS (thread)
6073 {
6074 struct target_waitstatus *ws = &thread->pending_follow;
6075
6076 if (is_pending_fork_parent (ws, pid, thread->ptid))
6077 {
6078 threads_listing_context_remove (ws, context);
6079 }
6080 }
6081
6082 /* Check for any pending fork events (not reported or processed yet)
6083 in process PID and remove those fork child threads from the
6084 CONTEXT list as well. */
6085 remote_notif_get_pending_events (notif);
6086 param.input = context;
6087 param.output = NULL;
6088 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6089 remove_child_of_pending_fork, &param);
6090 }
6091
6092 /* Remove stop replies in the queue if its pid is equal to the given
6093 inferior's pid. */
6094
6095 static int
6096 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6097 QUEUE_ITER (stop_reply_p) *iter,
6098 stop_reply_p event,
6099 void *data)
6100 {
6101 struct queue_iter_param *param = (struct queue_iter_param *) data;
6102 struct inferior *inf = (struct inferior *) param->input;
6103
6104 if (ptid_get_pid (event->ptid) == inf->pid)
6105 {
6106 stop_reply_xfree (event);
6107 QUEUE_remove_elem (stop_reply_p, q, iter);
6108 }
6109
6110 return 1;
6111 }
6112
6113 /* Discard all pending stop replies of inferior INF. */
6114
6115 static void
6116 discard_pending_stop_replies (struct inferior *inf)
6117 {
6118 int i;
6119 struct queue_iter_param param;
6120 struct stop_reply *reply;
6121 struct remote_state *rs = get_remote_state ();
6122 struct remote_notif_state *rns = rs->notif_state;
6123
6124 /* This function can be notified when an inferior exists. When the
6125 target is not remote, the notification state is NULL. */
6126 if (rs->remote_desc == NULL)
6127 return;
6128
6129 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6130
6131 /* Discard the in-flight notification. */
6132 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6133 {
6134 stop_reply_xfree (reply);
6135 rns->pending_event[notif_client_stop.id] = NULL;
6136 }
6137
6138 param.input = inf;
6139 param.output = NULL;
6140 /* Discard the stop replies we have already pulled with
6141 vStopped. */
6142 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6143 remove_stop_reply_for_inferior, &param);
6144 }
6145
6146 /* If its remote state is equal to the given remote state,
6147 remove EVENT from the stop reply queue. */
6148
6149 static int
6150 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6151 QUEUE_ITER (stop_reply_p) *iter,
6152 stop_reply_p event,
6153 void *data)
6154 {
6155 struct queue_iter_param *param = (struct queue_iter_param *) data;
6156 struct remote_state *rs = (struct remote_state *) param->input;
6157
6158 if (event->rs == rs)
6159 {
6160 stop_reply_xfree (event);
6161 QUEUE_remove_elem (stop_reply_p, q, iter);
6162 }
6163
6164 return 1;
6165 }
6166
6167 /* Discard the stop replies for RS in stop_reply_queue. */
6168
6169 static void
6170 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6171 {
6172 struct queue_iter_param param;
6173
6174 param.input = rs;
6175 param.output = NULL;
6176 /* Discard the stop replies we have already pulled with
6177 vStopped. */
6178 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6179 remove_stop_reply_of_remote_state, &param);
6180 }
6181
6182 /* A parameter to pass data in and out. */
6183
6184 static int
6185 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6186 QUEUE_ITER (stop_reply_p) *iter,
6187 stop_reply_p event,
6188 void *data)
6189 {
6190 struct queue_iter_param *param = (struct queue_iter_param *) data;
6191 ptid_t *ptid = (ptid_t *) param->input;
6192
6193 if (ptid_match (event->ptid, *ptid))
6194 {
6195 param->output = event;
6196 QUEUE_remove_elem (stop_reply_p, q, iter);
6197 return 0;
6198 }
6199
6200 return 1;
6201 }
6202
6203 /* Remove the first reply in 'stop_reply_queue' which matches
6204 PTID. */
6205
6206 static struct stop_reply *
6207 remote_notif_remove_queued_reply (ptid_t ptid)
6208 {
6209 struct queue_iter_param param;
6210
6211 param.input = &ptid;
6212 param.output = NULL;
6213
6214 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6215 remote_notif_remove_once_on_match, &param);
6216 if (notif_debug)
6217 fprintf_unfiltered (gdb_stdlog,
6218 "notif: discard queued event: 'Stop' in %s\n",
6219 target_pid_to_str (ptid));
6220
6221 return param.output;
6222 }
6223
6224 /* Look for a queued stop reply belonging to PTID. If one is found,
6225 remove it from the queue, and return it. Returns NULL if none is
6226 found. If there are still queued events left to process, tell the
6227 event loop to get back to target_wait soon. */
6228
6229 static struct stop_reply *
6230 queued_stop_reply (ptid_t ptid)
6231 {
6232 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6233
6234 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6235 /* There's still at least an event left. */
6236 mark_async_event_handler (remote_async_inferior_event_token);
6237
6238 return r;
6239 }
6240
6241 /* Push a fully parsed stop reply in the stop reply queue. Since we
6242 know that we now have at least one queued event left to pass to the
6243 core side, tell the event loop to get back to target_wait soon. */
6244
6245 static void
6246 push_stop_reply (struct stop_reply *new_event)
6247 {
6248 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6249
6250 if (notif_debug)
6251 fprintf_unfiltered (gdb_stdlog,
6252 "notif: push 'Stop' %s to queue %d\n",
6253 target_pid_to_str (new_event->ptid),
6254 QUEUE_length (stop_reply_p,
6255 stop_reply_queue));
6256
6257 mark_async_event_handler (remote_async_inferior_event_token);
6258 }
6259
6260 static int
6261 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6262 QUEUE_ITER (stop_reply_p) *iter,
6263 struct stop_reply *event,
6264 void *data)
6265 {
6266 ptid_t *ptid = (ptid_t *) data;
6267
6268 return !(ptid_equal (*ptid, event->ptid)
6269 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6270 }
6271
6272 /* Returns true if we have a stop reply for PTID. */
6273
6274 static int
6275 peek_stop_reply (ptid_t ptid)
6276 {
6277 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6278 stop_reply_match_ptid_and_ws, &ptid);
6279 }
6280
6281 /* Skip PACKET until the next semi-colon (or end of string). */
6282
6283 static char *
6284 skip_to_semicolon (char *p)
6285 {
6286 while (*p != '\0' && *p != ';')
6287 p++;
6288 return p;
6289 }
6290
6291 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6292 starting with P and ending with PEND matches PREFIX. */
6293
6294 static int
6295 strprefix (const char *p, const char *pend, const char *prefix)
6296 {
6297 for ( ; p < pend; p++, prefix++)
6298 if (*p != *prefix)
6299 return 0;
6300 return *prefix == '\0';
6301 }
6302
6303 /* Parse the stop reply in BUF. Either the function succeeds, and the
6304 result is stored in EVENT, or throws an error. */
6305
6306 static void
6307 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6308 {
6309 struct remote_arch_state *rsa = get_remote_arch_state ();
6310 ULONGEST addr;
6311 char *p;
6312 int skipregs = 0;
6313
6314 event->ptid = null_ptid;
6315 event->rs = get_remote_state ();
6316 event->ws.kind = TARGET_WAITKIND_IGNORE;
6317 event->ws.value.integer = 0;
6318 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6319 event->regcache = NULL;
6320 event->core = -1;
6321
6322 switch (buf[0])
6323 {
6324 case 'T': /* Status with PC, SP, FP, ... */
6325 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6326 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6327 ss = signal number
6328 n... = register number
6329 r... = register contents
6330 */
6331
6332 p = &buf[3]; /* after Txx */
6333 while (*p)
6334 {
6335 char *p1;
6336 int fieldsize;
6337
6338 p1 = strchr (p, ':');
6339 if (p1 == NULL)
6340 error (_("Malformed packet(a) (missing colon): %s\n\
6341 Packet: '%s'\n"),
6342 p, buf);
6343 if (p == p1)
6344 error (_("Malformed packet(a) (missing register number): %s\n\
6345 Packet: '%s'\n"),
6346 p, buf);
6347
6348 /* Some "registers" are actually extended stop information.
6349 Note if you're adding a new entry here: GDB 7.9 and
6350 earlier assume that all register "numbers" that start
6351 with an hex digit are real register numbers. Make sure
6352 the server only sends such a packet if it knows the
6353 client understands it. */
6354
6355 if (strprefix (p, p1, "thread"))
6356 event->ptid = read_ptid (++p1, &p);
6357 else if (strprefix (p, p1, "watch")
6358 || strprefix (p, p1, "rwatch")
6359 || strprefix (p, p1, "awatch"))
6360 {
6361 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6362 p = unpack_varlen_hex (++p1, &addr);
6363 event->watch_data_address = (CORE_ADDR) addr;
6364 }
6365 else if (strprefix (p, p1, "swbreak"))
6366 {
6367 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6368
6369 /* Make sure the stub doesn't forget to indicate support
6370 with qSupported. */
6371 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6372 error (_("Unexpected swbreak stop reason"));
6373
6374 /* The value part is documented as "must be empty",
6375 though we ignore it, in case we ever decide to make
6376 use of it in a backward compatible way. */
6377 p = skip_to_semicolon (p1 + 1);
6378 }
6379 else if (strprefix (p, p1, "hwbreak"))
6380 {
6381 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6382
6383 /* Make sure the stub doesn't forget to indicate support
6384 with qSupported. */
6385 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6386 error (_("Unexpected hwbreak stop reason"));
6387
6388 /* See above. */
6389 p = skip_to_semicolon (p1 + 1);
6390 }
6391 else if (strprefix (p, p1, "library"))
6392 {
6393 event->ws.kind = TARGET_WAITKIND_LOADED;
6394 p = skip_to_semicolon (p1 + 1);
6395 }
6396 else if (strprefix (p, p1, "replaylog"))
6397 {
6398 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6399 /* p1 will indicate "begin" or "end", but it makes
6400 no difference for now, so ignore it. */
6401 p = skip_to_semicolon (p1 + 1);
6402 }
6403 else if (strprefix (p, p1, "core"))
6404 {
6405 ULONGEST c;
6406
6407 p = unpack_varlen_hex (++p1, &c);
6408 event->core = c;
6409 }
6410 else if (strprefix (p, p1, "fork"))
6411 {
6412 event->ws.value.related_pid = read_ptid (++p1, &p);
6413 event->ws.kind = TARGET_WAITKIND_FORKED;
6414 }
6415 else if (strprefix (p, p1, "vfork"))
6416 {
6417 event->ws.value.related_pid = read_ptid (++p1, &p);
6418 event->ws.kind = TARGET_WAITKIND_VFORKED;
6419 }
6420 else if (strprefix (p, p1, "vforkdone"))
6421 {
6422 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6423 p = skip_to_semicolon (p1 + 1);
6424 }
6425 else if (strprefix (p, p1, "exec"))
6426 {
6427 ULONGEST ignored;
6428 char pathname[PATH_MAX];
6429 int pathlen;
6430
6431 /* Determine the length of the execd pathname. */
6432 p = unpack_varlen_hex (++p1, &ignored);
6433 pathlen = (p - p1) / 2;
6434
6435 /* Save the pathname for event reporting and for
6436 the next run command. */
6437 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6438 pathname[pathlen] = '\0';
6439
6440 /* This is freed during event handling. */
6441 event->ws.value.execd_pathname = xstrdup (pathname);
6442 event->ws.kind = TARGET_WAITKIND_EXECD;
6443
6444 /* Skip the registers included in this packet, since
6445 they may be for an architecture different from the
6446 one used by the original program. */
6447 skipregs = 1;
6448 }
6449 else
6450 {
6451 ULONGEST pnum;
6452 char *p_temp;
6453
6454 if (skipregs)
6455 {
6456 p = skip_to_semicolon (p1 + 1);
6457 p++;
6458 continue;
6459 }
6460
6461 /* Maybe a real ``P'' register number. */
6462 p_temp = unpack_varlen_hex (p, &pnum);
6463 /* If the first invalid character is the colon, we got a
6464 register number. Otherwise, it's an unknown stop
6465 reason. */
6466 if (p_temp == p1)
6467 {
6468 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6469 cached_reg_t cached_reg;
6470
6471 if (reg == NULL)
6472 error (_("Remote sent bad register number %s: %s\n\
6473 Packet: '%s'\n"),
6474 hex_string (pnum), p, buf);
6475
6476 cached_reg.num = reg->regnum;
6477
6478 p = p1 + 1;
6479 fieldsize = hex2bin (p, cached_reg.data,
6480 register_size (target_gdbarch (),
6481 reg->regnum));
6482 p += 2 * fieldsize;
6483 if (fieldsize < register_size (target_gdbarch (),
6484 reg->regnum))
6485 warning (_("Remote reply is too short: %s"), buf);
6486
6487 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6488 }
6489 else
6490 {
6491 /* Not a number. Silently skip unknown optional
6492 info. */
6493 p = skip_to_semicolon (p1 + 1);
6494 }
6495 }
6496
6497 if (*p != ';')
6498 error (_("Remote register badly formatted: %s\nhere: %s"),
6499 buf, p);
6500 ++p;
6501 }
6502
6503 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6504 break;
6505
6506 /* fall through */
6507 case 'S': /* Old style status, just signal only. */
6508 {
6509 int sig;
6510
6511 event->ws.kind = TARGET_WAITKIND_STOPPED;
6512 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6513 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6514 event->ws.value.sig = (enum gdb_signal) sig;
6515 else
6516 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6517 }
6518 break;
6519 case 'W': /* Target exited. */
6520 case 'X':
6521 {
6522 char *p;
6523 int pid;
6524 ULONGEST value;
6525
6526 /* GDB used to accept only 2 hex chars here. Stubs should
6527 only send more if they detect GDB supports multi-process
6528 support. */
6529 p = unpack_varlen_hex (&buf[1], &value);
6530
6531 if (buf[0] == 'W')
6532 {
6533 /* The remote process exited. */
6534 event->ws.kind = TARGET_WAITKIND_EXITED;
6535 event->ws.value.integer = value;
6536 }
6537 else
6538 {
6539 /* The remote process exited with a signal. */
6540 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6541 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6542 event->ws.value.sig = (enum gdb_signal) value;
6543 else
6544 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6545 }
6546
6547 /* If no process is specified, assume inferior_ptid. */
6548 pid = ptid_get_pid (inferior_ptid);
6549 if (*p == '\0')
6550 ;
6551 else if (*p == ';')
6552 {
6553 p++;
6554
6555 if (*p == '\0')
6556 ;
6557 else if (startswith (p, "process:"))
6558 {
6559 ULONGEST upid;
6560
6561 p += sizeof ("process:") - 1;
6562 unpack_varlen_hex (p, &upid);
6563 pid = upid;
6564 }
6565 else
6566 error (_("unknown stop reply packet: %s"), buf);
6567 }
6568 else
6569 error (_("unknown stop reply packet: %s"), buf);
6570 event->ptid = pid_to_ptid (pid);
6571 }
6572 break;
6573 }
6574
6575 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6576 error (_("No process or thread specified in stop reply: %s"), buf);
6577 }
6578
6579 /* When the stub wants to tell GDB about a new notification reply, it
6580 sends a notification (%Stop, for example). Those can come it at
6581 any time, hence, we have to make sure that any pending
6582 putpkt/getpkt sequence we're making is finished, before querying
6583 the stub for more events with the corresponding ack command
6584 (vStopped, for example). E.g., if we started a vStopped sequence
6585 immediately upon receiving the notification, something like this
6586 could happen:
6587
6588 1.1) --> Hg 1
6589 1.2) <-- OK
6590 1.3) --> g
6591 1.4) <-- %Stop
6592 1.5) --> vStopped
6593 1.6) <-- (registers reply to step #1.3)
6594
6595 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6596 query.
6597
6598 To solve this, whenever we parse a %Stop notification successfully,
6599 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6600 doing whatever we were doing:
6601
6602 2.1) --> Hg 1
6603 2.2) <-- OK
6604 2.3) --> g
6605 2.4) <-- %Stop
6606 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6607 2.5) <-- (registers reply to step #2.3)
6608
6609 Eventualy after step #2.5, we return to the event loop, which
6610 notices there's an event on the
6611 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6612 associated callback --- the function below. At this point, we're
6613 always safe to start a vStopped sequence. :
6614
6615 2.6) --> vStopped
6616 2.7) <-- T05 thread:2
6617 2.8) --> vStopped
6618 2.9) --> OK
6619 */
6620
6621 void
6622 remote_notif_get_pending_events (struct notif_client *nc)
6623 {
6624 struct remote_state *rs = get_remote_state ();
6625
6626 if (rs->notif_state->pending_event[nc->id] != NULL)
6627 {
6628 if (notif_debug)
6629 fprintf_unfiltered (gdb_stdlog,
6630 "notif: process: '%s' ack pending event\n",
6631 nc->name);
6632
6633 /* acknowledge */
6634 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6635 rs->notif_state->pending_event[nc->id] = NULL;
6636
6637 while (1)
6638 {
6639 getpkt (&rs->buf, &rs->buf_size, 0);
6640 if (strcmp (rs->buf, "OK") == 0)
6641 break;
6642 else
6643 remote_notif_ack (nc, rs->buf);
6644 }
6645 }
6646 else
6647 {
6648 if (notif_debug)
6649 fprintf_unfiltered (gdb_stdlog,
6650 "notif: process: '%s' no pending reply\n",
6651 nc->name);
6652 }
6653 }
6654
6655 /* Called when it is decided that STOP_REPLY holds the info of the
6656 event that is to be returned to the core. This function always
6657 destroys STOP_REPLY. */
6658
6659 static ptid_t
6660 process_stop_reply (struct stop_reply *stop_reply,
6661 struct target_waitstatus *status)
6662 {
6663 ptid_t ptid;
6664
6665 *status = stop_reply->ws;
6666 ptid = stop_reply->ptid;
6667
6668 /* If no thread/process was reported by the stub, assume the current
6669 inferior. */
6670 if (ptid_equal (ptid, null_ptid))
6671 ptid = inferior_ptid;
6672
6673 if (status->kind != TARGET_WAITKIND_EXITED
6674 && status->kind != TARGET_WAITKIND_SIGNALLED)
6675 {
6676 struct remote_state *rs = get_remote_state ();
6677 struct private_thread_info *remote_thr;
6678
6679 /* Expedited registers. */
6680 if (stop_reply->regcache)
6681 {
6682 struct regcache *regcache
6683 = get_thread_arch_regcache (ptid, target_gdbarch ());
6684 cached_reg_t *reg;
6685 int ix;
6686
6687 for (ix = 0;
6688 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6689 ix++)
6690 regcache_raw_supply (regcache, reg->num, reg->data);
6691 VEC_free (cached_reg_t, stop_reply->regcache);
6692 }
6693
6694 remote_notice_new_inferior (ptid, 0);
6695 remote_thr = demand_private_info (ptid);
6696 remote_thr->core = stop_reply->core;
6697 remote_thr->stop_reason = stop_reply->stop_reason;
6698 remote_thr->watch_data_address = stop_reply->watch_data_address;
6699 }
6700
6701 stop_reply_xfree (stop_reply);
6702 return ptid;
6703 }
6704
6705 /* The non-stop mode version of target_wait. */
6706
6707 static ptid_t
6708 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6709 {
6710 struct remote_state *rs = get_remote_state ();
6711 struct stop_reply *stop_reply;
6712 int ret;
6713 int is_notif = 0;
6714
6715 /* If in non-stop mode, get out of getpkt even if a
6716 notification is received. */
6717
6718 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6719 0 /* forever */, &is_notif);
6720 while (1)
6721 {
6722 if (ret != -1 && !is_notif)
6723 switch (rs->buf[0])
6724 {
6725 case 'E': /* Error of some sort. */
6726 /* We're out of sync with the target now. Did it continue
6727 or not? We can't tell which thread it was in non-stop,
6728 so just ignore this. */
6729 warning (_("Remote failure reply: %s"), rs->buf);
6730 break;
6731 case 'O': /* Console output. */
6732 remote_console_output (rs->buf + 1);
6733 break;
6734 default:
6735 warning (_("Invalid remote reply: %s"), rs->buf);
6736 break;
6737 }
6738
6739 /* Acknowledge a pending stop reply that may have arrived in the
6740 mean time. */
6741 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6742 remote_notif_get_pending_events (&notif_client_stop);
6743
6744 /* If indeed we noticed a stop reply, we're done. */
6745 stop_reply = queued_stop_reply (ptid);
6746 if (stop_reply != NULL)
6747 return process_stop_reply (stop_reply, status);
6748
6749 /* Still no event. If we're just polling for an event, then
6750 return to the event loop. */
6751 if (options & TARGET_WNOHANG)
6752 {
6753 status->kind = TARGET_WAITKIND_IGNORE;
6754 return minus_one_ptid;
6755 }
6756
6757 /* Otherwise do a blocking wait. */
6758 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6759 1 /* forever */, &is_notif);
6760 }
6761 }
6762
6763 /* Wait until the remote machine stops, then return, storing status in
6764 STATUS just as `wait' would. */
6765
6766 static ptid_t
6767 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6768 {
6769 struct remote_state *rs = get_remote_state ();
6770 ptid_t event_ptid = null_ptid;
6771 char *buf;
6772 struct stop_reply *stop_reply;
6773
6774 again:
6775
6776 status->kind = TARGET_WAITKIND_IGNORE;
6777 status->value.integer = 0;
6778
6779 stop_reply = queued_stop_reply (ptid);
6780 if (stop_reply != NULL)
6781 return process_stop_reply (stop_reply, status);
6782
6783 if (rs->cached_wait_status)
6784 /* Use the cached wait status, but only once. */
6785 rs->cached_wait_status = 0;
6786 else
6787 {
6788 int ret;
6789 int is_notif;
6790 int forever = ((options & TARGET_WNOHANG) == 0
6791 && wait_forever_enabled_p);
6792
6793 if (!rs->waiting_for_stop_reply)
6794 {
6795 status->kind = TARGET_WAITKIND_NO_RESUMED;
6796 return minus_one_ptid;
6797 }
6798
6799 if (!target_is_async_p ())
6800 {
6801 ofunc = signal (SIGINT, sync_remote_interrupt);
6802 /* If the user hit C-c before this packet, or between packets,
6803 pretend that it was hit right here. */
6804 if (check_quit_flag ())
6805 {
6806 clear_quit_flag ();
6807 sync_remote_interrupt (SIGINT);
6808 }
6809 }
6810
6811 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6812 _never_ wait for ever -> test on target_is_async_p().
6813 However, before we do that we need to ensure that the caller
6814 knows how to take the target into/out of async mode. */
6815 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6816 forever, &is_notif);
6817
6818 if (!target_is_async_p ())
6819 signal (SIGINT, ofunc);
6820
6821 /* GDB gets a notification. Return to core as this event is
6822 not interesting. */
6823 if (ret != -1 && is_notif)
6824 return minus_one_ptid;
6825
6826 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6827 return minus_one_ptid;
6828 }
6829
6830 buf = rs->buf;
6831
6832 /* Assume that the target has acknowledged Ctrl-C unless we receive
6833 an 'F' or 'O' packet. */
6834 if (buf[0] != 'F' && buf[0] != 'O')
6835 rs->ctrlc_pending_p = 0;
6836
6837 switch (buf[0])
6838 {
6839 case 'E': /* Error of some sort. */
6840 /* We're out of sync with the target now. Did it continue or
6841 not? Not is more likely, so report a stop. */
6842 rs->waiting_for_stop_reply = 0;
6843
6844 warning (_("Remote failure reply: %s"), buf);
6845 status->kind = TARGET_WAITKIND_STOPPED;
6846 status->value.sig = GDB_SIGNAL_0;
6847 break;
6848 case 'F': /* File-I/O request. */
6849 remote_fileio_request (buf, rs->ctrlc_pending_p);
6850 rs->ctrlc_pending_p = 0;
6851 break;
6852 case 'T': case 'S': case 'X': case 'W':
6853 {
6854 struct stop_reply *stop_reply;
6855
6856 /* There is a stop reply to handle. */
6857 rs->waiting_for_stop_reply = 0;
6858
6859 stop_reply
6860 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6861 rs->buf);
6862
6863 event_ptid = process_stop_reply (stop_reply, status);
6864 break;
6865 }
6866 case 'O': /* Console output. */
6867 remote_console_output (buf + 1);
6868 break;
6869 case '\0':
6870 if (rs->last_sent_signal != GDB_SIGNAL_0)
6871 {
6872 /* Zero length reply means that we tried 'S' or 'C' and the
6873 remote system doesn't support it. */
6874 target_terminal_ours_for_output ();
6875 printf_filtered
6876 ("Can't send signals to this remote system. %s not sent.\n",
6877 gdb_signal_to_name (rs->last_sent_signal));
6878 rs->last_sent_signal = GDB_SIGNAL_0;
6879 target_terminal_inferior ();
6880
6881 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6882 putpkt ((char *) buf);
6883 break;
6884 }
6885 /* else fallthrough */
6886 default:
6887 warning (_("Invalid remote reply: %s"), buf);
6888 break;
6889 }
6890
6891 if (status->kind == TARGET_WAITKIND_IGNORE)
6892 {
6893 /* Nothing interesting happened. If we're doing a non-blocking
6894 poll, we're done. Otherwise, go back to waiting. */
6895 if (options & TARGET_WNOHANG)
6896 return minus_one_ptid;
6897 else
6898 goto again;
6899 }
6900 else if (status->kind != TARGET_WAITKIND_EXITED
6901 && status->kind != TARGET_WAITKIND_SIGNALLED)
6902 {
6903 if (!ptid_equal (event_ptid, null_ptid))
6904 record_currthread (rs, event_ptid);
6905 else
6906 event_ptid = inferior_ptid;
6907 }
6908 else
6909 /* A process exit. Invalidate our notion of current thread. */
6910 record_currthread (rs, minus_one_ptid);
6911
6912 return event_ptid;
6913 }
6914
6915 /* Wait until the remote machine stops, then return, storing status in
6916 STATUS just as `wait' would. */
6917
6918 static ptid_t
6919 remote_wait (struct target_ops *ops,
6920 ptid_t ptid, struct target_waitstatus *status, int options)
6921 {
6922 ptid_t event_ptid;
6923
6924 if (target_is_non_stop_p ())
6925 event_ptid = remote_wait_ns (ptid, status, options);
6926 else
6927 event_ptid = remote_wait_as (ptid, status, options);
6928
6929 if (target_is_async_p ())
6930 {
6931 /* If there are are events left in the queue tell the event loop
6932 to return here. */
6933 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6934 mark_async_event_handler (remote_async_inferior_event_token);
6935 }
6936
6937 return event_ptid;
6938 }
6939
6940 /* Fetch a single register using a 'p' packet. */
6941
6942 static int
6943 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6944 {
6945 struct remote_state *rs = get_remote_state ();
6946 char *buf, *p;
6947 char regp[MAX_REGISTER_SIZE];
6948 int i;
6949
6950 if (packet_support (PACKET_p) == PACKET_DISABLE)
6951 return 0;
6952
6953 if (reg->pnum == -1)
6954 return 0;
6955
6956 p = rs->buf;
6957 *p++ = 'p';
6958 p += hexnumstr (p, reg->pnum);
6959 *p++ = '\0';
6960 putpkt (rs->buf);
6961 getpkt (&rs->buf, &rs->buf_size, 0);
6962
6963 buf = rs->buf;
6964
6965 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6966 {
6967 case PACKET_OK:
6968 break;
6969 case PACKET_UNKNOWN:
6970 return 0;
6971 case PACKET_ERROR:
6972 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6973 gdbarch_register_name (get_regcache_arch (regcache),
6974 reg->regnum),
6975 buf);
6976 }
6977
6978 /* If this register is unfetchable, tell the regcache. */
6979 if (buf[0] == 'x')
6980 {
6981 regcache_raw_supply (regcache, reg->regnum, NULL);
6982 return 1;
6983 }
6984
6985 /* Otherwise, parse and supply the value. */
6986 p = buf;
6987 i = 0;
6988 while (p[0] != 0)
6989 {
6990 if (p[1] == 0)
6991 error (_("fetch_register_using_p: early buf termination"));
6992
6993 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6994 p += 2;
6995 }
6996 regcache_raw_supply (regcache, reg->regnum, regp);
6997 return 1;
6998 }
6999
7000 /* Fetch the registers included in the target's 'g' packet. */
7001
7002 static int
7003 send_g_packet (void)
7004 {
7005 struct remote_state *rs = get_remote_state ();
7006 int buf_len;
7007
7008 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7009 remote_send (&rs->buf, &rs->buf_size);
7010
7011 /* We can get out of synch in various cases. If the first character
7012 in the buffer is not a hex character, assume that has happened
7013 and try to fetch another packet to read. */
7014 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7015 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7016 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7017 && rs->buf[0] != 'x') /* New: unavailable register value. */
7018 {
7019 if (remote_debug)
7020 fprintf_unfiltered (gdb_stdlog,
7021 "Bad register packet; fetching a new packet\n");
7022 getpkt (&rs->buf, &rs->buf_size, 0);
7023 }
7024
7025 buf_len = strlen (rs->buf);
7026
7027 /* Sanity check the received packet. */
7028 if (buf_len % 2 != 0)
7029 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7030
7031 return buf_len / 2;
7032 }
7033
7034 static void
7035 process_g_packet (struct regcache *regcache)
7036 {
7037 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7038 struct remote_state *rs = get_remote_state ();
7039 struct remote_arch_state *rsa = get_remote_arch_state ();
7040 int i, buf_len;
7041 char *p;
7042 char *regs;
7043
7044 buf_len = strlen (rs->buf);
7045
7046 /* Further sanity checks, with knowledge of the architecture. */
7047 if (buf_len > 2 * rsa->sizeof_g_packet)
7048 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7049
7050 /* Save the size of the packet sent to us by the target. It is used
7051 as a heuristic when determining the max size of packets that the
7052 target can safely receive. */
7053 if (rsa->actual_register_packet_size == 0)
7054 rsa->actual_register_packet_size = buf_len;
7055
7056 /* If this is smaller than we guessed the 'g' packet would be,
7057 update our records. A 'g' reply that doesn't include a register's
7058 value implies either that the register is not available, or that
7059 the 'p' packet must be used. */
7060 if (buf_len < 2 * rsa->sizeof_g_packet)
7061 {
7062 rsa->sizeof_g_packet = buf_len / 2;
7063
7064 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7065 {
7066 if (rsa->regs[i].pnum == -1)
7067 continue;
7068
7069 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7070 rsa->regs[i].in_g_packet = 0;
7071 else
7072 rsa->regs[i].in_g_packet = 1;
7073 }
7074 }
7075
7076 regs = (char *) alloca (rsa->sizeof_g_packet);
7077
7078 /* Unimplemented registers read as all bits zero. */
7079 memset (regs, 0, rsa->sizeof_g_packet);
7080
7081 /* Reply describes registers byte by byte, each byte encoded as two
7082 hex characters. Suck them all up, then supply them to the
7083 register cacheing/storage mechanism. */
7084
7085 p = rs->buf;
7086 for (i = 0; i < rsa->sizeof_g_packet; i++)
7087 {
7088 if (p[0] == 0 || p[1] == 0)
7089 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7090 internal_error (__FILE__, __LINE__,
7091 _("unexpected end of 'g' packet reply"));
7092
7093 if (p[0] == 'x' && p[1] == 'x')
7094 regs[i] = 0; /* 'x' */
7095 else
7096 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7097 p += 2;
7098 }
7099
7100 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7101 {
7102 struct packet_reg *r = &rsa->regs[i];
7103
7104 if (r->in_g_packet)
7105 {
7106 if (r->offset * 2 >= strlen (rs->buf))
7107 /* This shouldn't happen - we adjusted in_g_packet above. */
7108 internal_error (__FILE__, __LINE__,
7109 _("unexpected end of 'g' packet reply"));
7110 else if (rs->buf[r->offset * 2] == 'x')
7111 {
7112 gdb_assert (r->offset * 2 < strlen (rs->buf));
7113 /* The register isn't available, mark it as such (at
7114 the same time setting the value to zero). */
7115 regcache_raw_supply (regcache, r->regnum, NULL);
7116 }
7117 else
7118 regcache_raw_supply (regcache, r->regnum,
7119 regs + r->offset);
7120 }
7121 }
7122 }
7123
7124 static void
7125 fetch_registers_using_g (struct regcache *regcache)
7126 {
7127 send_g_packet ();
7128 process_g_packet (regcache);
7129 }
7130
7131 /* Make the remote selected traceframe match GDB's selected
7132 traceframe. */
7133
7134 static void
7135 set_remote_traceframe (void)
7136 {
7137 int newnum;
7138 struct remote_state *rs = get_remote_state ();
7139
7140 if (rs->remote_traceframe_number == get_traceframe_number ())
7141 return;
7142
7143 /* Avoid recursion, remote_trace_find calls us again. */
7144 rs->remote_traceframe_number = get_traceframe_number ();
7145
7146 newnum = target_trace_find (tfind_number,
7147 get_traceframe_number (), 0, 0, NULL);
7148
7149 /* Should not happen. If it does, all bets are off. */
7150 if (newnum != get_traceframe_number ())
7151 warning (_("could not set remote traceframe"));
7152 }
7153
7154 static void
7155 remote_fetch_registers (struct target_ops *ops,
7156 struct regcache *regcache, int regnum)
7157 {
7158 struct remote_arch_state *rsa = get_remote_arch_state ();
7159 int i;
7160
7161 set_remote_traceframe ();
7162 set_general_thread (inferior_ptid);
7163
7164 if (regnum >= 0)
7165 {
7166 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7167
7168 gdb_assert (reg != NULL);
7169
7170 /* If this register might be in the 'g' packet, try that first -
7171 we are likely to read more than one register. If this is the
7172 first 'g' packet, we might be overly optimistic about its
7173 contents, so fall back to 'p'. */
7174 if (reg->in_g_packet)
7175 {
7176 fetch_registers_using_g (regcache);
7177 if (reg->in_g_packet)
7178 return;
7179 }
7180
7181 if (fetch_register_using_p (regcache, reg))
7182 return;
7183
7184 /* This register is not available. */
7185 regcache_raw_supply (regcache, reg->regnum, NULL);
7186
7187 return;
7188 }
7189
7190 fetch_registers_using_g (regcache);
7191
7192 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7193 if (!rsa->regs[i].in_g_packet)
7194 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7195 {
7196 /* This register is not available. */
7197 regcache_raw_supply (regcache, i, NULL);
7198 }
7199 }
7200
7201 /* Prepare to store registers. Since we may send them all (using a
7202 'G' request), we have to read out the ones we don't want to change
7203 first. */
7204
7205 static void
7206 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7207 {
7208 struct remote_arch_state *rsa = get_remote_arch_state ();
7209 int i;
7210 gdb_byte buf[MAX_REGISTER_SIZE];
7211
7212 /* Make sure the entire registers array is valid. */
7213 switch (packet_support (PACKET_P))
7214 {
7215 case PACKET_DISABLE:
7216 case PACKET_SUPPORT_UNKNOWN:
7217 /* Make sure all the necessary registers are cached. */
7218 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7219 if (rsa->regs[i].in_g_packet)
7220 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7221 break;
7222 case PACKET_ENABLE:
7223 break;
7224 }
7225 }
7226
7227 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7228 packet was not recognized. */
7229
7230 static int
7231 store_register_using_P (const struct regcache *regcache,
7232 struct packet_reg *reg)
7233 {
7234 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7235 struct remote_state *rs = get_remote_state ();
7236 /* Try storing a single register. */
7237 char *buf = rs->buf;
7238 gdb_byte regp[MAX_REGISTER_SIZE];
7239 char *p;
7240
7241 if (packet_support (PACKET_P) == PACKET_DISABLE)
7242 return 0;
7243
7244 if (reg->pnum == -1)
7245 return 0;
7246
7247 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7248 p = buf + strlen (buf);
7249 regcache_raw_collect (regcache, reg->regnum, regp);
7250 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7251 putpkt (rs->buf);
7252 getpkt (&rs->buf, &rs->buf_size, 0);
7253
7254 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7255 {
7256 case PACKET_OK:
7257 return 1;
7258 case PACKET_ERROR:
7259 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7260 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7261 case PACKET_UNKNOWN:
7262 return 0;
7263 default:
7264 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7265 }
7266 }
7267
7268 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7269 contents of the register cache buffer. FIXME: ignores errors. */
7270
7271 static void
7272 store_registers_using_G (const struct regcache *regcache)
7273 {
7274 struct remote_state *rs = get_remote_state ();
7275 struct remote_arch_state *rsa = get_remote_arch_state ();
7276 gdb_byte *regs;
7277 char *p;
7278
7279 /* Extract all the registers in the regcache copying them into a
7280 local buffer. */
7281 {
7282 int i;
7283
7284 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7285 memset (regs, 0, rsa->sizeof_g_packet);
7286 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7287 {
7288 struct packet_reg *r = &rsa->regs[i];
7289
7290 if (r->in_g_packet)
7291 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7292 }
7293 }
7294
7295 /* Command describes registers byte by byte,
7296 each byte encoded as two hex characters. */
7297 p = rs->buf;
7298 *p++ = 'G';
7299 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7300 updated. */
7301 bin2hex (regs, p, rsa->sizeof_g_packet);
7302 putpkt (rs->buf);
7303 getpkt (&rs->buf, &rs->buf_size, 0);
7304 if (packet_check_result (rs->buf) == PACKET_ERROR)
7305 error (_("Could not write registers; remote failure reply '%s'"),
7306 rs->buf);
7307 }
7308
7309 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7310 of the register cache buffer. FIXME: ignores errors. */
7311
7312 static void
7313 remote_store_registers (struct target_ops *ops,
7314 struct regcache *regcache, int regnum)
7315 {
7316 struct remote_arch_state *rsa = get_remote_arch_state ();
7317 int i;
7318
7319 set_remote_traceframe ();
7320 set_general_thread (inferior_ptid);
7321
7322 if (regnum >= 0)
7323 {
7324 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7325
7326 gdb_assert (reg != NULL);
7327
7328 /* Always prefer to store registers using the 'P' packet if
7329 possible; we often change only a small number of registers.
7330 Sometimes we change a larger number; we'd need help from a
7331 higher layer to know to use 'G'. */
7332 if (store_register_using_P (regcache, reg))
7333 return;
7334
7335 /* For now, don't complain if we have no way to write the
7336 register. GDB loses track of unavailable registers too
7337 easily. Some day, this may be an error. We don't have
7338 any way to read the register, either... */
7339 if (!reg->in_g_packet)
7340 return;
7341
7342 store_registers_using_G (regcache);
7343 return;
7344 }
7345
7346 store_registers_using_G (regcache);
7347
7348 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7349 if (!rsa->regs[i].in_g_packet)
7350 if (!store_register_using_P (regcache, &rsa->regs[i]))
7351 /* See above for why we do not issue an error here. */
7352 continue;
7353 }
7354 \f
7355
7356 /* Return the number of hex digits in num. */
7357
7358 static int
7359 hexnumlen (ULONGEST num)
7360 {
7361 int i;
7362
7363 for (i = 0; num != 0; i++)
7364 num >>= 4;
7365
7366 return max (i, 1);
7367 }
7368
7369 /* Set BUF to the minimum number of hex digits representing NUM. */
7370
7371 static int
7372 hexnumstr (char *buf, ULONGEST num)
7373 {
7374 int len = hexnumlen (num);
7375
7376 return hexnumnstr (buf, num, len);
7377 }
7378
7379
7380 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7381
7382 static int
7383 hexnumnstr (char *buf, ULONGEST num, int width)
7384 {
7385 int i;
7386
7387 buf[width] = '\0';
7388
7389 for (i = width - 1; i >= 0; i--)
7390 {
7391 buf[i] = "0123456789abcdef"[(num & 0xf)];
7392 num >>= 4;
7393 }
7394
7395 return width;
7396 }
7397
7398 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7399
7400 static CORE_ADDR
7401 remote_address_masked (CORE_ADDR addr)
7402 {
7403 unsigned int address_size = remote_address_size;
7404
7405 /* If "remoteaddresssize" was not set, default to target address size. */
7406 if (!address_size)
7407 address_size = gdbarch_addr_bit (target_gdbarch ());
7408
7409 if (address_size > 0
7410 && address_size < (sizeof (ULONGEST) * 8))
7411 {
7412 /* Only create a mask when that mask can safely be constructed
7413 in a ULONGEST variable. */
7414 ULONGEST mask = 1;
7415
7416 mask = (mask << address_size) - 1;
7417 addr &= mask;
7418 }
7419 return addr;
7420 }
7421
7422 /* Determine whether the remote target supports binary downloading.
7423 This is accomplished by sending a no-op memory write of zero length
7424 to the target at the specified address. It does not suffice to send
7425 the whole packet, since many stubs strip the eighth bit and
7426 subsequently compute a wrong checksum, which causes real havoc with
7427 remote_write_bytes.
7428
7429 NOTE: This can still lose if the serial line is not eight-bit
7430 clean. In cases like this, the user should clear "remote
7431 X-packet". */
7432
7433 static void
7434 check_binary_download (CORE_ADDR addr)
7435 {
7436 struct remote_state *rs = get_remote_state ();
7437
7438 switch (packet_support (PACKET_X))
7439 {
7440 case PACKET_DISABLE:
7441 break;
7442 case PACKET_ENABLE:
7443 break;
7444 case PACKET_SUPPORT_UNKNOWN:
7445 {
7446 char *p;
7447
7448 p = rs->buf;
7449 *p++ = 'X';
7450 p += hexnumstr (p, (ULONGEST) addr);
7451 *p++ = ',';
7452 p += hexnumstr (p, (ULONGEST) 0);
7453 *p++ = ':';
7454 *p = '\0';
7455
7456 putpkt_binary (rs->buf, (int) (p - rs->buf));
7457 getpkt (&rs->buf, &rs->buf_size, 0);
7458
7459 if (rs->buf[0] == '\0')
7460 {
7461 if (remote_debug)
7462 fprintf_unfiltered (gdb_stdlog,
7463 "binary downloading NOT "
7464 "supported by target\n");
7465 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7466 }
7467 else
7468 {
7469 if (remote_debug)
7470 fprintf_unfiltered (gdb_stdlog,
7471 "binary downloading supported by target\n");
7472 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7473 }
7474 break;
7475 }
7476 }
7477 }
7478
7479 /* Helper function to resize the payload in order to try to get a good
7480 alignment. We try to write an amount of data such that the next write will
7481 start on an address aligned on REMOTE_ALIGN_WRITES. */
7482
7483 static int
7484 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7485 {
7486 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7487 }
7488
7489 /* Write memory data directly to the remote machine.
7490 This does not inform the data cache; the data cache uses this.
7491 HEADER is the starting part of the packet.
7492 MEMADDR is the address in the remote memory space.
7493 MYADDR is the address of the buffer in our space.
7494 LEN_UNITS is the number of addressable units to write.
7495 UNIT_SIZE is the length in bytes of an addressable unit.
7496 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7497 should send data as binary ('X'), or hex-encoded ('M').
7498
7499 The function creates packet of the form
7500 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7501
7502 where encoding of <DATA> is terminated by PACKET_FORMAT.
7503
7504 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7505 are omitted.
7506
7507 Return the transferred status, error or OK (an
7508 'enum target_xfer_status' value). Save the number of addressable units
7509 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7510
7511 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7512 exchange between gdb and the stub could look like (?? in place of the
7513 checksum):
7514
7515 -> $m1000,4#??
7516 <- aaaabbbbccccdddd
7517
7518 -> $M1000,3:eeeeffffeeee#??
7519 <- OK
7520
7521 -> $m1000,4#??
7522 <- eeeeffffeeeedddd */
7523
7524 static enum target_xfer_status
7525 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7526 const gdb_byte *myaddr, ULONGEST len_units,
7527 int unit_size, ULONGEST *xfered_len_units,
7528 char packet_format, int use_length)
7529 {
7530 struct remote_state *rs = get_remote_state ();
7531 char *p;
7532 char *plen = NULL;
7533 int plenlen = 0;
7534 int todo_units;
7535 int units_written;
7536 int payload_capacity_bytes;
7537 int payload_length_bytes;
7538
7539 if (packet_format != 'X' && packet_format != 'M')
7540 internal_error (__FILE__, __LINE__,
7541 _("remote_write_bytes_aux: bad packet format"));
7542
7543 if (len_units == 0)
7544 return TARGET_XFER_EOF;
7545
7546 payload_capacity_bytes = get_memory_write_packet_size ();
7547
7548 /* The packet buffer will be large enough for the payload;
7549 get_memory_packet_size ensures this. */
7550 rs->buf[0] = '\0';
7551
7552 /* Compute the size of the actual payload by subtracting out the
7553 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7554
7555 payload_capacity_bytes -= strlen ("$,:#NN");
7556 if (!use_length)
7557 /* The comma won't be used. */
7558 payload_capacity_bytes += 1;
7559 payload_capacity_bytes -= strlen (header);
7560 payload_capacity_bytes -= hexnumlen (memaddr);
7561
7562 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7563
7564 strcat (rs->buf, header);
7565 p = rs->buf + strlen (header);
7566
7567 /* Compute a best guess of the number of bytes actually transfered. */
7568 if (packet_format == 'X')
7569 {
7570 /* Best guess at number of bytes that will fit. */
7571 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7572 if (use_length)
7573 payload_capacity_bytes -= hexnumlen (todo_units);
7574 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7575 }
7576 else
7577 {
7578 /* Number of bytes that will fit. */
7579 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7580 if (use_length)
7581 payload_capacity_bytes -= hexnumlen (todo_units);
7582 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7583 }
7584
7585 if (todo_units <= 0)
7586 internal_error (__FILE__, __LINE__,
7587 _("minimum packet size too small to write data"));
7588
7589 /* If we already need another packet, then try to align the end
7590 of this packet to a useful boundary. */
7591 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7592 todo_units = align_for_efficient_write (todo_units, memaddr);
7593
7594 /* Append "<memaddr>". */
7595 memaddr = remote_address_masked (memaddr);
7596 p += hexnumstr (p, (ULONGEST) memaddr);
7597
7598 if (use_length)
7599 {
7600 /* Append ",". */
7601 *p++ = ',';
7602
7603 /* Append the length and retain its location and size. It may need to be
7604 adjusted once the packet body has been created. */
7605 plen = p;
7606 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7607 p += plenlen;
7608 }
7609
7610 /* Append ":". */
7611 *p++ = ':';
7612 *p = '\0';
7613
7614 /* Append the packet body. */
7615 if (packet_format == 'X')
7616 {
7617 /* Binary mode. Send target system values byte by byte, in
7618 increasing byte addresses. Only escape certain critical
7619 characters. */
7620 payload_length_bytes =
7621 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7622 &units_written, payload_capacity_bytes);
7623
7624 /* If not all TODO units fit, then we'll need another packet. Make
7625 a second try to keep the end of the packet aligned. Don't do
7626 this if the packet is tiny. */
7627 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7628 {
7629 int new_todo_units;
7630
7631 new_todo_units = align_for_efficient_write (units_written, memaddr);
7632
7633 if (new_todo_units != units_written)
7634 payload_length_bytes =
7635 remote_escape_output (myaddr, new_todo_units, unit_size,
7636 (gdb_byte *) p, &units_written,
7637 payload_capacity_bytes);
7638 }
7639
7640 p += payload_length_bytes;
7641 if (use_length && units_written < todo_units)
7642 {
7643 /* Escape chars have filled up the buffer prematurely,
7644 and we have actually sent fewer units than planned.
7645 Fix-up the length field of the packet. Use the same
7646 number of characters as before. */
7647 plen += hexnumnstr (plen, (ULONGEST) units_written,
7648 plenlen);
7649 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7650 }
7651 }
7652 else
7653 {
7654 /* Normal mode: Send target system values byte by byte, in
7655 increasing byte addresses. Each byte is encoded as a two hex
7656 value. */
7657 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7658 units_written = todo_units;
7659 }
7660
7661 putpkt_binary (rs->buf, (int) (p - rs->buf));
7662 getpkt (&rs->buf, &rs->buf_size, 0);
7663
7664 if (rs->buf[0] == 'E')
7665 return TARGET_XFER_E_IO;
7666
7667 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7668 send fewer units than we'd planned. */
7669 *xfered_len_units = (ULONGEST) units_written;
7670 return TARGET_XFER_OK;
7671 }
7672
7673 /* Write memory data directly to the remote machine.
7674 This does not inform the data cache; the data cache uses this.
7675 MEMADDR is the address in the remote memory space.
7676 MYADDR is the address of the buffer in our space.
7677 LEN is the number of bytes.
7678
7679 Return the transferred status, error or OK (an
7680 'enum target_xfer_status' value). Save the number of bytes
7681 transferred in *XFERED_LEN. Only transfer a single packet. */
7682
7683 static enum target_xfer_status
7684 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7685 int unit_size, ULONGEST *xfered_len)
7686 {
7687 char *packet_format = 0;
7688
7689 /* Check whether the target supports binary download. */
7690 check_binary_download (memaddr);
7691
7692 switch (packet_support (PACKET_X))
7693 {
7694 case PACKET_ENABLE:
7695 packet_format = "X";
7696 break;
7697 case PACKET_DISABLE:
7698 packet_format = "M";
7699 break;
7700 case PACKET_SUPPORT_UNKNOWN:
7701 internal_error (__FILE__, __LINE__,
7702 _("remote_write_bytes: bad internal state"));
7703 default:
7704 internal_error (__FILE__, __LINE__, _("bad switch"));
7705 }
7706
7707 return remote_write_bytes_aux (packet_format,
7708 memaddr, myaddr, len, unit_size, xfered_len,
7709 packet_format[0], 1);
7710 }
7711
7712 /* Read memory data directly from the remote machine.
7713 This does not use the data cache; the data cache uses this.
7714 MEMADDR is the address in the remote memory space.
7715 MYADDR is the address of the buffer in our space.
7716 LEN_UNITS is the number of addressable memory units to read..
7717 UNIT_SIZE is the length in bytes of an addressable unit.
7718
7719 Return the transferred status, error or OK (an
7720 'enum target_xfer_status' value). Save the number of bytes
7721 transferred in *XFERED_LEN_UNITS.
7722
7723 See the comment of remote_write_bytes_aux for an example of
7724 memory read/write exchange between gdb and the stub. */
7725
7726 static enum target_xfer_status
7727 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7728 int unit_size, ULONGEST *xfered_len_units)
7729 {
7730 struct remote_state *rs = get_remote_state ();
7731 int buf_size_bytes; /* Max size of packet output buffer. */
7732 char *p;
7733 int todo_units;
7734 int decoded_bytes;
7735
7736 buf_size_bytes = get_memory_read_packet_size ();
7737 /* The packet buffer will be large enough for the payload;
7738 get_memory_packet_size ensures this. */
7739
7740 /* Number of units that will fit. */
7741 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7742
7743 /* Construct "m"<memaddr>","<len>". */
7744 memaddr = remote_address_masked (memaddr);
7745 p = rs->buf;
7746 *p++ = 'm';
7747 p += hexnumstr (p, (ULONGEST) memaddr);
7748 *p++ = ',';
7749 p += hexnumstr (p, (ULONGEST) todo_units);
7750 *p = '\0';
7751 putpkt (rs->buf);
7752 getpkt (&rs->buf, &rs->buf_size, 0);
7753 if (rs->buf[0] == 'E'
7754 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7755 && rs->buf[3] == '\0')
7756 return TARGET_XFER_E_IO;
7757 /* Reply describes memory byte by byte, each byte encoded as two hex
7758 characters. */
7759 p = rs->buf;
7760 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7761 /* Return what we have. Let higher layers handle partial reads. */
7762 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7763 return TARGET_XFER_OK;
7764 }
7765
7766 /* Using the set of read-only target sections of remote, read live
7767 read-only memory.
7768
7769 For interface/parameters/return description see target.h,
7770 to_xfer_partial. */
7771
7772 static enum target_xfer_status
7773 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7774 ULONGEST memaddr, ULONGEST len,
7775 int unit_size, ULONGEST *xfered_len)
7776 {
7777 struct target_section *secp;
7778 struct target_section_table *table;
7779
7780 secp = target_section_by_addr (ops, memaddr);
7781 if (secp != NULL
7782 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7783 secp->the_bfd_section)
7784 & SEC_READONLY))
7785 {
7786 struct target_section *p;
7787 ULONGEST memend = memaddr + len;
7788
7789 table = target_get_section_table (ops);
7790
7791 for (p = table->sections; p < table->sections_end; p++)
7792 {
7793 if (memaddr >= p->addr)
7794 {
7795 if (memend <= p->endaddr)
7796 {
7797 /* Entire transfer is within this section. */
7798 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7799 xfered_len);
7800 }
7801 else if (memaddr >= p->endaddr)
7802 {
7803 /* This section ends before the transfer starts. */
7804 continue;
7805 }
7806 else
7807 {
7808 /* This section overlaps the transfer. Just do half. */
7809 len = p->endaddr - memaddr;
7810 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7811 xfered_len);
7812 }
7813 }
7814 }
7815 }
7816
7817 return TARGET_XFER_EOF;
7818 }
7819
7820 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7821 first if the requested memory is unavailable in traceframe.
7822 Otherwise, fall back to remote_read_bytes_1. */
7823
7824 static enum target_xfer_status
7825 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7826 gdb_byte *myaddr, ULONGEST len, int unit_size,
7827 ULONGEST *xfered_len)
7828 {
7829 if (len == 0)
7830 return TARGET_XFER_EOF;
7831
7832 if (get_traceframe_number () != -1)
7833 {
7834 VEC(mem_range_s) *available;
7835
7836 /* If we fail to get the set of available memory, then the
7837 target does not support querying traceframe info, and so we
7838 attempt reading from the traceframe anyway (assuming the
7839 target implements the old QTro packet then). */
7840 if (traceframe_available_memory (&available, memaddr, len))
7841 {
7842 struct cleanup *old_chain;
7843
7844 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7845
7846 if (VEC_empty (mem_range_s, available)
7847 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7848 {
7849 enum target_xfer_status res;
7850
7851 /* Don't read into the traceframe's available
7852 memory. */
7853 if (!VEC_empty (mem_range_s, available))
7854 {
7855 LONGEST oldlen = len;
7856
7857 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7858 gdb_assert (len <= oldlen);
7859 }
7860
7861 do_cleanups (old_chain);
7862
7863 /* This goes through the topmost target again. */
7864 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7865 len, unit_size, xfered_len);
7866 if (res == TARGET_XFER_OK)
7867 return TARGET_XFER_OK;
7868 else
7869 {
7870 /* No use trying further, we know some memory starting
7871 at MEMADDR isn't available. */
7872 *xfered_len = len;
7873 return TARGET_XFER_UNAVAILABLE;
7874 }
7875 }
7876
7877 /* Don't try to read more than how much is available, in
7878 case the target implements the deprecated QTro packet to
7879 cater for older GDBs (the target's knowledge of read-only
7880 sections may be outdated by now). */
7881 len = VEC_index (mem_range_s, available, 0)->length;
7882
7883 do_cleanups (old_chain);
7884 }
7885 }
7886
7887 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7888 }
7889
7890 \f
7891
7892 /* Sends a packet with content determined by the printf format string
7893 FORMAT and the remaining arguments, then gets the reply. Returns
7894 whether the packet was a success, a failure, or unknown. */
7895
7896 static enum packet_result remote_send_printf (const char *format, ...)
7897 ATTRIBUTE_PRINTF (1, 2);
7898
7899 static enum packet_result
7900 remote_send_printf (const char *format, ...)
7901 {
7902 struct remote_state *rs = get_remote_state ();
7903 int max_size = get_remote_packet_size ();
7904 va_list ap;
7905
7906 va_start (ap, format);
7907
7908 rs->buf[0] = '\0';
7909 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7910 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7911
7912 if (putpkt (rs->buf) < 0)
7913 error (_("Communication problem with target."));
7914
7915 rs->buf[0] = '\0';
7916 getpkt (&rs->buf, &rs->buf_size, 0);
7917
7918 return packet_check_result (rs->buf);
7919 }
7920
7921 static void
7922 restore_remote_timeout (void *p)
7923 {
7924 int value = *(int *)p;
7925
7926 remote_timeout = value;
7927 }
7928
7929 /* Flash writing can take quite some time. We'll set
7930 effectively infinite timeout for flash operations.
7931 In future, we'll need to decide on a better approach. */
7932 static const int remote_flash_timeout = 1000;
7933
7934 static void
7935 remote_flash_erase (struct target_ops *ops,
7936 ULONGEST address, LONGEST length)
7937 {
7938 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7939 int saved_remote_timeout = remote_timeout;
7940 enum packet_result ret;
7941 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7942 &saved_remote_timeout);
7943
7944 remote_timeout = remote_flash_timeout;
7945
7946 ret = remote_send_printf ("vFlashErase:%s,%s",
7947 phex (address, addr_size),
7948 phex (length, 4));
7949 switch (ret)
7950 {
7951 case PACKET_UNKNOWN:
7952 error (_("Remote target does not support flash erase"));
7953 case PACKET_ERROR:
7954 error (_("Error erasing flash with vFlashErase packet"));
7955 default:
7956 break;
7957 }
7958
7959 do_cleanups (back_to);
7960 }
7961
7962 static enum target_xfer_status
7963 remote_flash_write (struct target_ops *ops, ULONGEST address,
7964 ULONGEST length, ULONGEST *xfered_len,
7965 const gdb_byte *data)
7966 {
7967 int saved_remote_timeout = remote_timeout;
7968 enum target_xfer_status ret;
7969 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7970 &saved_remote_timeout);
7971
7972 remote_timeout = remote_flash_timeout;
7973 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7974 xfered_len,'X', 0);
7975 do_cleanups (back_to);
7976
7977 return ret;
7978 }
7979
7980 static void
7981 remote_flash_done (struct target_ops *ops)
7982 {
7983 int saved_remote_timeout = remote_timeout;
7984 int ret;
7985 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7986 &saved_remote_timeout);
7987
7988 remote_timeout = remote_flash_timeout;
7989 ret = remote_send_printf ("vFlashDone");
7990 do_cleanups (back_to);
7991
7992 switch (ret)
7993 {
7994 case PACKET_UNKNOWN:
7995 error (_("Remote target does not support vFlashDone"));
7996 case PACKET_ERROR:
7997 error (_("Error finishing flash operation"));
7998 default:
7999 break;
8000 }
8001 }
8002
8003 static void
8004 remote_files_info (struct target_ops *ignore)
8005 {
8006 puts_filtered ("Debugging a target over a serial line.\n");
8007 }
8008 \f
8009 /* Stuff for dealing with the packets which are part of this protocol.
8010 See comment at top of file for details. */
8011
8012 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8013 error to higher layers. Called when a serial error is detected.
8014 The exception message is STRING, followed by a colon and a blank,
8015 the system error message for errno at function entry and final dot
8016 for output compatibility with throw_perror_with_name. */
8017
8018 static void
8019 unpush_and_perror (const char *string)
8020 {
8021 int saved_errno = errno;
8022
8023 remote_unpush_target ();
8024 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8025 safe_strerror (saved_errno));
8026 }
8027
8028 /* Read a single character from the remote end. */
8029
8030 static int
8031 readchar (int timeout)
8032 {
8033 int ch;
8034 struct remote_state *rs = get_remote_state ();
8035
8036 ch = serial_readchar (rs->remote_desc, timeout);
8037
8038 if (ch >= 0)
8039 return ch;
8040
8041 switch ((enum serial_rc) ch)
8042 {
8043 case SERIAL_EOF:
8044 remote_unpush_target ();
8045 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8046 /* no return */
8047 case SERIAL_ERROR:
8048 unpush_and_perror (_("Remote communication error. "
8049 "Target disconnected."));
8050 /* no return */
8051 case SERIAL_TIMEOUT:
8052 break;
8053 }
8054 return ch;
8055 }
8056
8057 /* Wrapper for serial_write that closes the target and throws if
8058 writing fails. */
8059
8060 static void
8061 remote_serial_write (const char *str, int len)
8062 {
8063 struct remote_state *rs = get_remote_state ();
8064
8065 if (serial_write (rs->remote_desc, str, len))
8066 {
8067 unpush_and_perror (_("Remote communication error. "
8068 "Target disconnected."));
8069 }
8070 }
8071
8072 /* Send the command in *BUF to the remote machine, and read the reply
8073 into *BUF. Report an error if we get an error reply. Resize
8074 *BUF using xrealloc if necessary to hold the result, and update
8075 *SIZEOF_BUF. */
8076
8077 static void
8078 remote_send (char **buf,
8079 long *sizeof_buf)
8080 {
8081 putpkt (*buf);
8082 getpkt (buf, sizeof_buf, 0);
8083
8084 if ((*buf)[0] == 'E')
8085 error (_("Remote failure reply: %s"), *buf);
8086 }
8087
8088 /* Return a pointer to an xmalloc'ed string representing an escaped
8089 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8090 etc. The caller is responsible for releasing the returned
8091 memory. */
8092
8093 static char *
8094 escape_buffer (const char *buf, int n)
8095 {
8096 struct cleanup *old_chain;
8097 struct ui_file *stb;
8098 char *str;
8099
8100 stb = mem_fileopen ();
8101 old_chain = make_cleanup_ui_file_delete (stb);
8102
8103 fputstrn_unfiltered (buf, n, '\\', stb);
8104 str = ui_file_xstrdup (stb, NULL);
8105 do_cleanups (old_chain);
8106 return str;
8107 }
8108
8109 /* Display a null-terminated packet on stdout, for debugging, using C
8110 string notation. */
8111
8112 static void
8113 print_packet (const char *buf)
8114 {
8115 puts_filtered ("\"");
8116 fputstr_filtered (buf, '"', gdb_stdout);
8117 puts_filtered ("\"");
8118 }
8119
8120 int
8121 putpkt (const char *buf)
8122 {
8123 return putpkt_binary (buf, strlen (buf));
8124 }
8125
8126 /* Send a packet to the remote machine, with error checking. The data
8127 of the packet is in BUF. The string in BUF can be at most
8128 get_remote_packet_size () - 5 to account for the $, # and checksum,
8129 and for a possible /0 if we are debugging (remote_debug) and want
8130 to print the sent packet as a string. */
8131
8132 static int
8133 putpkt_binary (const char *buf, int cnt)
8134 {
8135 struct remote_state *rs = get_remote_state ();
8136 int i;
8137 unsigned char csum = 0;
8138 char *buf2 = (char *) xmalloc (cnt + 6);
8139 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8140
8141 int ch;
8142 int tcount = 0;
8143 char *p;
8144 char *message;
8145
8146 /* Catch cases like trying to read memory or listing threads while
8147 we're waiting for a stop reply. The remote server wouldn't be
8148 ready to handle this request, so we'd hang and timeout. We don't
8149 have to worry about this in synchronous mode, because in that
8150 case it's not possible to issue a command while the target is
8151 running. This is not a problem in non-stop mode, because in that
8152 case, the stub is always ready to process serial input. */
8153 if (!target_is_non_stop_p ()
8154 && target_is_async_p ()
8155 && rs->waiting_for_stop_reply)
8156 {
8157 error (_("Cannot execute this command while the target is running.\n"
8158 "Use the \"interrupt\" command to stop the target\n"
8159 "and then try again."));
8160 }
8161
8162 /* We're sending out a new packet. Make sure we don't look at a
8163 stale cached response. */
8164 rs->cached_wait_status = 0;
8165
8166 /* Copy the packet into buffer BUF2, encapsulating it
8167 and giving it a checksum. */
8168
8169 p = buf2;
8170 *p++ = '$';
8171
8172 for (i = 0; i < cnt; i++)
8173 {
8174 csum += buf[i];
8175 *p++ = buf[i];
8176 }
8177 *p++ = '#';
8178 *p++ = tohex ((csum >> 4) & 0xf);
8179 *p++ = tohex (csum & 0xf);
8180
8181 /* Send it over and over until we get a positive ack. */
8182
8183 while (1)
8184 {
8185 int started_error_output = 0;
8186
8187 if (remote_debug)
8188 {
8189 struct cleanup *old_chain;
8190 char *str;
8191
8192 *p = '\0';
8193 str = escape_buffer (buf2, p - buf2);
8194 old_chain = make_cleanup (xfree, str);
8195 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8196 gdb_flush (gdb_stdlog);
8197 do_cleanups (old_chain);
8198 }
8199 remote_serial_write (buf2, p - buf2);
8200
8201 /* If this is a no acks version of the remote protocol, send the
8202 packet and move on. */
8203 if (rs->noack_mode)
8204 break;
8205
8206 /* Read until either a timeout occurs (-2) or '+' is read.
8207 Handle any notification that arrives in the mean time. */
8208 while (1)
8209 {
8210 ch = readchar (remote_timeout);
8211
8212 if (remote_debug)
8213 {
8214 switch (ch)
8215 {
8216 case '+':
8217 case '-':
8218 case SERIAL_TIMEOUT:
8219 case '$':
8220 case '%':
8221 if (started_error_output)
8222 {
8223 putchar_unfiltered ('\n');
8224 started_error_output = 0;
8225 }
8226 }
8227 }
8228
8229 switch (ch)
8230 {
8231 case '+':
8232 if (remote_debug)
8233 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8234 do_cleanups (old_chain);
8235 return 1;
8236 case '-':
8237 if (remote_debug)
8238 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8239 /* FALLTHROUGH */
8240 case SERIAL_TIMEOUT:
8241 tcount++;
8242 if (tcount > 3)
8243 {
8244 do_cleanups (old_chain);
8245 return 0;
8246 }
8247 break; /* Retransmit buffer. */
8248 case '$':
8249 {
8250 if (remote_debug)
8251 fprintf_unfiltered (gdb_stdlog,
8252 "Packet instead of Ack, ignoring it\n");
8253 /* It's probably an old response sent because an ACK
8254 was lost. Gobble up the packet and ack it so it
8255 doesn't get retransmitted when we resend this
8256 packet. */
8257 skip_frame ();
8258 remote_serial_write ("+", 1);
8259 continue; /* Now, go look for +. */
8260 }
8261
8262 case '%':
8263 {
8264 int val;
8265
8266 /* If we got a notification, handle it, and go back to looking
8267 for an ack. */
8268 /* We've found the start of a notification. Now
8269 collect the data. */
8270 val = read_frame (&rs->buf, &rs->buf_size);
8271 if (val >= 0)
8272 {
8273 if (remote_debug)
8274 {
8275 struct cleanup *old_chain;
8276 char *str;
8277
8278 str = escape_buffer (rs->buf, val);
8279 old_chain = make_cleanup (xfree, str);
8280 fprintf_unfiltered (gdb_stdlog,
8281 " Notification received: %s\n",
8282 str);
8283 do_cleanups (old_chain);
8284 }
8285 handle_notification (rs->notif_state, rs->buf);
8286 /* We're in sync now, rewait for the ack. */
8287 tcount = 0;
8288 }
8289 else
8290 {
8291 if (remote_debug)
8292 {
8293 if (!started_error_output)
8294 {
8295 started_error_output = 1;
8296 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8297 }
8298 fputc_unfiltered (ch & 0177, gdb_stdlog);
8299 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8300 }
8301 }
8302 continue;
8303 }
8304 /* fall-through */
8305 default:
8306 if (remote_debug)
8307 {
8308 if (!started_error_output)
8309 {
8310 started_error_output = 1;
8311 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8312 }
8313 fputc_unfiltered (ch & 0177, gdb_stdlog);
8314 }
8315 continue;
8316 }
8317 break; /* Here to retransmit. */
8318 }
8319
8320 #if 0
8321 /* This is wrong. If doing a long backtrace, the user should be
8322 able to get out next time we call QUIT, without anything as
8323 violent as interrupt_query. If we want to provide a way out of
8324 here without getting to the next QUIT, it should be based on
8325 hitting ^C twice as in remote_wait. */
8326 if (quit_flag)
8327 {
8328 quit_flag = 0;
8329 interrupt_query ();
8330 }
8331 #endif
8332 }
8333
8334 do_cleanups (old_chain);
8335 return 0;
8336 }
8337
8338 /* Come here after finding the start of a frame when we expected an
8339 ack. Do our best to discard the rest of this packet. */
8340
8341 static void
8342 skip_frame (void)
8343 {
8344 int c;
8345
8346 while (1)
8347 {
8348 c = readchar (remote_timeout);
8349 switch (c)
8350 {
8351 case SERIAL_TIMEOUT:
8352 /* Nothing we can do. */
8353 return;
8354 case '#':
8355 /* Discard the two bytes of checksum and stop. */
8356 c = readchar (remote_timeout);
8357 if (c >= 0)
8358 c = readchar (remote_timeout);
8359
8360 return;
8361 case '*': /* Run length encoding. */
8362 /* Discard the repeat count. */
8363 c = readchar (remote_timeout);
8364 if (c < 0)
8365 return;
8366 break;
8367 default:
8368 /* A regular character. */
8369 break;
8370 }
8371 }
8372 }
8373
8374 /* Come here after finding the start of the frame. Collect the rest
8375 into *BUF, verifying the checksum, length, and handling run-length
8376 compression. NUL terminate the buffer. If there is not enough room,
8377 expand *BUF using xrealloc.
8378
8379 Returns -1 on error, number of characters in buffer (ignoring the
8380 trailing NULL) on success. (could be extended to return one of the
8381 SERIAL status indications). */
8382
8383 static long
8384 read_frame (char **buf_p,
8385 long *sizeof_buf)
8386 {
8387 unsigned char csum;
8388 long bc;
8389 int c;
8390 char *buf = *buf_p;
8391 struct remote_state *rs = get_remote_state ();
8392
8393 csum = 0;
8394 bc = 0;
8395
8396 while (1)
8397 {
8398 c = readchar (remote_timeout);
8399 switch (c)
8400 {
8401 case SERIAL_TIMEOUT:
8402 if (remote_debug)
8403 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8404 return -1;
8405 case '$':
8406 if (remote_debug)
8407 fputs_filtered ("Saw new packet start in middle of old one\n",
8408 gdb_stdlog);
8409 return -1; /* Start a new packet, count retries. */
8410 case '#':
8411 {
8412 unsigned char pktcsum;
8413 int check_0 = 0;
8414 int check_1 = 0;
8415
8416 buf[bc] = '\0';
8417
8418 check_0 = readchar (remote_timeout);
8419 if (check_0 >= 0)
8420 check_1 = readchar (remote_timeout);
8421
8422 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8423 {
8424 if (remote_debug)
8425 fputs_filtered ("Timeout in checksum, retrying\n",
8426 gdb_stdlog);
8427 return -1;
8428 }
8429 else if (check_0 < 0 || check_1 < 0)
8430 {
8431 if (remote_debug)
8432 fputs_filtered ("Communication error in checksum\n",
8433 gdb_stdlog);
8434 return -1;
8435 }
8436
8437 /* Don't recompute the checksum; with no ack packets we
8438 don't have any way to indicate a packet retransmission
8439 is necessary. */
8440 if (rs->noack_mode)
8441 return bc;
8442
8443 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8444 if (csum == pktcsum)
8445 return bc;
8446
8447 if (remote_debug)
8448 {
8449 struct cleanup *old_chain;
8450 char *str;
8451
8452 str = escape_buffer (buf, bc);
8453 old_chain = make_cleanup (xfree, str);
8454 fprintf_unfiltered (gdb_stdlog,
8455 "Bad checksum, sentsum=0x%x, "
8456 "csum=0x%x, buf=%s\n",
8457 pktcsum, csum, str);
8458 do_cleanups (old_chain);
8459 }
8460 /* Number of characters in buffer ignoring trailing
8461 NULL. */
8462 return -1;
8463 }
8464 case '*': /* Run length encoding. */
8465 {
8466 int repeat;
8467
8468 csum += c;
8469 c = readchar (remote_timeout);
8470 csum += c;
8471 repeat = c - ' ' + 3; /* Compute repeat count. */
8472
8473 /* The character before ``*'' is repeated. */
8474
8475 if (repeat > 0 && repeat <= 255 && bc > 0)
8476 {
8477 if (bc + repeat - 1 >= *sizeof_buf - 1)
8478 {
8479 /* Make some more room in the buffer. */
8480 *sizeof_buf += repeat;
8481 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8482 buf = *buf_p;
8483 }
8484
8485 memset (&buf[bc], buf[bc - 1], repeat);
8486 bc += repeat;
8487 continue;
8488 }
8489
8490 buf[bc] = '\0';
8491 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8492 return -1;
8493 }
8494 default:
8495 if (bc >= *sizeof_buf - 1)
8496 {
8497 /* Make some more room in the buffer. */
8498 *sizeof_buf *= 2;
8499 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8500 buf = *buf_p;
8501 }
8502
8503 buf[bc++] = c;
8504 csum += c;
8505 continue;
8506 }
8507 }
8508 }
8509
8510 /* Read a packet from the remote machine, with error checking, and
8511 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8512 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8513 rather than timing out; this is used (in synchronous mode) to wait
8514 for a target that is is executing user code to stop. */
8515 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8516 don't have to change all the calls to getpkt to deal with the
8517 return value, because at the moment I don't know what the right
8518 thing to do it for those. */
8519 void
8520 getpkt (char **buf,
8521 long *sizeof_buf,
8522 int forever)
8523 {
8524 int timed_out;
8525
8526 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8527 }
8528
8529
8530 /* Read a packet from the remote machine, with error checking, and
8531 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8532 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8533 rather than timing out; this is used (in synchronous mode) to wait
8534 for a target that is is executing user code to stop. If FOREVER ==
8535 0, this function is allowed to time out gracefully and return an
8536 indication of this to the caller. Otherwise return the number of
8537 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8538 enough reason to return to the caller. *IS_NOTIF is an output
8539 boolean that indicates whether *BUF holds a notification or not
8540 (a regular packet). */
8541
8542 static int
8543 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8544 int expecting_notif, int *is_notif)
8545 {
8546 struct remote_state *rs = get_remote_state ();
8547 int c;
8548 int tries;
8549 int timeout;
8550 int val = -1;
8551
8552 /* We're reading a new response. Make sure we don't look at a
8553 previously cached response. */
8554 rs->cached_wait_status = 0;
8555
8556 strcpy (*buf, "timeout");
8557
8558 if (forever)
8559 timeout = watchdog > 0 ? watchdog : -1;
8560 else if (expecting_notif)
8561 timeout = 0; /* There should already be a char in the buffer. If
8562 not, bail out. */
8563 else
8564 timeout = remote_timeout;
8565
8566 #define MAX_TRIES 3
8567
8568 /* Process any number of notifications, and then return when
8569 we get a packet. */
8570 for (;;)
8571 {
8572 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8573 times. */
8574 for (tries = 1; tries <= MAX_TRIES; tries++)
8575 {
8576 /* This can loop forever if the remote side sends us
8577 characters continuously, but if it pauses, we'll get
8578 SERIAL_TIMEOUT from readchar because of timeout. Then
8579 we'll count that as a retry.
8580
8581 Note that even when forever is set, we will only wait
8582 forever prior to the start of a packet. After that, we
8583 expect characters to arrive at a brisk pace. They should
8584 show up within remote_timeout intervals. */
8585 do
8586 c = readchar (timeout);
8587 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8588
8589 if (c == SERIAL_TIMEOUT)
8590 {
8591 if (expecting_notif)
8592 return -1; /* Don't complain, it's normal to not get
8593 anything in this case. */
8594
8595 if (forever) /* Watchdog went off? Kill the target. */
8596 {
8597 QUIT;
8598 remote_unpush_target ();
8599 throw_error (TARGET_CLOSE_ERROR,
8600 _("Watchdog timeout has expired. "
8601 "Target detached."));
8602 }
8603 if (remote_debug)
8604 fputs_filtered ("Timed out.\n", gdb_stdlog);
8605 }
8606 else
8607 {
8608 /* We've found the start of a packet or notification.
8609 Now collect the data. */
8610 val = read_frame (buf, sizeof_buf);
8611 if (val >= 0)
8612 break;
8613 }
8614
8615 remote_serial_write ("-", 1);
8616 }
8617
8618 if (tries > MAX_TRIES)
8619 {
8620 /* We have tried hard enough, and just can't receive the
8621 packet/notification. Give up. */
8622 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8623
8624 /* Skip the ack char if we're in no-ack mode. */
8625 if (!rs->noack_mode)
8626 remote_serial_write ("+", 1);
8627 return -1;
8628 }
8629
8630 /* If we got an ordinary packet, return that to our caller. */
8631 if (c == '$')
8632 {
8633 if (remote_debug)
8634 {
8635 struct cleanup *old_chain;
8636 char *str;
8637
8638 str = escape_buffer (*buf, val);
8639 old_chain = make_cleanup (xfree, str);
8640 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8641 do_cleanups (old_chain);
8642 }
8643
8644 /* Skip the ack char if we're in no-ack mode. */
8645 if (!rs->noack_mode)
8646 remote_serial_write ("+", 1);
8647 if (is_notif != NULL)
8648 *is_notif = 0;
8649 return val;
8650 }
8651
8652 /* If we got a notification, handle it, and go back to looking
8653 for a packet. */
8654 else
8655 {
8656 gdb_assert (c == '%');
8657
8658 if (remote_debug)
8659 {
8660 struct cleanup *old_chain;
8661 char *str;
8662
8663 str = escape_buffer (*buf, val);
8664 old_chain = make_cleanup (xfree, str);
8665 fprintf_unfiltered (gdb_stdlog,
8666 " Notification received: %s\n",
8667 str);
8668 do_cleanups (old_chain);
8669 }
8670 if (is_notif != NULL)
8671 *is_notif = 1;
8672
8673 handle_notification (rs->notif_state, *buf);
8674
8675 /* Notifications require no acknowledgement. */
8676
8677 if (expecting_notif)
8678 return val;
8679 }
8680 }
8681 }
8682
8683 static int
8684 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8685 {
8686 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8687 }
8688
8689 static int
8690 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8691 int *is_notif)
8692 {
8693 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8694 is_notif);
8695 }
8696
8697 /* Check whether EVENT is a fork event for the process specified
8698 by the pid passed in DATA, and if it is, kill the fork child. */
8699
8700 static int
8701 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8702 QUEUE_ITER (stop_reply_p) *iter,
8703 stop_reply_p event,
8704 void *data)
8705 {
8706 struct queue_iter_param *param = (struct queue_iter_param *) data;
8707 int parent_pid = *(int *) param->input;
8708
8709 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8710 {
8711 struct remote_state *rs = get_remote_state ();
8712 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8713 int res;
8714
8715 res = remote_vkill (child_pid, rs);
8716 if (res != 0)
8717 error (_("Can't kill fork child process %d"), child_pid);
8718 }
8719
8720 return 1;
8721 }
8722
8723 /* Kill any new fork children of process PID that haven't been
8724 processed by follow_fork. */
8725
8726 static void
8727 kill_new_fork_children (int pid, struct remote_state *rs)
8728 {
8729 struct thread_info *thread;
8730 struct notif_client *notif = &notif_client_stop;
8731 struct queue_iter_param param;
8732
8733 /* Kill the fork child threads of any threads in process PID
8734 that are stopped at a fork event. */
8735 ALL_NON_EXITED_THREADS (thread)
8736 {
8737 struct target_waitstatus *ws = &thread->pending_follow;
8738
8739 if (is_pending_fork_parent (ws, pid, thread->ptid))
8740 {
8741 struct remote_state *rs = get_remote_state ();
8742 int child_pid = ptid_get_pid (ws->value.related_pid);
8743 int res;
8744
8745 res = remote_vkill (child_pid, rs);
8746 if (res != 0)
8747 error (_("Can't kill fork child process %d"), child_pid);
8748 }
8749 }
8750
8751 /* Check for any pending fork events (not reported or processed yet)
8752 in process PID and kill those fork child threads as well. */
8753 remote_notif_get_pending_events (notif);
8754 param.input = &pid;
8755 param.output = NULL;
8756 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8757 kill_child_of_pending_fork, &param);
8758 }
8759
8760 \f
8761 static void
8762 remote_kill (struct target_ops *ops)
8763 {
8764
8765 /* Catch errors so the user can quit from gdb even when we
8766 aren't on speaking terms with the remote system. */
8767 TRY
8768 {
8769 putpkt ("k");
8770 }
8771 CATCH (ex, RETURN_MASK_ERROR)
8772 {
8773 if (ex.error == TARGET_CLOSE_ERROR)
8774 {
8775 /* If we got an (EOF) error that caused the target
8776 to go away, then we're done, that's what we wanted.
8777 "k" is susceptible to cause a premature EOF, given
8778 that the remote server isn't actually required to
8779 reply to "k", and it can happen that it doesn't
8780 even get to reply ACK to the "k". */
8781 return;
8782 }
8783
8784 /* Otherwise, something went wrong. We didn't actually kill
8785 the target. Just propagate the exception, and let the
8786 user or higher layers decide what to do. */
8787 throw_exception (ex);
8788 }
8789 END_CATCH
8790
8791 /* We've killed the remote end, we get to mourn it. Since this is
8792 target remote, single-process, mourning the inferior also
8793 unpushes remote_ops. */
8794 target_mourn_inferior ();
8795 }
8796
8797 static int
8798 remote_vkill (int pid, struct remote_state *rs)
8799 {
8800 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8801 return -1;
8802
8803 /* Tell the remote target to detach. */
8804 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8805 putpkt (rs->buf);
8806 getpkt (&rs->buf, &rs->buf_size, 0);
8807
8808 switch (packet_ok (rs->buf,
8809 &remote_protocol_packets[PACKET_vKill]))
8810 {
8811 case PACKET_OK:
8812 return 0;
8813 case PACKET_ERROR:
8814 return 1;
8815 case PACKET_UNKNOWN:
8816 return -1;
8817 default:
8818 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8819 }
8820 }
8821
8822 static void
8823 extended_remote_kill (struct target_ops *ops)
8824 {
8825 int res;
8826 int pid = ptid_get_pid (inferior_ptid);
8827 struct remote_state *rs = get_remote_state ();
8828
8829 /* If we're stopped while forking and we haven't followed yet, kill the
8830 child task. We need to do this before killing the parent task
8831 because if this is a vfork then the parent will be sleeping. */
8832 kill_new_fork_children (pid, rs);
8833
8834 res = remote_vkill (pid, rs);
8835 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8836 {
8837 /* Don't try 'k' on a multi-process aware stub -- it has no way
8838 to specify the pid. */
8839
8840 putpkt ("k");
8841 #if 0
8842 getpkt (&rs->buf, &rs->buf_size, 0);
8843 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8844 res = 1;
8845 #else
8846 /* Don't wait for it to die. I'm not really sure it matters whether
8847 we do or not. For the existing stubs, kill is a noop. */
8848 res = 0;
8849 #endif
8850 }
8851
8852 if (res != 0)
8853 error (_("Can't kill process"));
8854
8855 target_mourn_inferior ();
8856 }
8857
8858 static void
8859 remote_mourn (struct target_ops *target)
8860 {
8861 unpush_target (target);
8862
8863 /* remote_close takes care of doing most of the clean up. */
8864 generic_mourn_inferior ();
8865 }
8866
8867 static void
8868 extended_remote_mourn (struct target_ops *target)
8869 {
8870 struct remote_state *rs = get_remote_state ();
8871
8872 /* In case we got here due to an error, but we're going to stay
8873 connected. */
8874 rs->waiting_for_stop_reply = 0;
8875
8876 /* If the current general thread belonged to the process we just
8877 detached from or has exited, the remote side current general
8878 thread becomes undefined. Considering a case like this:
8879
8880 - We just got here due to a detach.
8881 - The process that we're detaching from happens to immediately
8882 report a global breakpoint being hit in non-stop mode, in the
8883 same thread we had selected before.
8884 - GDB attaches to this process again.
8885 - This event happens to be the next event we handle.
8886
8887 GDB would consider that the current general thread didn't need to
8888 be set on the stub side (with Hg), since for all it knew,
8889 GENERAL_THREAD hadn't changed.
8890
8891 Notice that although in all-stop mode, the remote server always
8892 sets the current thread to the thread reporting the stop event,
8893 that doesn't happen in non-stop mode; in non-stop, the stub *must
8894 not* change the current thread when reporting a breakpoint hit,
8895 due to the decoupling of event reporting and event handling.
8896
8897 To keep things simple, we always invalidate our notion of the
8898 current thread. */
8899 record_currthread (rs, minus_one_ptid);
8900
8901 /* Unlike "target remote", we do not want to unpush the target; then
8902 the next time the user says "run", we won't be connected. */
8903
8904 /* Call common code to mark the inferior as not running. */
8905 generic_mourn_inferior ();
8906
8907 if (!have_inferiors ())
8908 {
8909 if (!remote_multi_process_p (rs))
8910 {
8911 /* Check whether the target is running now - some remote stubs
8912 automatically restart after kill. */
8913 putpkt ("?");
8914 getpkt (&rs->buf, &rs->buf_size, 0);
8915
8916 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8917 {
8918 /* Assume that the target has been restarted. Set
8919 inferior_ptid so that bits of core GDB realizes
8920 there's something here, e.g., so that the user can
8921 say "kill" again. */
8922 inferior_ptid = magic_null_ptid;
8923 }
8924 }
8925 }
8926 }
8927
8928 static int
8929 extended_remote_supports_disable_randomization (struct target_ops *self)
8930 {
8931 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8932 }
8933
8934 static void
8935 extended_remote_disable_randomization (int val)
8936 {
8937 struct remote_state *rs = get_remote_state ();
8938 char *reply;
8939
8940 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8941 val);
8942 putpkt (rs->buf);
8943 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8944 if (*reply == '\0')
8945 error (_("Target does not support QDisableRandomization."));
8946 if (strcmp (reply, "OK") != 0)
8947 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8948 }
8949
8950 static int
8951 extended_remote_run (char *args)
8952 {
8953 struct remote_state *rs = get_remote_state ();
8954 int len;
8955 const char *remote_exec_file = get_remote_exec_file ();
8956
8957 /* If the user has disabled vRun support, or we have detected that
8958 support is not available, do not try it. */
8959 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8960 return -1;
8961
8962 strcpy (rs->buf, "vRun;");
8963 len = strlen (rs->buf);
8964
8965 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8966 error (_("Remote file name too long for run packet"));
8967 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8968 strlen (remote_exec_file));
8969
8970 gdb_assert (args != NULL);
8971 if (*args)
8972 {
8973 struct cleanup *back_to;
8974 int i;
8975 char **argv;
8976
8977 argv = gdb_buildargv (args);
8978 back_to = make_cleanup_freeargv (argv);
8979 for (i = 0; argv[i] != NULL; i++)
8980 {
8981 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8982 error (_("Argument list too long for run packet"));
8983 rs->buf[len++] = ';';
8984 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8985 strlen (argv[i]));
8986 }
8987 do_cleanups (back_to);
8988 }
8989
8990 rs->buf[len++] = '\0';
8991
8992 putpkt (rs->buf);
8993 getpkt (&rs->buf, &rs->buf_size, 0);
8994
8995 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8996 {
8997 case PACKET_OK:
8998 /* We have a wait response. All is well. */
8999 return 0;
9000 case PACKET_UNKNOWN:
9001 return -1;
9002 case PACKET_ERROR:
9003 if (remote_exec_file[0] == '\0')
9004 error (_("Running the default executable on the remote target failed; "
9005 "try \"set remote exec-file\"?"));
9006 else
9007 error (_("Running \"%s\" on the remote target failed"),
9008 remote_exec_file);
9009 default:
9010 gdb_assert_not_reached (_("bad switch"));
9011 }
9012 }
9013
9014 /* In the extended protocol we want to be able to do things like
9015 "run" and have them basically work as expected. So we need
9016 a special create_inferior function. We support changing the
9017 executable file and the command line arguments, but not the
9018 environment. */
9019
9020 static void
9021 extended_remote_create_inferior (struct target_ops *ops,
9022 char *exec_file, char *args,
9023 char **env, int from_tty)
9024 {
9025 int run_worked;
9026 char *stop_reply;
9027 struct remote_state *rs = get_remote_state ();
9028 const char *remote_exec_file = get_remote_exec_file ();
9029
9030 /* If running asynchronously, register the target file descriptor
9031 with the event loop. */
9032 if (target_can_async_p ())
9033 target_async (1);
9034
9035 /* Disable address space randomization if requested (and supported). */
9036 if (extended_remote_supports_disable_randomization (ops))
9037 extended_remote_disable_randomization (disable_randomization);
9038
9039 /* Now restart the remote server. */
9040 run_worked = extended_remote_run (args) != -1;
9041 if (!run_worked)
9042 {
9043 /* vRun was not supported. Fail if we need it to do what the
9044 user requested. */
9045 if (remote_exec_file[0])
9046 error (_("Remote target does not support \"set remote exec-file\""));
9047 if (args[0])
9048 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9049
9050 /* Fall back to "R". */
9051 extended_remote_restart ();
9052 }
9053
9054 if (!have_inferiors ())
9055 {
9056 /* Clean up from the last time we ran, before we mark the target
9057 running again. This will mark breakpoints uninserted, and
9058 get_offsets may insert breakpoints. */
9059 init_thread_list ();
9060 init_wait_for_inferior ();
9061 }
9062
9063 /* vRun's success return is a stop reply. */
9064 stop_reply = run_worked ? rs->buf : NULL;
9065 add_current_inferior_and_thread (stop_reply);
9066
9067 /* Get updated offsets, if the stub uses qOffsets. */
9068 get_offsets ();
9069 }
9070 \f
9071
9072 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9073 the list of conditions (in agent expression bytecode format), if any, the
9074 target needs to evaluate. The output is placed into the packet buffer
9075 started from BUF and ended at BUF_END. */
9076
9077 static int
9078 remote_add_target_side_condition (struct gdbarch *gdbarch,
9079 struct bp_target_info *bp_tgt, char *buf,
9080 char *buf_end)
9081 {
9082 struct agent_expr *aexpr = NULL;
9083 int i, ix;
9084 char *pkt;
9085 char *buf_start = buf;
9086
9087 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9088 return 0;
9089
9090 buf += strlen (buf);
9091 xsnprintf (buf, buf_end - buf, "%s", ";");
9092 buf++;
9093
9094 /* Send conditions to the target and free the vector. */
9095 for (ix = 0;
9096 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9097 ix++)
9098 {
9099 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9100 buf += strlen (buf);
9101 for (i = 0; i < aexpr->len; ++i)
9102 buf = pack_hex_byte (buf, aexpr->buf[i]);
9103 *buf = '\0';
9104 }
9105 return 0;
9106 }
9107
9108 static void
9109 remote_add_target_side_commands (struct gdbarch *gdbarch,
9110 struct bp_target_info *bp_tgt, char *buf)
9111 {
9112 struct agent_expr *aexpr = NULL;
9113 int i, ix;
9114
9115 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9116 return;
9117
9118 buf += strlen (buf);
9119
9120 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9121 buf += strlen (buf);
9122
9123 /* Concatenate all the agent expressions that are commands into the
9124 cmds parameter. */
9125 for (ix = 0;
9126 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9127 ix++)
9128 {
9129 sprintf (buf, "X%x,", aexpr->len);
9130 buf += strlen (buf);
9131 for (i = 0; i < aexpr->len; ++i)
9132 buf = pack_hex_byte (buf, aexpr->buf[i]);
9133 *buf = '\0';
9134 }
9135 }
9136
9137 /* Insert a breakpoint. On targets that have software breakpoint
9138 support, we ask the remote target to do the work; on targets
9139 which don't, we insert a traditional memory breakpoint. */
9140
9141 static int
9142 remote_insert_breakpoint (struct target_ops *ops,
9143 struct gdbarch *gdbarch,
9144 struct bp_target_info *bp_tgt)
9145 {
9146 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9147 If it succeeds, then set the support to PACKET_ENABLE. If it
9148 fails, and the user has explicitly requested the Z support then
9149 report an error, otherwise, mark it disabled and go on. */
9150
9151 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9152 {
9153 CORE_ADDR addr = bp_tgt->reqstd_address;
9154 struct remote_state *rs;
9155 char *p, *endbuf;
9156 int bpsize;
9157 struct condition_list *cond = NULL;
9158
9159 /* Make sure the remote is pointing at the right process, if
9160 necessary. */
9161 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9162 set_general_process ();
9163
9164 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9165
9166 rs = get_remote_state ();
9167 p = rs->buf;
9168 endbuf = rs->buf + get_remote_packet_size ();
9169
9170 *(p++) = 'Z';
9171 *(p++) = '0';
9172 *(p++) = ',';
9173 addr = (ULONGEST) remote_address_masked (addr);
9174 p += hexnumstr (p, addr);
9175 xsnprintf (p, endbuf - p, ",%d", bpsize);
9176
9177 if (remote_supports_cond_breakpoints (ops))
9178 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9179
9180 if (remote_can_run_breakpoint_commands (ops))
9181 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9182
9183 putpkt (rs->buf);
9184 getpkt (&rs->buf, &rs->buf_size, 0);
9185
9186 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9187 {
9188 case PACKET_ERROR:
9189 return -1;
9190 case PACKET_OK:
9191 bp_tgt->placed_address = addr;
9192 bp_tgt->placed_size = bpsize;
9193 return 0;
9194 case PACKET_UNKNOWN:
9195 break;
9196 }
9197 }
9198
9199 /* If this breakpoint has target-side commands but this stub doesn't
9200 support Z0 packets, throw error. */
9201 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9202 throw_error (NOT_SUPPORTED_ERROR, _("\
9203 Target doesn't support breakpoints that have target side commands."));
9204
9205 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9206 }
9207
9208 static int
9209 remote_remove_breakpoint (struct target_ops *ops,
9210 struct gdbarch *gdbarch,
9211 struct bp_target_info *bp_tgt)
9212 {
9213 CORE_ADDR addr = bp_tgt->placed_address;
9214 struct remote_state *rs = get_remote_state ();
9215
9216 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9217 {
9218 char *p = rs->buf;
9219 char *endbuf = rs->buf + get_remote_packet_size ();
9220
9221 /* Make sure the remote is pointing at the right process, if
9222 necessary. */
9223 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9224 set_general_process ();
9225
9226 *(p++) = 'z';
9227 *(p++) = '0';
9228 *(p++) = ',';
9229
9230 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9231 p += hexnumstr (p, addr);
9232 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9233
9234 putpkt (rs->buf);
9235 getpkt (&rs->buf, &rs->buf_size, 0);
9236
9237 return (rs->buf[0] == 'E');
9238 }
9239
9240 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9241 }
9242
9243 static enum Z_packet_type
9244 watchpoint_to_Z_packet (int type)
9245 {
9246 switch (type)
9247 {
9248 case hw_write:
9249 return Z_PACKET_WRITE_WP;
9250 break;
9251 case hw_read:
9252 return Z_PACKET_READ_WP;
9253 break;
9254 case hw_access:
9255 return Z_PACKET_ACCESS_WP;
9256 break;
9257 default:
9258 internal_error (__FILE__, __LINE__,
9259 _("hw_bp_to_z: bad watchpoint type %d"), type);
9260 }
9261 }
9262
9263 static int
9264 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9265 enum target_hw_bp_type type, struct expression *cond)
9266 {
9267 struct remote_state *rs = get_remote_state ();
9268 char *endbuf = rs->buf + get_remote_packet_size ();
9269 char *p;
9270 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9271
9272 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9273 return 1;
9274
9275 /* Make sure the remote is pointing at the right process, if
9276 necessary. */
9277 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9278 set_general_process ();
9279
9280 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9281 p = strchr (rs->buf, '\0');
9282 addr = remote_address_masked (addr);
9283 p += hexnumstr (p, (ULONGEST) addr);
9284 xsnprintf (p, endbuf - p, ",%x", len);
9285
9286 putpkt (rs->buf);
9287 getpkt (&rs->buf, &rs->buf_size, 0);
9288
9289 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9290 {
9291 case PACKET_ERROR:
9292 return -1;
9293 case PACKET_UNKNOWN:
9294 return 1;
9295 case PACKET_OK:
9296 return 0;
9297 }
9298 internal_error (__FILE__, __LINE__,
9299 _("remote_insert_watchpoint: reached end of function"));
9300 }
9301
9302 static int
9303 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9304 CORE_ADDR start, int length)
9305 {
9306 CORE_ADDR diff = remote_address_masked (addr - start);
9307
9308 return diff < length;
9309 }
9310
9311
9312 static int
9313 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9314 enum target_hw_bp_type type, struct expression *cond)
9315 {
9316 struct remote_state *rs = get_remote_state ();
9317 char *endbuf = rs->buf + get_remote_packet_size ();
9318 char *p;
9319 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9320
9321 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9322 return -1;
9323
9324 /* Make sure the remote is pointing at the right process, if
9325 necessary. */
9326 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9327 set_general_process ();
9328
9329 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9330 p = strchr (rs->buf, '\0');
9331 addr = remote_address_masked (addr);
9332 p += hexnumstr (p, (ULONGEST) addr);
9333 xsnprintf (p, endbuf - p, ",%x", len);
9334 putpkt (rs->buf);
9335 getpkt (&rs->buf, &rs->buf_size, 0);
9336
9337 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9338 {
9339 case PACKET_ERROR:
9340 case PACKET_UNKNOWN:
9341 return -1;
9342 case PACKET_OK:
9343 return 0;
9344 }
9345 internal_error (__FILE__, __LINE__,
9346 _("remote_remove_watchpoint: reached end of function"));
9347 }
9348
9349
9350 int remote_hw_watchpoint_limit = -1;
9351 int remote_hw_watchpoint_length_limit = -1;
9352 int remote_hw_breakpoint_limit = -1;
9353
9354 static int
9355 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9356 CORE_ADDR addr, int len)
9357 {
9358 if (remote_hw_watchpoint_length_limit == 0)
9359 return 0;
9360 else if (remote_hw_watchpoint_length_limit < 0)
9361 return 1;
9362 else if (len <= remote_hw_watchpoint_length_limit)
9363 return 1;
9364 else
9365 return 0;
9366 }
9367
9368 static int
9369 remote_check_watch_resources (struct target_ops *self,
9370 enum bptype type, int cnt, int ot)
9371 {
9372 if (type == bp_hardware_breakpoint)
9373 {
9374 if (remote_hw_breakpoint_limit == 0)
9375 return 0;
9376 else if (remote_hw_breakpoint_limit < 0)
9377 return 1;
9378 else if (cnt <= remote_hw_breakpoint_limit)
9379 return 1;
9380 }
9381 else
9382 {
9383 if (remote_hw_watchpoint_limit == 0)
9384 return 0;
9385 else if (remote_hw_watchpoint_limit < 0)
9386 return 1;
9387 else if (ot)
9388 return -1;
9389 else if (cnt <= remote_hw_watchpoint_limit)
9390 return 1;
9391 }
9392 return -1;
9393 }
9394
9395 /* The to_stopped_by_sw_breakpoint method of target remote. */
9396
9397 static int
9398 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9399 {
9400 struct thread_info *thread = inferior_thread ();
9401
9402 return (thread->priv != NULL
9403 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9404 }
9405
9406 /* The to_supports_stopped_by_sw_breakpoint method of target
9407 remote. */
9408
9409 static int
9410 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9411 {
9412 struct remote_state *rs = get_remote_state ();
9413
9414 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9415 }
9416
9417 /* The to_stopped_by_hw_breakpoint method of target remote. */
9418
9419 static int
9420 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9421 {
9422 struct thread_info *thread = inferior_thread ();
9423
9424 return (thread->priv != NULL
9425 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9426 }
9427
9428 /* The to_supports_stopped_by_hw_breakpoint method of target
9429 remote. */
9430
9431 static int
9432 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9433 {
9434 struct remote_state *rs = get_remote_state ();
9435
9436 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9437 }
9438
9439 static int
9440 remote_stopped_by_watchpoint (struct target_ops *ops)
9441 {
9442 struct thread_info *thread = inferior_thread ();
9443
9444 return (thread->priv != NULL
9445 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9446 }
9447
9448 static int
9449 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9450 {
9451 struct thread_info *thread = inferior_thread ();
9452
9453 if (thread->priv != NULL
9454 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9455 {
9456 *addr_p = thread->priv->watch_data_address;
9457 return 1;
9458 }
9459
9460 return 0;
9461 }
9462
9463
9464 static int
9465 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9466 struct bp_target_info *bp_tgt)
9467 {
9468 CORE_ADDR addr = bp_tgt->reqstd_address;
9469 struct remote_state *rs;
9470 char *p, *endbuf;
9471 char *message;
9472 int bpsize;
9473
9474 /* The length field should be set to the size of a breakpoint
9475 instruction, even though we aren't inserting one ourselves. */
9476
9477 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9478
9479 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9480 return -1;
9481
9482 /* Make sure the remote is pointing at the right process, if
9483 necessary. */
9484 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9485 set_general_process ();
9486
9487 rs = get_remote_state ();
9488 p = rs->buf;
9489 endbuf = rs->buf + get_remote_packet_size ();
9490
9491 *(p++) = 'Z';
9492 *(p++) = '1';
9493 *(p++) = ',';
9494
9495 addr = remote_address_masked (addr);
9496 p += hexnumstr (p, (ULONGEST) addr);
9497 xsnprintf (p, endbuf - p, ",%x", bpsize);
9498
9499 if (remote_supports_cond_breakpoints (self))
9500 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9501
9502 if (remote_can_run_breakpoint_commands (self))
9503 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9504
9505 putpkt (rs->buf);
9506 getpkt (&rs->buf, &rs->buf_size, 0);
9507
9508 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9509 {
9510 case PACKET_ERROR:
9511 if (rs->buf[1] == '.')
9512 {
9513 message = strchr (rs->buf + 2, '.');
9514 if (message)
9515 error (_("Remote failure reply: %s"), message + 1);
9516 }
9517 return -1;
9518 case PACKET_UNKNOWN:
9519 return -1;
9520 case PACKET_OK:
9521 bp_tgt->placed_address = addr;
9522 bp_tgt->placed_size = bpsize;
9523 return 0;
9524 }
9525 internal_error (__FILE__, __LINE__,
9526 _("remote_insert_hw_breakpoint: reached end of function"));
9527 }
9528
9529
9530 static int
9531 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9532 struct bp_target_info *bp_tgt)
9533 {
9534 CORE_ADDR addr;
9535 struct remote_state *rs = get_remote_state ();
9536 char *p = rs->buf;
9537 char *endbuf = rs->buf + get_remote_packet_size ();
9538
9539 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9540 return -1;
9541
9542 /* Make sure the remote is pointing at the right process, if
9543 necessary. */
9544 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9545 set_general_process ();
9546
9547 *(p++) = 'z';
9548 *(p++) = '1';
9549 *(p++) = ',';
9550
9551 addr = remote_address_masked (bp_tgt->placed_address);
9552 p += hexnumstr (p, (ULONGEST) addr);
9553 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9554
9555 putpkt (rs->buf);
9556 getpkt (&rs->buf, &rs->buf_size, 0);
9557
9558 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9559 {
9560 case PACKET_ERROR:
9561 case PACKET_UNKNOWN:
9562 return -1;
9563 case PACKET_OK:
9564 return 0;
9565 }
9566 internal_error (__FILE__, __LINE__,
9567 _("remote_remove_hw_breakpoint: reached end of function"));
9568 }
9569
9570 /* Verify memory using the "qCRC:" request. */
9571
9572 static int
9573 remote_verify_memory (struct target_ops *ops,
9574 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9575 {
9576 struct remote_state *rs = get_remote_state ();
9577 unsigned long host_crc, target_crc;
9578 char *tmp;
9579
9580 /* It doesn't make sense to use qCRC if the remote target is
9581 connected but not running. */
9582 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9583 {
9584 enum packet_result result;
9585
9586 /* Make sure the remote is pointing at the right process. */
9587 set_general_process ();
9588
9589 /* FIXME: assumes lma can fit into long. */
9590 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9591 (long) lma, (long) size);
9592 putpkt (rs->buf);
9593
9594 /* Be clever; compute the host_crc before waiting for target
9595 reply. */
9596 host_crc = xcrc32 (data, size, 0xffffffff);
9597
9598 getpkt (&rs->buf, &rs->buf_size, 0);
9599
9600 result = packet_ok (rs->buf,
9601 &remote_protocol_packets[PACKET_qCRC]);
9602 if (result == PACKET_ERROR)
9603 return -1;
9604 else if (result == PACKET_OK)
9605 {
9606 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9607 target_crc = target_crc * 16 + fromhex (*tmp);
9608
9609 return (host_crc == target_crc);
9610 }
9611 }
9612
9613 return simple_verify_memory (ops, data, lma, size);
9614 }
9615
9616 /* compare-sections command
9617
9618 With no arguments, compares each loadable section in the exec bfd
9619 with the same memory range on the target, and reports mismatches.
9620 Useful for verifying the image on the target against the exec file. */
9621
9622 static void
9623 compare_sections_command (char *args, int from_tty)
9624 {
9625 asection *s;
9626 struct cleanup *old_chain;
9627 gdb_byte *sectdata;
9628 const char *sectname;
9629 bfd_size_type size;
9630 bfd_vma lma;
9631 int matched = 0;
9632 int mismatched = 0;
9633 int res;
9634 int read_only = 0;
9635
9636 if (!exec_bfd)
9637 error (_("command cannot be used without an exec file"));
9638
9639 /* Make sure the remote is pointing at the right process. */
9640 set_general_process ();
9641
9642 if (args != NULL && strcmp (args, "-r") == 0)
9643 {
9644 read_only = 1;
9645 args = NULL;
9646 }
9647
9648 for (s = exec_bfd->sections; s; s = s->next)
9649 {
9650 if (!(s->flags & SEC_LOAD))
9651 continue; /* Skip non-loadable section. */
9652
9653 if (read_only && (s->flags & SEC_READONLY) == 0)
9654 continue; /* Skip writeable sections */
9655
9656 size = bfd_get_section_size (s);
9657 if (size == 0)
9658 continue; /* Skip zero-length section. */
9659
9660 sectname = bfd_get_section_name (exec_bfd, s);
9661 if (args && strcmp (args, sectname) != 0)
9662 continue; /* Not the section selected by user. */
9663
9664 matched = 1; /* Do this section. */
9665 lma = s->lma;
9666
9667 sectdata = (gdb_byte *) xmalloc (size);
9668 old_chain = make_cleanup (xfree, sectdata);
9669 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9670
9671 res = target_verify_memory (sectdata, lma, size);
9672
9673 if (res == -1)
9674 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9675 paddress (target_gdbarch (), lma),
9676 paddress (target_gdbarch (), lma + size));
9677
9678 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9679 paddress (target_gdbarch (), lma),
9680 paddress (target_gdbarch (), lma + size));
9681 if (res)
9682 printf_filtered ("matched.\n");
9683 else
9684 {
9685 printf_filtered ("MIS-MATCHED!\n");
9686 mismatched++;
9687 }
9688
9689 do_cleanups (old_chain);
9690 }
9691 if (mismatched > 0)
9692 warning (_("One or more sections of the target image does not match\n\
9693 the loaded file\n"));
9694 if (args && !matched)
9695 printf_filtered (_("No loaded section named '%s'.\n"), args);
9696 }
9697
9698 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9699 into remote target. The number of bytes written to the remote
9700 target is returned, or -1 for error. */
9701
9702 static enum target_xfer_status
9703 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9704 const char *annex, const gdb_byte *writebuf,
9705 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9706 struct packet_config *packet)
9707 {
9708 int i, buf_len;
9709 ULONGEST n;
9710 struct remote_state *rs = get_remote_state ();
9711 int max_size = get_memory_write_packet_size ();
9712
9713 if (packet->support == PACKET_DISABLE)
9714 return TARGET_XFER_E_IO;
9715
9716 /* Insert header. */
9717 i = snprintf (rs->buf, max_size,
9718 "qXfer:%s:write:%s:%s:",
9719 object_name, annex ? annex : "",
9720 phex_nz (offset, sizeof offset));
9721 max_size -= (i + 1);
9722
9723 /* Escape as much data as fits into rs->buf. */
9724 buf_len = remote_escape_output
9725 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9726
9727 if (putpkt_binary (rs->buf, i + buf_len) < 0
9728 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9729 || packet_ok (rs->buf, packet) != PACKET_OK)
9730 return TARGET_XFER_E_IO;
9731
9732 unpack_varlen_hex (rs->buf, &n);
9733
9734 *xfered_len = n;
9735 return TARGET_XFER_OK;
9736 }
9737
9738 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9739 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9740 number of bytes read is returned, or 0 for EOF, or -1 for error.
9741 The number of bytes read may be less than LEN without indicating an
9742 EOF. PACKET is checked and updated to indicate whether the remote
9743 target supports this object. */
9744
9745 static enum target_xfer_status
9746 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9747 const char *annex,
9748 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9749 ULONGEST *xfered_len,
9750 struct packet_config *packet)
9751 {
9752 struct remote_state *rs = get_remote_state ();
9753 LONGEST i, n, packet_len;
9754
9755 if (packet->support == PACKET_DISABLE)
9756 return TARGET_XFER_E_IO;
9757
9758 /* Check whether we've cached an end-of-object packet that matches
9759 this request. */
9760 if (rs->finished_object)
9761 {
9762 if (strcmp (object_name, rs->finished_object) == 0
9763 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9764 && offset == rs->finished_offset)
9765 return TARGET_XFER_EOF;
9766
9767
9768 /* Otherwise, we're now reading something different. Discard
9769 the cache. */
9770 xfree (rs->finished_object);
9771 xfree (rs->finished_annex);
9772 rs->finished_object = NULL;
9773 rs->finished_annex = NULL;
9774 }
9775
9776 /* Request only enough to fit in a single packet. The actual data
9777 may not, since we don't know how much of it will need to be escaped;
9778 the target is free to respond with slightly less data. We subtract
9779 five to account for the response type and the protocol frame. */
9780 n = min (get_remote_packet_size () - 5, len);
9781 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9782 object_name, annex ? annex : "",
9783 phex_nz (offset, sizeof offset),
9784 phex_nz (n, sizeof n));
9785 i = putpkt (rs->buf);
9786 if (i < 0)
9787 return TARGET_XFER_E_IO;
9788
9789 rs->buf[0] = '\0';
9790 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9791 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9792 return TARGET_XFER_E_IO;
9793
9794 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9795 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9796
9797 /* 'm' means there is (or at least might be) more data after this
9798 batch. That does not make sense unless there's at least one byte
9799 of data in this reply. */
9800 if (rs->buf[0] == 'm' && packet_len == 1)
9801 error (_("Remote qXfer reply contained no data."));
9802
9803 /* Got some data. */
9804 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9805 packet_len - 1, readbuf, n);
9806
9807 /* 'l' is an EOF marker, possibly including a final block of data,
9808 or possibly empty. If we have the final block of a non-empty
9809 object, record this fact to bypass a subsequent partial read. */
9810 if (rs->buf[0] == 'l' && offset + i > 0)
9811 {
9812 rs->finished_object = xstrdup (object_name);
9813 rs->finished_annex = xstrdup (annex ? annex : "");
9814 rs->finished_offset = offset + i;
9815 }
9816
9817 if (i == 0)
9818 return TARGET_XFER_EOF;
9819 else
9820 {
9821 *xfered_len = i;
9822 return TARGET_XFER_OK;
9823 }
9824 }
9825
9826 static enum target_xfer_status
9827 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9828 const char *annex, gdb_byte *readbuf,
9829 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9830 ULONGEST *xfered_len)
9831 {
9832 struct remote_state *rs;
9833 int i;
9834 char *p2;
9835 char query_type;
9836 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9837
9838 set_remote_traceframe ();
9839 set_general_thread (inferior_ptid);
9840
9841 rs = get_remote_state ();
9842
9843 /* Handle memory using the standard memory routines. */
9844 if (object == TARGET_OBJECT_MEMORY)
9845 {
9846 /* If the remote target is connected but not running, we should
9847 pass this request down to a lower stratum (e.g. the executable
9848 file). */
9849 if (!target_has_execution)
9850 return TARGET_XFER_EOF;
9851
9852 if (writebuf != NULL)
9853 return remote_write_bytes (offset, writebuf, len, unit_size,
9854 xfered_len);
9855 else
9856 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9857 xfered_len);
9858 }
9859
9860 /* Handle SPU memory using qxfer packets. */
9861 if (object == TARGET_OBJECT_SPU)
9862 {
9863 if (readbuf)
9864 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9865 xfered_len, &remote_protocol_packets
9866 [PACKET_qXfer_spu_read]);
9867 else
9868 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9869 xfered_len, &remote_protocol_packets
9870 [PACKET_qXfer_spu_write]);
9871 }
9872
9873 /* Handle extra signal info using qxfer packets. */
9874 if (object == TARGET_OBJECT_SIGNAL_INFO)
9875 {
9876 if (readbuf)
9877 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9878 xfered_len, &remote_protocol_packets
9879 [PACKET_qXfer_siginfo_read]);
9880 else
9881 return remote_write_qxfer (ops, "siginfo", annex,
9882 writebuf, offset, len, xfered_len,
9883 &remote_protocol_packets
9884 [PACKET_qXfer_siginfo_write]);
9885 }
9886
9887 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9888 {
9889 if (readbuf)
9890 return remote_read_qxfer (ops, "statictrace", annex,
9891 readbuf, offset, len, xfered_len,
9892 &remote_protocol_packets
9893 [PACKET_qXfer_statictrace_read]);
9894 else
9895 return TARGET_XFER_E_IO;
9896 }
9897
9898 /* Only handle flash writes. */
9899 if (writebuf != NULL)
9900 {
9901 LONGEST xfered;
9902
9903 switch (object)
9904 {
9905 case TARGET_OBJECT_FLASH:
9906 return remote_flash_write (ops, offset, len, xfered_len,
9907 writebuf);
9908
9909 default:
9910 return TARGET_XFER_E_IO;
9911 }
9912 }
9913
9914 /* Map pre-existing objects onto letters. DO NOT do this for new
9915 objects!!! Instead specify new query packets. */
9916 switch (object)
9917 {
9918 case TARGET_OBJECT_AVR:
9919 query_type = 'R';
9920 break;
9921
9922 case TARGET_OBJECT_AUXV:
9923 gdb_assert (annex == NULL);
9924 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9925 xfered_len,
9926 &remote_protocol_packets[PACKET_qXfer_auxv]);
9927
9928 case TARGET_OBJECT_AVAILABLE_FEATURES:
9929 return remote_read_qxfer
9930 (ops, "features", annex, readbuf, offset, len, xfered_len,
9931 &remote_protocol_packets[PACKET_qXfer_features]);
9932
9933 case TARGET_OBJECT_LIBRARIES:
9934 return remote_read_qxfer
9935 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9936 &remote_protocol_packets[PACKET_qXfer_libraries]);
9937
9938 case TARGET_OBJECT_LIBRARIES_SVR4:
9939 return remote_read_qxfer
9940 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9941 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9942
9943 case TARGET_OBJECT_MEMORY_MAP:
9944 gdb_assert (annex == NULL);
9945 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9946 xfered_len,
9947 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9948
9949 case TARGET_OBJECT_OSDATA:
9950 /* Should only get here if we're connected. */
9951 gdb_assert (rs->remote_desc);
9952 return remote_read_qxfer
9953 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9954 &remote_protocol_packets[PACKET_qXfer_osdata]);
9955
9956 case TARGET_OBJECT_THREADS:
9957 gdb_assert (annex == NULL);
9958 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9959 xfered_len,
9960 &remote_protocol_packets[PACKET_qXfer_threads]);
9961
9962 case TARGET_OBJECT_TRACEFRAME_INFO:
9963 gdb_assert (annex == NULL);
9964 return remote_read_qxfer
9965 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9966 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9967
9968 case TARGET_OBJECT_FDPIC:
9969 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9970 xfered_len,
9971 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9972
9973 case TARGET_OBJECT_OPENVMS_UIB:
9974 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9975 xfered_len,
9976 &remote_protocol_packets[PACKET_qXfer_uib]);
9977
9978 case TARGET_OBJECT_BTRACE:
9979 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9980 xfered_len,
9981 &remote_protocol_packets[PACKET_qXfer_btrace]);
9982
9983 case TARGET_OBJECT_BTRACE_CONF:
9984 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9985 len, xfered_len,
9986 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9987
9988 case TARGET_OBJECT_EXEC_FILE:
9989 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9990 len, xfered_len,
9991 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9992
9993 default:
9994 return TARGET_XFER_E_IO;
9995 }
9996
9997 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9998 large enough let the caller deal with it. */
9999 if (len < get_remote_packet_size ())
10000 return TARGET_XFER_E_IO;
10001 len = get_remote_packet_size ();
10002
10003 /* Except for querying the minimum buffer size, target must be open. */
10004 if (!rs->remote_desc)
10005 error (_("remote query is only available after target open"));
10006
10007 gdb_assert (annex != NULL);
10008 gdb_assert (readbuf != NULL);
10009
10010 p2 = rs->buf;
10011 *p2++ = 'q';
10012 *p2++ = query_type;
10013
10014 /* We used one buffer char for the remote protocol q command and
10015 another for the query type. As the remote protocol encapsulation
10016 uses 4 chars plus one extra in case we are debugging
10017 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10018 string. */
10019 i = 0;
10020 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10021 {
10022 /* Bad caller may have sent forbidden characters. */
10023 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10024 *p2++ = annex[i];
10025 i++;
10026 }
10027 *p2 = '\0';
10028 gdb_assert (annex[i] == '\0');
10029
10030 i = putpkt (rs->buf);
10031 if (i < 0)
10032 return TARGET_XFER_E_IO;
10033
10034 getpkt (&rs->buf, &rs->buf_size, 0);
10035 strcpy ((char *) readbuf, rs->buf);
10036
10037 *xfered_len = strlen ((char *) readbuf);
10038 return TARGET_XFER_OK;
10039 }
10040
10041 static int
10042 remote_search_memory (struct target_ops* ops,
10043 CORE_ADDR start_addr, ULONGEST search_space_len,
10044 const gdb_byte *pattern, ULONGEST pattern_len,
10045 CORE_ADDR *found_addrp)
10046 {
10047 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10048 struct remote_state *rs = get_remote_state ();
10049 int max_size = get_memory_write_packet_size ();
10050 struct packet_config *packet =
10051 &remote_protocol_packets[PACKET_qSearch_memory];
10052 /* Number of packet bytes used to encode the pattern;
10053 this could be more than PATTERN_LEN due to escape characters. */
10054 int escaped_pattern_len;
10055 /* Amount of pattern that was encodable in the packet. */
10056 int used_pattern_len;
10057 int i;
10058 int found;
10059 ULONGEST found_addr;
10060
10061 /* Don't go to the target if we don't have to.
10062 This is done before checking packet->support to avoid the possibility that
10063 a success for this edge case means the facility works in general. */
10064 if (pattern_len > search_space_len)
10065 return 0;
10066 if (pattern_len == 0)
10067 {
10068 *found_addrp = start_addr;
10069 return 1;
10070 }
10071
10072 /* If we already know the packet isn't supported, fall back to the simple
10073 way of searching memory. */
10074
10075 if (packet_config_support (packet) == PACKET_DISABLE)
10076 {
10077 /* Target doesn't provided special support, fall back and use the
10078 standard support (copy memory and do the search here). */
10079 return simple_search_memory (ops, start_addr, search_space_len,
10080 pattern, pattern_len, found_addrp);
10081 }
10082
10083 /* Make sure the remote is pointing at the right process. */
10084 set_general_process ();
10085
10086 /* Insert header. */
10087 i = snprintf (rs->buf, max_size,
10088 "qSearch:memory:%s;%s;",
10089 phex_nz (start_addr, addr_size),
10090 phex_nz (search_space_len, sizeof (search_space_len)));
10091 max_size -= (i + 1);
10092
10093 /* Escape as much data as fits into rs->buf. */
10094 escaped_pattern_len =
10095 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10096 &used_pattern_len, max_size);
10097
10098 /* Bail if the pattern is too large. */
10099 if (used_pattern_len != pattern_len)
10100 error (_("Pattern is too large to transmit to remote target."));
10101
10102 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10103 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10104 || packet_ok (rs->buf, packet) != PACKET_OK)
10105 {
10106 /* The request may not have worked because the command is not
10107 supported. If so, fall back to the simple way. */
10108 if (packet->support == PACKET_DISABLE)
10109 {
10110 return simple_search_memory (ops, start_addr, search_space_len,
10111 pattern, pattern_len, found_addrp);
10112 }
10113 return -1;
10114 }
10115
10116 if (rs->buf[0] == '0')
10117 found = 0;
10118 else if (rs->buf[0] == '1')
10119 {
10120 found = 1;
10121 if (rs->buf[1] != ',')
10122 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10123 unpack_varlen_hex (rs->buf + 2, &found_addr);
10124 *found_addrp = found_addr;
10125 }
10126 else
10127 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10128
10129 return found;
10130 }
10131
10132 static void
10133 remote_rcmd (struct target_ops *self, const char *command,
10134 struct ui_file *outbuf)
10135 {
10136 struct remote_state *rs = get_remote_state ();
10137 char *p = rs->buf;
10138
10139 if (!rs->remote_desc)
10140 error (_("remote rcmd is only available after target open"));
10141
10142 /* Send a NULL command across as an empty command. */
10143 if (command == NULL)
10144 command = "";
10145
10146 /* The query prefix. */
10147 strcpy (rs->buf, "qRcmd,");
10148 p = strchr (rs->buf, '\0');
10149
10150 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10151 > get_remote_packet_size ())
10152 error (_("\"monitor\" command ``%s'' is too long."), command);
10153
10154 /* Encode the actual command. */
10155 bin2hex ((const gdb_byte *) command, p, strlen (command));
10156
10157 if (putpkt (rs->buf) < 0)
10158 error (_("Communication problem with target."));
10159
10160 /* get/display the response */
10161 while (1)
10162 {
10163 char *buf;
10164
10165 /* XXX - see also remote_get_noisy_reply(). */
10166 QUIT; /* Allow user to bail out with ^C. */
10167 rs->buf[0] = '\0';
10168 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10169 {
10170 /* Timeout. Continue to (try to) read responses.
10171 This is better than stopping with an error, assuming the stub
10172 is still executing the (long) monitor command.
10173 If needed, the user can interrupt gdb using C-c, obtaining
10174 an effect similar to stop on timeout. */
10175 continue;
10176 }
10177 buf = rs->buf;
10178 if (buf[0] == '\0')
10179 error (_("Target does not support this command."));
10180 if (buf[0] == 'O' && buf[1] != 'K')
10181 {
10182 remote_console_output (buf + 1); /* 'O' message from stub. */
10183 continue;
10184 }
10185 if (strcmp (buf, "OK") == 0)
10186 break;
10187 if (strlen (buf) == 3 && buf[0] == 'E'
10188 && isdigit (buf[1]) && isdigit (buf[2]))
10189 {
10190 error (_("Protocol error with Rcmd"));
10191 }
10192 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10193 {
10194 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10195
10196 fputc_unfiltered (c, outbuf);
10197 }
10198 break;
10199 }
10200 }
10201
10202 static VEC(mem_region_s) *
10203 remote_memory_map (struct target_ops *ops)
10204 {
10205 VEC(mem_region_s) *result = NULL;
10206 char *text = target_read_stralloc (&current_target,
10207 TARGET_OBJECT_MEMORY_MAP, NULL);
10208
10209 if (text)
10210 {
10211 struct cleanup *back_to = make_cleanup (xfree, text);
10212
10213 result = parse_memory_map (text);
10214 do_cleanups (back_to);
10215 }
10216
10217 return result;
10218 }
10219
10220 static void
10221 packet_command (char *args, int from_tty)
10222 {
10223 struct remote_state *rs = get_remote_state ();
10224
10225 if (!rs->remote_desc)
10226 error (_("command can only be used with remote target"));
10227
10228 if (!args)
10229 error (_("remote-packet command requires packet text as argument"));
10230
10231 puts_filtered ("sending: ");
10232 print_packet (args);
10233 puts_filtered ("\n");
10234 putpkt (args);
10235
10236 getpkt (&rs->buf, &rs->buf_size, 0);
10237 puts_filtered ("received: ");
10238 print_packet (rs->buf);
10239 puts_filtered ("\n");
10240 }
10241
10242 #if 0
10243 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10244
10245 static void display_thread_info (struct gdb_ext_thread_info *info);
10246
10247 static void threadset_test_cmd (char *cmd, int tty);
10248
10249 static void threadalive_test (char *cmd, int tty);
10250
10251 static void threadlist_test_cmd (char *cmd, int tty);
10252
10253 int get_and_display_threadinfo (threadref *ref);
10254
10255 static void threadinfo_test_cmd (char *cmd, int tty);
10256
10257 static int thread_display_step (threadref *ref, void *context);
10258
10259 static void threadlist_update_test_cmd (char *cmd, int tty);
10260
10261 static void init_remote_threadtests (void);
10262
10263 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10264
10265 static void
10266 threadset_test_cmd (char *cmd, int tty)
10267 {
10268 int sample_thread = SAMPLE_THREAD;
10269
10270 printf_filtered (_("Remote threadset test\n"));
10271 set_general_thread (sample_thread);
10272 }
10273
10274
10275 static void
10276 threadalive_test (char *cmd, int tty)
10277 {
10278 int sample_thread = SAMPLE_THREAD;
10279 int pid = ptid_get_pid (inferior_ptid);
10280 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10281
10282 if (remote_thread_alive (ptid))
10283 printf_filtered ("PASS: Thread alive test\n");
10284 else
10285 printf_filtered ("FAIL: Thread alive test\n");
10286 }
10287
10288 void output_threadid (char *title, threadref *ref);
10289
10290 void
10291 output_threadid (char *title, threadref *ref)
10292 {
10293 char hexid[20];
10294
10295 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10296 hexid[16] = 0;
10297 printf_filtered ("%s %s\n", title, (&hexid[0]));
10298 }
10299
10300 static void
10301 threadlist_test_cmd (char *cmd, int tty)
10302 {
10303 int startflag = 1;
10304 threadref nextthread;
10305 int done, result_count;
10306 threadref threadlist[3];
10307
10308 printf_filtered ("Remote Threadlist test\n");
10309 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10310 &result_count, &threadlist[0]))
10311 printf_filtered ("FAIL: threadlist test\n");
10312 else
10313 {
10314 threadref *scan = threadlist;
10315 threadref *limit = scan + result_count;
10316
10317 while (scan < limit)
10318 output_threadid (" thread ", scan++);
10319 }
10320 }
10321
10322 void
10323 display_thread_info (struct gdb_ext_thread_info *info)
10324 {
10325 output_threadid ("Threadid: ", &info->threadid);
10326 printf_filtered ("Name: %s\n ", info->shortname);
10327 printf_filtered ("State: %s\n", info->display);
10328 printf_filtered ("other: %s\n\n", info->more_display);
10329 }
10330
10331 int
10332 get_and_display_threadinfo (threadref *ref)
10333 {
10334 int result;
10335 int set;
10336 struct gdb_ext_thread_info threadinfo;
10337
10338 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10339 | TAG_MOREDISPLAY | TAG_DISPLAY;
10340 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10341 display_thread_info (&threadinfo);
10342 return result;
10343 }
10344
10345 static void
10346 threadinfo_test_cmd (char *cmd, int tty)
10347 {
10348 int athread = SAMPLE_THREAD;
10349 threadref thread;
10350 int set;
10351
10352 int_to_threadref (&thread, athread);
10353 printf_filtered ("Remote Threadinfo test\n");
10354 if (!get_and_display_threadinfo (&thread))
10355 printf_filtered ("FAIL cannot get thread info\n");
10356 }
10357
10358 static int
10359 thread_display_step (threadref *ref, void *context)
10360 {
10361 /* output_threadid(" threadstep ",ref); *//* simple test */
10362 return get_and_display_threadinfo (ref);
10363 }
10364
10365 static void
10366 threadlist_update_test_cmd (char *cmd, int tty)
10367 {
10368 printf_filtered ("Remote Threadlist update test\n");
10369 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10370 }
10371
10372 static void
10373 init_remote_threadtests (void)
10374 {
10375 add_com ("tlist", class_obscure, threadlist_test_cmd,
10376 _("Fetch and print the remote list of "
10377 "thread identifiers, one pkt only"));
10378 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10379 _("Fetch and display info about one thread"));
10380 add_com ("tset", class_obscure, threadset_test_cmd,
10381 _("Test setting to a different thread"));
10382 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10383 _("Iterate through updating all remote thread info"));
10384 add_com ("talive", class_obscure, threadalive_test,
10385 _(" Remote thread alive test "));
10386 }
10387
10388 #endif /* 0 */
10389
10390 /* Convert a thread ID to a string. Returns the string in a static
10391 buffer. */
10392
10393 static char *
10394 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10395 {
10396 static char buf[64];
10397 struct remote_state *rs = get_remote_state ();
10398
10399 if (ptid_equal (ptid, null_ptid))
10400 return normal_pid_to_str (ptid);
10401 else if (ptid_is_pid (ptid))
10402 {
10403 /* Printing an inferior target id. */
10404
10405 /* When multi-process extensions are off, there's no way in the
10406 remote protocol to know the remote process id, if there's any
10407 at all. There's one exception --- when we're connected with
10408 target extended-remote, and we manually attached to a process
10409 with "attach PID". We don't record anywhere a flag that
10410 allows us to distinguish that case from the case of
10411 connecting with extended-remote and the stub already being
10412 attached to a process, and reporting yes to qAttached, hence
10413 no smart special casing here. */
10414 if (!remote_multi_process_p (rs))
10415 {
10416 xsnprintf (buf, sizeof buf, "Remote target");
10417 return buf;
10418 }
10419
10420 return normal_pid_to_str (ptid);
10421 }
10422 else
10423 {
10424 if (ptid_equal (magic_null_ptid, ptid))
10425 xsnprintf (buf, sizeof buf, "Thread <main>");
10426 else if (rs->extended && remote_multi_process_p (rs))
10427 if (ptid_get_lwp (ptid) == 0)
10428 return normal_pid_to_str (ptid);
10429 else
10430 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10431 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10432 else
10433 xsnprintf (buf, sizeof buf, "Thread %ld",
10434 ptid_get_lwp (ptid));
10435 return buf;
10436 }
10437 }
10438
10439 /* Get the address of the thread local variable in OBJFILE which is
10440 stored at OFFSET within the thread local storage for thread PTID. */
10441
10442 static CORE_ADDR
10443 remote_get_thread_local_address (struct target_ops *ops,
10444 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10445 {
10446 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10447 {
10448 struct remote_state *rs = get_remote_state ();
10449 char *p = rs->buf;
10450 char *endp = rs->buf + get_remote_packet_size ();
10451 enum packet_result result;
10452
10453 strcpy (p, "qGetTLSAddr:");
10454 p += strlen (p);
10455 p = write_ptid (p, endp, ptid);
10456 *p++ = ',';
10457 p += hexnumstr (p, offset);
10458 *p++ = ',';
10459 p += hexnumstr (p, lm);
10460 *p++ = '\0';
10461
10462 putpkt (rs->buf);
10463 getpkt (&rs->buf, &rs->buf_size, 0);
10464 result = packet_ok (rs->buf,
10465 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10466 if (result == PACKET_OK)
10467 {
10468 ULONGEST result;
10469
10470 unpack_varlen_hex (rs->buf, &result);
10471 return result;
10472 }
10473 else if (result == PACKET_UNKNOWN)
10474 throw_error (TLS_GENERIC_ERROR,
10475 _("Remote target doesn't support qGetTLSAddr packet"));
10476 else
10477 throw_error (TLS_GENERIC_ERROR,
10478 _("Remote target failed to process qGetTLSAddr request"));
10479 }
10480 else
10481 throw_error (TLS_GENERIC_ERROR,
10482 _("TLS not supported or disabled on this target"));
10483 /* Not reached. */
10484 return 0;
10485 }
10486
10487 /* Provide thread local base, i.e. Thread Information Block address.
10488 Returns 1 if ptid is found and thread_local_base is non zero. */
10489
10490 static int
10491 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10492 {
10493 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10494 {
10495 struct remote_state *rs = get_remote_state ();
10496 char *p = rs->buf;
10497 char *endp = rs->buf + get_remote_packet_size ();
10498 enum packet_result result;
10499
10500 strcpy (p, "qGetTIBAddr:");
10501 p += strlen (p);
10502 p = write_ptid (p, endp, ptid);
10503 *p++ = '\0';
10504
10505 putpkt (rs->buf);
10506 getpkt (&rs->buf, &rs->buf_size, 0);
10507 result = packet_ok (rs->buf,
10508 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10509 if (result == PACKET_OK)
10510 {
10511 ULONGEST result;
10512
10513 unpack_varlen_hex (rs->buf, &result);
10514 if (addr)
10515 *addr = (CORE_ADDR) result;
10516 return 1;
10517 }
10518 else if (result == PACKET_UNKNOWN)
10519 error (_("Remote target doesn't support qGetTIBAddr packet"));
10520 else
10521 error (_("Remote target failed to process qGetTIBAddr request"));
10522 }
10523 else
10524 error (_("qGetTIBAddr not supported or disabled on this target"));
10525 /* Not reached. */
10526 return 0;
10527 }
10528
10529 /* Support for inferring a target description based on the current
10530 architecture and the size of a 'g' packet. While the 'g' packet
10531 can have any size (since optional registers can be left off the
10532 end), some sizes are easily recognizable given knowledge of the
10533 approximate architecture. */
10534
10535 struct remote_g_packet_guess
10536 {
10537 int bytes;
10538 const struct target_desc *tdesc;
10539 };
10540 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10541 DEF_VEC_O(remote_g_packet_guess_s);
10542
10543 struct remote_g_packet_data
10544 {
10545 VEC(remote_g_packet_guess_s) *guesses;
10546 };
10547
10548 static struct gdbarch_data *remote_g_packet_data_handle;
10549
10550 static void *
10551 remote_g_packet_data_init (struct obstack *obstack)
10552 {
10553 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10554 }
10555
10556 void
10557 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10558 const struct target_desc *tdesc)
10559 {
10560 struct remote_g_packet_data *data
10561 = ((struct remote_g_packet_data *)
10562 gdbarch_data (gdbarch, remote_g_packet_data_handle));
10563 struct remote_g_packet_guess new_guess, *guess;
10564 int ix;
10565
10566 gdb_assert (tdesc != NULL);
10567
10568 for (ix = 0;
10569 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10570 ix++)
10571 if (guess->bytes == bytes)
10572 internal_error (__FILE__, __LINE__,
10573 _("Duplicate g packet description added for size %d"),
10574 bytes);
10575
10576 new_guess.bytes = bytes;
10577 new_guess.tdesc = tdesc;
10578 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10579 }
10580
10581 /* Return 1 if remote_read_description would do anything on this target
10582 and architecture, 0 otherwise. */
10583
10584 static int
10585 remote_read_description_p (struct target_ops *target)
10586 {
10587 struct remote_g_packet_data *data
10588 = ((struct remote_g_packet_data *)
10589 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10590
10591 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10592 return 1;
10593
10594 return 0;
10595 }
10596
10597 static const struct target_desc *
10598 remote_read_description (struct target_ops *target)
10599 {
10600 struct remote_g_packet_data *data
10601 = ((struct remote_g_packet_data *)
10602 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10603
10604 /* Do not try this during initial connection, when we do not know
10605 whether there is a running but stopped thread. */
10606 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10607 return target->beneath->to_read_description (target->beneath);
10608
10609 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10610 {
10611 struct remote_g_packet_guess *guess;
10612 int ix;
10613 int bytes = send_g_packet ();
10614
10615 for (ix = 0;
10616 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10617 ix++)
10618 if (guess->bytes == bytes)
10619 return guess->tdesc;
10620
10621 /* We discard the g packet. A minor optimization would be to
10622 hold on to it, and fill the register cache once we have selected
10623 an architecture, but it's too tricky to do safely. */
10624 }
10625
10626 return target->beneath->to_read_description (target->beneath);
10627 }
10628
10629 /* Remote file transfer support. This is host-initiated I/O, not
10630 target-initiated; for target-initiated, see remote-fileio.c. */
10631
10632 /* If *LEFT is at least the length of STRING, copy STRING to
10633 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10634 decrease *LEFT. Otherwise raise an error. */
10635
10636 static void
10637 remote_buffer_add_string (char **buffer, int *left, char *string)
10638 {
10639 int len = strlen (string);
10640
10641 if (len > *left)
10642 error (_("Packet too long for target."));
10643
10644 memcpy (*buffer, string, len);
10645 *buffer += len;
10646 *left -= len;
10647
10648 /* NUL-terminate the buffer as a convenience, if there is
10649 room. */
10650 if (*left)
10651 **buffer = '\0';
10652 }
10653
10654 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10655 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10656 decrease *LEFT. Otherwise raise an error. */
10657
10658 static void
10659 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10660 int len)
10661 {
10662 if (2 * len > *left)
10663 error (_("Packet too long for target."));
10664
10665 bin2hex (bytes, *buffer, len);
10666 *buffer += 2 * len;
10667 *left -= 2 * len;
10668
10669 /* NUL-terminate the buffer as a convenience, if there is
10670 room. */
10671 if (*left)
10672 **buffer = '\0';
10673 }
10674
10675 /* If *LEFT is large enough, convert VALUE to hex and add it to
10676 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10677 decrease *LEFT. Otherwise raise an error. */
10678
10679 static void
10680 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10681 {
10682 int len = hexnumlen (value);
10683
10684 if (len > *left)
10685 error (_("Packet too long for target."));
10686
10687 hexnumstr (*buffer, value);
10688 *buffer += len;
10689 *left -= len;
10690
10691 /* NUL-terminate the buffer as a convenience, if there is
10692 room. */
10693 if (*left)
10694 **buffer = '\0';
10695 }
10696
10697 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10698 value, *REMOTE_ERRNO to the remote error number or zero if none
10699 was included, and *ATTACHMENT to point to the start of the annex
10700 if any. The length of the packet isn't needed here; there may
10701 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10702
10703 Return 0 if the packet could be parsed, -1 if it could not. If
10704 -1 is returned, the other variables may not be initialized. */
10705
10706 static int
10707 remote_hostio_parse_result (char *buffer, int *retcode,
10708 int *remote_errno, char **attachment)
10709 {
10710 char *p, *p2;
10711
10712 *remote_errno = 0;
10713 *attachment = NULL;
10714
10715 if (buffer[0] != 'F')
10716 return -1;
10717
10718 errno = 0;
10719 *retcode = strtol (&buffer[1], &p, 16);
10720 if (errno != 0 || p == &buffer[1])
10721 return -1;
10722
10723 /* Check for ",errno". */
10724 if (*p == ',')
10725 {
10726 errno = 0;
10727 *remote_errno = strtol (p + 1, &p2, 16);
10728 if (errno != 0 || p + 1 == p2)
10729 return -1;
10730 p = p2;
10731 }
10732
10733 /* Check for ";attachment". If there is no attachment, the
10734 packet should end here. */
10735 if (*p == ';')
10736 {
10737 *attachment = p + 1;
10738 return 0;
10739 }
10740 else if (*p == '\0')
10741 return 0;
10742 else
10743 return -1;
10744 }
10745
10746 /* Send a prepared I/O packet to the target and read its response.
10747 The prepared packet is in the global RS->BUF before this function
10748 is called, and the answer is there when we return.
10749
10750 COMMAND_BYTES is the length of the request to send, which may include
10751 binary data. WHICH_PACKET is the packet configuration to check
10752 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10753 is set to the error number and -1 is returned. Otherwise the value
10754 returned by the function is returned.
10755
10756 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10757 attachment is expected; an error will be reported if there's a
10758 mismatch. If one is found, *ATTACHMENT will be set to point into
10759 the packet buffer and *ATTACHMENT_LEN will be set to the
10760 attachment's length. */
10761
10762 static int
10763 remote_hostio_send_command (int command_bytes, int which_packet,
10764 int *remote_errno, char **attachment,
10765 int *attachment_len)
10766 {
10767 struct remote_state *rs = get_remote_state ();
10768 int ret, bytes_read;
10769 char *attachment_tmp;
10770
10771 if (!rs->remote_desc
10772 || packet_support (which_packet) == PACKET_DISABLE)
10773 {
10774 *remote_errno = FILEIO_ENOSYS;
10775 return -1;
10776 }
10777
10778 putpkt_binary (rs->buf, command_bytes);
10779 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10780
10781 /* If it timed out, something is wrong. Don't try to parse the
10782 buffer. */
10783 if (bytes_read < 0)
10784 {
10785 *remote_errno = FILEIO_EINVAL;
10786 return -1;
10787 }
10788
10789 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10790 {
10791 case PACKET_ERROR:
10792 *remote_errno = FILEIO_EINVAL;
10793 return -1;
10794 case PACKET_UNKNOWN:
10795 *remote_errno = FILEIO_ENOSYS;
10796 return -1;
10797 case PACKET_OK:
10798 break;
10799 }
10800
10801 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10802 &attachment_tmp))
10803 {
10804 *remote_errno = FILEIO_EINVAL;
10805 return -1;
10806 }
10807
10808 /* Make sure we saw an attachment if and only if we expected one. */
10809 if ((attachment_tmp == NULL && attachment != NULL)
10810 || (attachment_tmp != NULL && attachment == NULL))
10811 {
10812 *remote_errno = FILEIO_EINVAL;
10813 return -1;
10814 }
10815
10816 /* If an attachment was found, it must point into the packet buffer;
10817 work out how many bytes there were. */
10818 if (attachment_tmp != NULL)
10819 {
10820 *attachment = attachment_tmp;
10821 *attachment_len = bytes_read - (*attachment - rs->buf);
10822 }
10823
10824 return ret;
10825 }
10826
10827 /* Invalidate the readahead cache. */
10828
10829 static void
10830 readahead_cache_invalidate (void)
10831 {
10832 struct remote_state *rs = get_remote_state ();
10833
10834 rs->readahead_cache.fd = -1;
10835 }
10836
10837 /* Invalidate the readahead cache if it is holding data for FD. */
10838
10839 static void
10840 readahead_cache_invalidate_fd (int fd)
10841 {
10842 struct remote_state *rs = get_remote_state ();
10843
10844 if (rs->readahead_cache.fd == fd)
10845 rs->readahead_cache.fd = -1;
10846 }
10847
10848 /* Set the filesystem remote_hostio functions that take FILENAME
10849 arguments will use. Return 0 on success, or -1 if an error
10850 occurs (and set *REMOTE_ERRNO). */
10851
10852 static int
10853 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10854 {
10855 struct remote_state *rs = get_remote_state ();
10856 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10857 char *p = rs->buf;
10858 int left = get_remote_packet_size () - 1;
10859 char arg[9];
10860 int ret;
10861
10862 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10863 return 0;
10864
10865 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10866 return 0;
10867
10868 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10869
10870 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10871 remote_buffer_add_string (&p, &left, arg);
10872
10873 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10874 remote_errno, NULL, NULL);
10875
10876 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10877 return 0;
10878
10879 if (ret == 0)
10880 rs->fs_pid = required_pid;
10881
10882 return ret;
10883 }
10884
10885 /* Implementation of to_fileio_open. */
10886
10887 static int
10888 remote_hostio_open (struct target_ops *self,
10889 struct inferior *inf, const char *filename,
10890 int flags, int mode, int warn_if_slow,
10891 int *remote_errno)
10892 {
10893 struct remote_state *rs = get_remote_state ();
10894 char *p = rs->buf;
10895 int left = get_remote_packet_size () - 1;
10896
10897 if (warn_if_slow)
10898 {
10899 static int warning_issued = 0;
10900
10901 printf_unfiltered (_("Reading %s from remote target...\n"),
10902 filename);
10903
10904 if (!warning_issued)
10905 {
10906 warning (_("File transfers from remote targets can be slow."
10907 " Use \"set sysroot\" to access files locally"
10908 " instead."));
10909 warning_issued = 1;
10910 }
10911 }
10912
10913 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10914 return -1;
10915
10916 remote_buffer_add_string (&p, &left, "vFile:open:");
10917
10918 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10919 strlen (filename));
10920 remote_buffer_add_string (&p, &left, ",");
10921
10922 remote_buffer_add_int (&p, &left, flags);
10923 remote_buffer_add_string (&p, &left, ",");
10924
10925 remote_buffer_add_int (&p, &left, mode);
10926
10927 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10928 remote_errno, NULL, NULL);
10929 }
10930
10931 /* Implementation of to_fileio_pwrite. */
10932
10933 static int
10934 remote_hostio_pwrite (struct target_ops *self,
10935 int fd, const gdb_byte *write_buf, int len,
10936 ULONGEST offset, int *remote_errno)
10937 {
10938 struct remote_state *rs = get_remote_state ();
10939 char *p = rs->buf;
10940 int left = get_remote_packet_size ();
10941 int out_len;
10942
10943 readahead_cache_invalidate_fd (fd);
10944
10945 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10946
10947 remote_buffer_add_int (&p, &left, fd);
10948 remote_buffer_add_string (&p, &left, ",");
10949
10950 remote_buffer_add_int (&p, &left, offset);
10951 remote_buffer_add_string (&p, &left, ",");
10952
10953 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10954 get_remote_packet_size () - (p - rs->buf));
10955
10956 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10957 remote_errno, NULL, NULL);
10958 }
10959
10960 /* Helper for the implementation of to_fileio_pread. Read the file
10961 from the remote side with vFile:pread. */
10962
10963 static int
10964 remote_hostio_pread_vFile (struct target_ops *self,
10965 int fd, gdb_byte *read_buf, int len,
10966 ULONGEST offset, int *remote_errno)
10967 {
10968 struct remote_state *rs = get_remote_state ();
10969 char *p = rs->buf;
10970 char *attachment;
10971 int left = get_remote_packet_size ();
10972 int ret, attachment_len;
10973 int read_len;
10974
10975 remote_buffer_add_string (&p, &left, "vFile:pread:");
10976
10977 remote_buffer_add_int (&p, &left, fd);
10978 remote_buffer_add_string (&p, &left, ",");
10979
10980 remote_buffer_add_int (&p, &left, len);
10981 remote_buffer_add_string (&p, &left, ",");
10982
10983 remote_buffer_add_int (&p, &left, offset);
10984
10985 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10986 remote_errno, &attachment,
10987 &attachment_len);
10988
10989 if (ret < 0)
10990 return ret;
10991
10992 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10993 read_buf, len);
10994 if (read_len != ret)
10995 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10996
10997 return ret;
10998 }
10999
11000 /* Serve pread from the readahead cache. Returns number of bytes
11001 read, or 0 if the request can't be served from the cache. */
11002
11003 static int
11004 remote_hostio_pread_from_cache (struct remote_state *rs,
11005 int fd, gdb_byte *read_buf, size_t len,
11006 ULONGEST offset)
11007 {
11008 struct readahead_cache *cache = &rs->readahead_cache;
11009
11010 if (cache->fd == fd
11011 && cache->offset <= offset
11012 && offset < cache->offset + cache->bufsize)
11013 {
11014 ULONGEST max = cache->offset + cache->bufsize;
11015
11016 if (offset + len > max)
11017 len = max - offset;
11018
11019 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11020 return len;
11021 }
11022
11023 return 0;
11024 }
11025
11026 /* Implementation of to_fileio_pread. */
11027
11028 static int
11029 remote_hostio_pread (struct target_ops *self,
11030 int fd, gdb_byte *read_buf, int len,
11031 ULONGEST offset, int *remote_errno)
11032 {
11033 int ret;
11034 struct remote_state *rs = get_remote_state ();
11035 struct readahead_cache *cache = &rs->readahead_cache;
11036
11037 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11038 if (ret > 0)
11039 {
11040 cache->hit_count++;
11041
11042 if (remote_debug)
11043 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11044 pulongest (cache->hit_count));
11045 return ret;
11046 }
11047
11048 cache->miss_count++;
11049 if (remote_debug)
11050 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11051 pulongest (cache->miss_count));
11052
11053 cache->fd = fd;
11054 cache->offset = offset;
11055 cache->bufsize = get_remote_packet_size ();
11056 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11057
11058 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11059 cache->offset, remote_errno);
11060 if (ret <= 0)
11061 {
11062 readahead_cache_invalidate_fd (fd);
11063 return ret;
11064 }
11065
11066 cache->bufsize = ret;
11067 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11068 }
11069
11070 /* Implementation of to_fileio_close. */
11071
11072 static int
11073 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11074 {
11075 struct remote_state *rs = get_remote_state ();
11076 char *p = rs->buf;
11077 int left = get_remote_packet_size () - 1;
11078
11079 readahead_cache_invalidate_fd (fd);
11080
11081 remote_buffer_add_string (&p, &left, "vFile:close:");
11082
11083 remote_buffer_add_int (&p, &left, fd);
11084
11085 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11086 remote_errno, NULL, NULL);
11087 }
11088
11089 /* Implementation of to_fileio_unlink. */
11090
11091 static int
11092 remote_hostio_unlink (struct target_ops *self,
11093 struct inferior *inf, const char *filename,
11094 int *remote_errno)
11095 {
11096 struct remote_state *rs = get_remote_state ();
11097 char *p = rs->buf;
11098 int left = get_remote_packet_size () - 1;
11099
11100 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11101 return -1;
11102
11103 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11104
11105 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11106 strlen (filename));
11107
11108 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11109 remote_errno, NULL, NULL);
11110 }
11111
11112 /* Implementation of to_fileio_readlink. */
11113
11114 static char *
11115 remote_hostio_readlink (struct target_ops *self,
11116 struct inferior *inf, const char *filename,
11117 int *remote_errno)
11118 {
11119 struct remote_state *rs = get_remote_state ();
11120 char *p = rs->buf;
11121 char *attachment;
11122 int left = get_remote_packet_size ();
11123 int len, attachment_len;
11124 int read_len;
11125 char *ret;
11126
11127 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11128 return NULL;
11129
11130 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11131
11132 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11133 strlen (filename));
11134
11135 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11136 remote_errno, &attachment,
11137 &attachment_len);
11138
11139 if (len < 0)
11140 return NULL;
11141
11142 ret = (char *) xmalloc (len + 1);
11143
11144 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11145 (gdb_byte *) ret, len);
11146 if (read_len != len)
11147 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11148
11149 ret[len] = '\0';
11150 return ret;
11151 }
11152
11153 /* Implementation of to_fileio_fstat. */
11154
11155 static int
11156 remote_hostio_fstat (struct target_ops *self,
11157 int fd, struct stat *st,
11158 int *remote_errno)
11159 {
11160 struct remote_state *rs = get_remote_state ();
11161 char *p = rs->buf;
11162 int left = get_remote_packet_size ();
11163 int attachment_len, ret;
11164 char *attachment;
11165 struct fio_stat fst;
11166 int read_len;
11167
11168 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11169
11170 remote_buffer_add_int (&p, &left, fd);
11171
11172 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11173 remote_errno, &attachment,
11174 &attachment_len);
11175 if (ret < 0)
11176 {
11177 if (*remote_errno != FILEIO_ENOSYS)
11178 return ret;
11179
11180 /* Strictly we should return -1, ENOSYS here, but when
11181 "set sysroot remote:" was implemented in August 2008
11182 BFD's need for a stat function was sidestepped with
11183 this hack. This was not remedied until March 2015
11184 so we retain the previous behavior to avoid breaking
11185 compatibility.
11186
11187 Note that the memset is a March 2015 addition; older
11188 GDBs set st_size *and nothing else* so the structure
11189 would have garbage in all other fields. This might
11190 break something but retaining the previous behavior
11191 here would be just too wrong. */
11192
11193 memset (st, 0, sizeof (struct stat));
11194 st->st_size = INT_MAX;
11195 return 0;
11196 }
11197
11198 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11199 (gdb_byte *) &fst, sizeof (fst));
11200
11201 if (read_len != ret)
11202 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11203
11204 if (read_len != sizeof (fst))
11205 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11206 read_len, (int) sizeof (fst));
11207
11208 remote_fileio_to_host_stat (&fst, st);
11209
11210 return 0;
11211 }
11212
11213 /* Implementation of to_filesystem_is_local. */
11214
11215 static int
11216 remote_filesystem_is_local (struct target_ops *self)
11217 {
11218 /* Valgrind GDB presents itself as a remote target but works
11219 on the local filesystem: it does not implement remote get
11220 and users are not expected to set a sysroot. To handle
11221 this case we treat the remote filesystem as local if the
11222 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11223 does not support vFile:open. */
11224 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11225 {
11226 enum packet_support ps = packet_support (PACKET_vFile_open);
11227
11228 if (ps == PACKET_SUPPORT_UNKNOWN)
11229 {
11230 int fd, remote_errno;
11231
11232 /* Try opening a file to probe support. The supplied
11233 filename is irrelevant, we only care about whether
11234 the stub recognizes the packet or not. */
11235 fd = remote_hostio_open (self, NULL, "just probing",
11236 FILEIO_O_RDONLY, 0700, 0,
11237 &remote_errno);
11238
11239 if (fd >= 0)
11240 remote_hostio_close (self, fd, &remote_errno);
11241
11242 ps = packet_support (PACKET_vFile_open);
11243 }
11244
11245 if (ps == PACKET_DISABLE)
11246 {
11247 static int warning_issued = 0;
11248
11249 if (!warning_issued)
11250 {
11251 warning (_("remote target does not support file"
11252 " transfer, attempting to access files"
11253 " from local filesystem."));
11254 warning_issued = 1;
11255 }
11256
11257 return 1;
11258 }
11259 }
11260
11261 return 0;
11262 }
11263
11264 static int
11265 remote_fileio_errno_to_host (int errnum)
11266 {
11267 switch (errnum)
11268 {
11269 case FILEIO_EPERM:
11270 return EPERM;
11271 case FILEIO_ENOENT:
11272 return ENOENT;
11273 case FILEIO_EINTR:
11274 return EINTR;
11275 case FILEIO_EIO:
11276 return EIO;
11277 case FILEIO_EBADF:
11278 return EBADF;
11279 case FILEIO_EACCES:
11280 return EACCES;
11281 case FILEIO_EFAULT:
11282 return EFAULT;
11283 case FILEIO_EBUSY:
11284 return EBUSY;
11285 case FILEIO_EEXIST:
11286 return EEXIST;
11287 case FILEIO_ENODEV:
11288 return ENODEV;
11289 case FILEIO_ENOTDIR:
11290 return ENOTDIR;
11291 case FILEIO_EISDIR:
11292 return EISDIR;
11293 case FILEIO_EINVAL:
11294 return EINVAL;
11295 case FILEIO_ENFILE:
11296 return ENFILE;
11297 case FILEIO_EMFILE:
11298 return EMFILE;
11299 case FILEIO_EFBIG:
11300 return EFBIG;
11301 case FILEIO_ENOSPC:
11302 return ENOSPC;
11303 case FILEIO_ESPIPE:
11304 return ESPIPE;
11305 case FILEIO_EROFS:
11306 return EROFS;
11307 case FILEIO_ENOSYS:
11308 return ENOSYS;
11309 case FILEIO_ENAMETOOLONG:
11310 return ENAMETOOLONG;
11311 }
11312 return -1;
11313 }
11314
11315 static char *
11316 remote_hostio_error (int errnum)
11317 {
11318 int host_error = remote_fileio_errno_to_host (errnum);
11319
11320 if (host_error == -1)
11321 error (_("Unknown remote I/O error %d"), errnum);
11322 else
11323 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11324 }
11325
11326 static void
11327 remote_hostio_close_cleanup (void *opaque)
11328 {
11329 int fd = *(int *) opaque;
11330 int remote_errno;
11331
11332 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11333 }
11334
11335 void
11336 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11337 {
11338 struct cleanup *back_to, *close_cleanup;
11339 int retcode, fd, remote_errno, bytes, io_size;
11340 FILE *file;
11341 gdb_byte *buffer;
11342 int bytes_in_buffer;
11343 int saw_eof;
11344 ULONGEST offset;
11345 struct remote_state *rs = get_remote_state ();
11346
11347 if (!rs->remote_desc)
11348 error (_("command can only be used with remote target"));
11349
11350 file = gdb_fopen_cloexec (local_file, "rb");
11351 if (file == NULL)
11352 perror_with_name (local_file);
11353 back_to = make_cleanup_fclose (file);
11354
11355 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11356 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11357 | FILEIO_O_TRUNC),
11358 0700, 0, &remote_errno);
11359 if (fd == -1)
11360 remote_hostio_error (remote_errno);
11361
11362 /* Send up to this many bytes at once. They won't all fit in the
11363 remote packet limit, so we'll transfer slightly fewer. */
11364 io_size = get_remote_packet_size ();
11365 buffer = (gdb_byte *) xmalloc (io_size);
11366 make_cleanup (xfree, buffer);
11367
11368 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11369
11370 bytes_in_buffer = 0;
11371 saw_eof = 0;
11372 offset = 0;
11373 while (bytes_in_buffer || !saw_eof)
11374 {
11375 if (!saw_eof)
11376 {
11377 bytes = fread (buffer + bytes_in_buffer, 1,
11378 io_size - bytes_in_buffer,
11379 file);
11380 if (bytes == 0)
11381 {
11382 if (ferror (file))
11383 error (_("Error reading %s."), local_file);
11384 else
11385 {
11386 /* EOF. Unless there is something still in the
11387 buffer from the last iteration, we are done. */
11388 saw_eof = 1;
11389 if (bytes_in_buffer == 0)
11390 break;
11391 }
11392 }
11393 }
11394 else
11395 bytes = 0;
11396
11397 bytes += bytes_in_buffer;
11398 bytes_in_buffer = 0;
11399
11400 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11401 fd, buffer, bytes,
11402 offset, &remote_errno);
11403
11404 if (retcode < 0)
11405 remote_hostio_error (remote_errno);
11406 else if (retcode == 0)
11407 error (_("Remote write of %d bytes returned 0!"), bytes);
11408 else if (retcode < bytes)
11409 {
11410 /* Short write. Save the rest of the read data for the next
11411 write. */
11412 bytes_in_buffer = bytes - retcode;
11413 memmove (buffer, buffer + retcode, bytes_in_buffer);
11414 }
11415
11416 offset += retcode;
11417 }
11418
11419 discard_cleanups (close_cleanup);
11420 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11421 remote_hostio_error (remote_errno);
11422
11423 if (from_tty)
11424 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11425 do_cleanups (back_to);
11426 }
11427
11428 void
11429 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11430 {
11431 struct cleanup *back_to, *close_cleanup;
11432 int fd, remote_errno, bytes, io_size;
11433 FILE *file;
11434 gdb_byte *buffer;
11435 ULONGEST offset;
11436 struct remote_state *rs = get_remote_state ();
11437
11438 if (!rs->remote_desc)
11439 error (_("command can only be used with remote target"));
11440
11441 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11442 remote_file, FILEIO_O_RDONLY, 0, 0,
11443 &remote_errno);
11444 if (fd == -1)
11445 remote_hostio_error (remote_errno);
11446
11447 file = gdb_fopen_cloexec (local_file, "wb");
11448 if (file == NULL)
11449 perror_with_name (local_file);
11450 back_to = make_cleanup_fclose (file);
11451
11452 /* Send up to this many bytes at once. They won't all fit in the
11453 remote packet limit, so we'll transfer slightly fewer. */
11454 io_size = get_remote_packet_size ();
11455 buffer = (gdb_byte *) xmalloc (io_size);
11456 make_cleanup (xfree, buffer);
11457
11458 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11459
11460 offset = 0;
11461 while (1)
11462 {
11463 bytes = remote_hostio_pread (find_target_at (process_stratum),
11464 fd, buffer, io_size, offset, &remote_errno);
11465 if (bytes == 0)
11466 /* Success, but no bytes, means end-of-file. */
11467 break;
11468 if (bytes == -1)
11469 remote_hostio_error (remote_errno);
11470
11471 offset += bytes;
11472
11473 bytes = fwrite (buffer, 1, bytes, file);
11474 if (bytes == 0)
11475 perror_with_name (local_file);
11476 }
11477
11478 discard_cleanups (close_cleanup);
11479 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11480 remote_hostio_error (remote_errno);
11481
11482 if (from_tty)
11483 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11484 do_cleanups (back_to);
11485 }
11486
11487 void
11488 remote_file_delete (const char *remote_file, int from_tty)
11489 {
11490 int retcode, remote_errno;
11491 struct remote_state *rs = get_remote_state ();
11492
11493 if (!rs->remote_desc)
11494 error (_("command can only be used with remote target"));
11495
11496 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11497 NULL, remote_file, &remote_errno);
11498 if (retcode == -1)
11499 remote_hostio_error (remote_errno);
11500
11501 if (from_tty)
11502 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11503 }
11504
11505 static void
11506 remote_put_command (char *args, int from_tty)
11507 {
11508 struct cleanup *back_to;
11509 char **argv;
11510
11511 if (args == NULL)
11512 error_no_arg (_("file to put"));
11513
11514 argv = gdb_buildargv (args);
11515 back_to = make_cleanup_freeargv (argv);
11516 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11517 error (_("Invalid parameters to remote put"));
11518
11519 remote_file_put (argv[0], argv[1], from_tty);
11520
11521 do_cleanups (back_to);
11522 }
11523
11524 static void
11525 remote_get_command (char *args, int from_tty)
11526 {
11527 struct cleanup *back_to;
11528 char **argv;
11529
11530 if (args == NULL)
11531 error_no_arg (_("file to get"));
11532
11533 argv = gdb_buildargv (args);
11534 back_to = make_cleanup_freeargv (argv);
11535 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11536 error (_("Invalid parameters to remote get"));
11537
11538 remote_file_get (argv[0], argv[1], from_tty);
11539
11540 do_cleanups (back_to);
11541 }
11542
11543 static void
11544 remote_delete_command (char *args, int from_tty)
11545 {
11546 struct cleanup *back_to;
11547 char **argv;
11548
11549 if (args == NULL)
11550 error_no_arg (_("file to delete"));
11551
11552 argv = gdb_buildargv (args);
11553 back_to = make_cleanup_freeargv (argv);
11554 if (argv[0] == NULL || argv[1] != NULL)
11555 error (_("Invalid parameters to remote delete"));
11556
11557 remote_file_delete (argv[0], from_tty);
11558
11559 do_cleanups (back_to);
11560 }
11561
11562 static void
11563 remote_command (char *args, int from_tty)
11564 {
11565 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11566 }
11567
11568 static int
11569 remote_can_execute_reverse (struct target_ops *self)
11570 {
11571 if (packet_support (PACKET_bs) == PACKET_ENABLE
11572 || packet_support (PACKET_bc) == PACKET_ENABLE)
11573 return 1;
11574 else
11575 return 0;
11576 }
11577
11578 static int
11579 remote_supports_non_stop (struct target_ops *self)
11580 {
11581 return 1;
11582 }
11583
11584 static int
11585 remote_supports_disable_randomization (struct target_ops *self)
11586 {
11587 /* Only supported in extended mode. */
11588 return 0;
11589 }
11590
11591 static int
11592 remote_supports_multi_process (struct target_ops *self)
11593 {
11594 struct remote_state *rs = get_remote_state ();
11595
11596 /* Only extended-remote handles being attached to multiple
11597 processes, even though plain remote can use the multi-process
11598 thread id extensions, so that GDB knows the target process's
11599 PID. */
11600 return rs->extended && remote_multi_process_p (rs);
11601 }
11602
11603 static int
11604 remote_supports_cond_tracepoints (void)
11605 {
11606 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11607 }
11608
11609 static int
11610 remote_supports_cond_breakpoints (struct target_ops *self)
11611 {
11612 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11613 }
11614
11615 static int
11616 remote_supports_fast_tracepoints (void)
11617 {
11618 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11619 }
11620
11621 static int
11622 remote_supports_static_tracepoints (void)
11623 {
11624 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11625 }
11626
11627 static int
11628 remote_supports_install_in_trace (void)
11629 {
11630 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11631 }
11632
11633 static int
11634 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11635 {
11636 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11637 == PACKET_ENABLE);
11638 }
11639
11640 static int
11641 remote_supports_string_tracing (struct target_ops *self)
11642 {
11643 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11644 }
11645
11646 static int
11647 remote_can_run_breakpoint_commands (struct target_ops *self)
11648 {
11649 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11650 }
11651
11652 static void
11653 remote_trace_init (struct target_ops *self)
11654 {
11655 putpkt ("QTinit");
11656 remote_get_noisy_reply (&target_buf, &target_buf_size);
11657 if (strcmp (target_buf, "OK") != 0)
11658 error (_("Target does not support this command."));
11659 }
11660
11661 static void free_actions_list (char **actions_list);
11662 static void free_actions_list_cleanup_wrapper (void *);
11663 static void
11664 free_actions_list_cleanup_wrapper (void *al)
11665 {
11666 free_actions_list ((char **) al);
11667 }
11668
11669 static void
11670 free_actions_list (char **actions_list)
11671 {
11672 int ndx;
11673
11674 if (actions_list == 0)
11675 return;
11676
11677 for (ndx = 0; actions_list[ndx]; ndx++)
11678 xfree (actions_list[ndx]);
11679
11680 xfree (actions_list);
11681 }
11682
11683 /* Recursive routine to walk through command list including loops, and
11684 download packets for each command. */
11685
11686 static void
11687 remote_download_command_source (int num, ULONGEST addr,
11688 struct command_line *cmds)
11689 {
11690 struct remote_state *rs = get_remote_state ();
11691 struct command_line *cmd;
11692
11693 for (cmd = cmds; cmd; cmd = cmd->next)
11694 {
11695 QUIT; /* Allow user to bail out with ^C. */
11696 strcpy (rs->buf, "QTDPsrc:");
11697 encode_source_string (num, addr, "cmd", cmd->line,
11698 rs->buf + strlen (rs->buf),
11699 rs->buf_size - strlen (rs->buf));
11700 putpkt (rs->buf);
11701 remote_get_noisy_reply (&target_buf, &target_buf_size);
11702 if (strcmp (target_buf, "OK"))
11703 warning (_("Target does not support source download."));
11704
11705 if (cmd->control_type == while_control
11706 || cmd->control_type == while_stepping_control)
11707 {
11708 remote_download_command_source (num, addr, *cmd->body_list);
11709
11710 QUIT; /* Allow user to bail out with ^C. */
11711 strcpy (rs->buf, "QTDPsrc:");
11712 encode_source_string (num, addr, "cmd", "end",
11713 rs->buf + strlen (rs->buf),
11714 rs->buf_size - strlen (rs->buf));
11715 putpkt (rs->buf);
11716 remote_get_noisy_reply (&target_buf, &target_buf_size);
11717 if (strcmp (target_buf, "OK"))
11718 warning (_("Target does not support source download."));
11719 }
11720 }
11721 }
11722
11723 static void
11724 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11725 {
11726 #define BUF_SIZE 2048
11727
11728 CORE_ADDR tpaddr;
11729 char addrbuf[40];
11730 char buf[BUF_SIZE];
11731 char **tdp_actions;
11732 char **stepping_actions;
11733 int ndx;
11734 struct cleanup *old_chain = NULL;
11735 struct agent_expr *aexpr;
11736 struct cleanup *aexpr_chain = NULL;
11737 char *pkt;
11738 struct breakpoint *b = loc->owner;
11739 struct tracepoint *t = (struct tracepoint *) b;
11740
11741 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11742 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11743 tdp_actions);
11744 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11745 stepping_actions);
11746
11747 tpaddr = loc->address;
11748 sprintf_vma (addrbuf, tpaddr);
11749 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11750 addrbuf, /* address */
11751 (b->enable_state == bp_enabled ? 'E' : 'D'),
11752 t->step_count, t->pass_count);
11753 /* Fast tracepoints are mostly handled by the target, but we can
11754 tell the target how big of an instruction block should be moved
11755 around. */
11756 if (b->type == bp_fast_tracepoint)
11757 {
11758 /* Only test for support at download time; we may not know
11759 target capabilities at definition time. */
11760 if (remote_supports_fast_tracepoints ())
11761 {
11762 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11763 NULL))
11764 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11765 gdb_insn_length (loc->gdbarch, tpaddr));
11766 else
11767 /* If it passed validation at definition but fails now,
11768 something is very wrong. */
11769 internal_error (__FILE__, __LINE__,
11770 _("Fast tracepoint not "
11771 "valid during download"));
11772 }
11773 else
11774 /* Fast tracepoints are functionally identical to regular
11775 tracepoints, so don't take lack of support as a reason to
11776 give up on the trace run. */
11777 warning (_("Target does not support fast tracepoints, "
11778 "downloading %d as regular tracepoint"), b->number);
11779 }
11780 else if (b->type == bp_static_tracepoint)
11781 {
11782 /* Only test for support at download time; we may not know
11783 target capabilities at definition time. */
11784 if (remote_supports_static_tracepoints ())
11785 {
11786 struct static_tracepoint_marker marker;
11787
11788 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11789 strcat (buf, ":S");
11790 else
11791 error (_("Static tracepoint not valid during download"));
11792 }
11793 else
11794 /* Fast tracepoints are functionally identical to regular
11795 tracepoints, so don't take lack of support as a reason
11796 to give up on the trace run. */
11797 error (_("Target does not support static tracepoints"));
11798 }
11799 /* If the tracepoint has a conditional, make it into an agent
11800 expression and append to the definition. */
11801 if (loc->cond)
11802 {
11803 /* Only test support at download time, we may not know target
11804 capabilities at definition time. */
11805 if (remote_supports_cond_tracepoints ())
11806 {
11807 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11808 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11809 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11810 aexpr->len);
11811 pkt = buf + strlen (buf);
11812 for (ndx = 0; ndx < aexpr->len; ++ndx)
11813 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11814 *pkt = '\0';
11815 do_cleanups (aexpr_chain);
11816 }
11817 else
11818 warning (_("Target does not support conditional tracepoints, "
11819 "ignoring tp %d cond"), b->number);
11820 }
11821
11822 if (b->commands || *default_collect)
11823 strcat (buf, "-");
11824 putpkt (buf);
11825 remote_get_noisy_reply (&target_buf, &target_buf_size);
11826 if (strcmp (target_buf, "OK"))
11827 error (_("Target does not support tracepoints."));
11828
11829 /* do_single_steps (t); */
11830 if (tdp_actions)
11831 {
11832 for (ndx = 0; tdp_actions[ndx]; ndx++)
11833 {
11834 QUIT; /* Allow user to bail out with ^C. */
11835 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11836 b->number, addrbuf, /* address */
11837 tdp_actions[ndx],
11838 ((tdp_actions[ndx + 1] || stepping_actions)
11839 ? '-' : 0));
11840 putpkt (buf);
11841 remote_get_noisy_reply (&target_buf,
11842 &target_buf_size);
11843 if (strcmp (target_buf, "OK"))
11844 error (_("Error on target while setting tracepoints."));
11845 }
11846 }
11847 if (stepping_actions)
11848 {
11849 for (ndx = 0; stepping_actions[ndx]; ndx++)
11850 {
11851 QUIT; /* Allow user to bail out with ^C. */
11852 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11853 b->number, addrbuf, /* address */
11854 ((ndx == 0) ? "S" : ""),
11855 stepping_actions[ndx],
11856 (stepping_actions[ndx + 1] ? "-" : ""));
11857 putpkt (buf);
11858 remote_get_noisy_reply (&target_buf,
11859 &target_buf_size);
11860 if (strcmp (target_buf, "OK"))
11861 error (_("Error on target while setting tracepoints."));
11862 }
11863 }
11864
11865 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11866 {
11867 if (b->location != NULL)
11868 {
11869 strcpy (buf, "QTDPsrc:");
11870 encode_source_string (b->number, loc->address, "at",
11871 event_location_to_string (b->location),
11872 buf + strlen (buf), 2048 - strlen (buf));
11873 putpkt (buf);
11874 remote_get_noisy_reply (&target_buf, &target_buf_size);
11875 if (strcmp (target_buf, "OK"))
11876 warning (_("Target does not support source download."));
11877 }
11878 if (b->cond_string)
11879 {
11880 strcpy (buf, "QTDPsrc:");
11881 encode_source_string (b->number, loc->address,
11882 "cond", b->cond_string, buf + strlen (buf),
11883 2048 - strlen (buf));
11884 putpkt (buf);
11885 remote_get_noisy_reply (&target_buf, &target_buf_size);
11886 if (strcmp (target_buf, "OK"))
11887 warning (_("Target does not support source download."));
11888 }
11889 remote_download_command_source (b->number, loc->address,
11890 breakpoint_commands (b));
11891 }
11892
11893 do_cleanups (old_chain);
11894 }
11895
11896 static int
11897 remote_can_download_tracepoint (struct target_ops *self)
11898 {
11899 struct remote_state *rs = get_remote_state ();
11900 struct trace_status *ts;
11901 int status;
11902
11903 /* Don't try to install tracepoints until we've relocated our
11904 symbols, and fetched and merged the target's tracepoint list with
11905 ours. */
11906 if (rs->starting_up)
11907 return 0;
11908
11909 ts = current_trace_status ();
11910 status = remote_get_trace_status (self, ts);
11911
11912 if (status == -1 || !ts->running_known || !ts->running)
11913 return 0;
11914
11915 /* If we are in a tracing experiment, but remote stub doesn't support
11916 installing tracepoint in trace, we have to return. */
11917 if (!remote_supports_install_in_trace ())
11918 return 0;
11919
11920 return 1;
11921 }
11922
11923
11924 static void
11925 remote_download_trace_state_variable (struct target_ops *self,
11926 struct trace_state_variable *tsv)
11927 {
11928 struct remote_state *rs = get_remote_state ();
11929 char *p;
11930
11931 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11932 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11933 tsv->builtin);
11934 p = rs->buf + strlen (rs->buf);
11935 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11936 error (_("Trace state variable name too long for tsv definition packet"));
11937 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11938 *p++ = '\0';
11939 putpkt (rs->buf);
11940 remote_get_noisy_reply (&target_buf, &target_buf_size);
11941 if (*target_buf == '\0')
11942 error (_("Target does not support this command."));
11943 if (strcmp (target_buf, "OK") != 0)
11944 error (_("Error on target while downloading trace state variable."));
11945 }
11946
11947 static void
11948 remote_enable_tracepoint (struct target_ops *self,
11949 struct bp_location *location)
11950 {
11951 struct remote_state *rs = get_remote_state ();
11952 char addr_buf[40];
11953
11954 sprintf_vma (addr_buf, location->address);
11955 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11956 location->owner->number, addr_buf);
11957 putpkt (rs->buf);
11958 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11959 if (*rs->buf == '\0')
11960 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11961 if (strcmp (rs->buf, "OK") != 0)
11962 error (_("Error on target while enabling tracepoint."));
11963 }
11964
11965 static void
11966 remote_disable_tracepoint (struct target_ops *self,
11967 struct bp_location *location)
11968 {
11969 struct remote_state *rs = get_remote_state ();
11970 char addr_buf[40];
11971
11972 sprintf_vma (addr_buf, location->address);
11973 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11974 location->owner->number, addr_buf);
11975 putpkt (rs->buf);
11976 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11977 if (*rs->buf == '\0')
11978 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11979 if (strcmp (rs->buf, "OK") != 0)
11980 error (_("Error on target while disabling tracepoint."));
11981 }
11982
11983 static void
11984 remote_trace_set_readonly_regions (struct target_ops *self)
11985 {
11986 asection *s;
11987 bfd *abfd = NULL;
11988 bfd_size_type size;
11989 bfd_vma vma;
11990 int anysecs = 0;
11991 int offset = 0;
11992
11993 if (!exec_bfd)
11994 return; /* No information to give. */
11995
11996 strcpy (target_buf, "QTro");
11997 offset = strlen (target_buf);
11998 for (s = exec_bfd->sections; s; s = s->next)
11999 {
12000 char tmp1[40], tmp2[40];
12001 int sec_length;
12002
12003 if ((s->flags & SEC_LOAD) == 0 ||
12004 /* (s->flags & SEC_CODE) == 0 || */
12005 (s->flags & SEC_READONLY) == 0)
12006 continue;
12007
12008 anysecs = 1;
12009 vma = bfd_get_section_vma (abfd, s);
12010 size = bfd_get_section_size (s);
12011 sprintf_vma (tmp1, vma);
12012 sprintf_vma (tmp2, vma + size);
12013 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12014 if (offset + sec_length + 1 > target_buf_size)
12015 {
12016 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12017 warning (_("\
12018 Too many sections for read-only sections definition packet."));
12019 break;
12020 }
12021 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12022 tmp1, tmp2);
12023 offset += sec_length;
12024 }
12025 if (anysecs)
12026 {
12027 putpkt (target_buf);
12028 getpkt (&target_buf, &target_buf_size, 0);
12029 }
12030 }
12031
12032 static void
12033 remote_trace_start (struct target_ops *self)
12034 {
12035 putpkt ("QTStart");
12036 remote_get_noisy_reply (&target_buf, &target_buf_size);
12037 if (*target_buf == '\0')
12038 error (_("Target does not support this command."));
12039 if (strcmp (target_buf, "OK") != 0)
12040 error (_("Bogus reply from target: %s"), target_buf);
12041 }
12042
12043 static int
12044 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12045 {
12046 /* Initialize it just to avoid a GCC false warning. */
12047 char *p = NULL;
12048 /* FIXME we need to get register block size some other way. */
12049 extern int trace_regblock_size;
12050 enum packet_result result;
12051
12052 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12053 return -1;
12054
12055 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12056
12057 putpkt ("qTStatus");
12058
12059 TRY
12060 {
12061 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12062 }
12063 CATCH (ex, RETURN_MASK_ERROR)
12064 {
12065 if (ex.error != TARGET_CLOSE_ERROR)
12066 {
12067 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12068 return -1;
12069 }
12070 throw_exception (ex);
12071 }
12072 END_CATCH
12073
12074 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12075
12076 /* If the remote target doesn't do tracing, flag it. */
12077 if (result == PACKET_UNKNOWN)
12078 return -1;
12079
12080 /* We're working with a live target. */
12081 ts->filename = NULL;
12082
12083 if (*p++ != 'T')
12084 error (_("Bogus trace status reply from target: %s"), target_buf);
12085
12086 /* Function 'parse_trace_status' sets default value of each field of
12087 'ts' at first, so we don't have to do it here. */
12088 parse_trace_status (p, ts);
12089
12090 return ts->running;
12091 }
12092
12093 static void
12094 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12095 struct uploaded_tp *utp)
12096 {
12097 struct remote_state *rs = get_remote_state ();
12098 char *reply;
12099 struct bp_location *loc;
12100 struct tracepoint *tp = (struct tracepoint *) bp;
12101 size_t size = get_remote_packet_size ();
12102
12103 if (tp)
12104 {
12105 tp->base.hit_count = 0;
12106 tp->traceframe_usage = 0;
12107 for (loc = tp->base.loc; loc; loc = loc->next)
12108 {
12109 /* If the tracepoint was never downloaded, don't go asking for
12110 any status. */
12111 if (tp->number_on_target == 0)
12112 continue;
12113 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12114 phex_nz (loc->address, 0));
12115 putpkt (rs->buf);
12116 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12117 if (reply && *reply)
12118 {
12119 if (*reply == 'V')
12120 parse_tracepoint_status (reply + 1, bp, utp);
12121 }
12122 }
12123 }
12124 else if (utp)
12125 {
12126 utp->hit_count = 0;
12127 utp->traceframe_usage = 0;
12128 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12129 phex_nz (utp->addr, 0));
12130 putpkt (rs->buf);
12131 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12132 if (reply && *reply)
12133 {
12134 if (*reply == 'V')
12135 parse_tracepoint_status (reply + 1, bp, utp);
12136 }
12137 }
12138 }
12139
12140 static void
12141 remote_trace_stop (struct target_ops *self)
12142 {
12143 putpkt ("QTStop");
12144 remote_get_noisy_reply (&target_buf, &target_buf_size);
12145 if (*target_buf == '\0')
12146 error (_("Target does not support this command."));
12147 if (strcmp (target_buf, "OK") != 0)
12148 error (_("Bogus reply from target: %s"), target_buf);
12149 }
12150
12151 static int
12152 remote_trace_find (struct target_ops *self,
12153 enum trace_find_type type, int num,
12154 CORE_ADDR addr1, CORE_ADDR addr2,
12155 int *tpp)
12156 {
12157 struct remote_state *rs = get_remote_state ();
12158 char *endbuf = rs->buf + get_remote_packet_size ();
12159 char *p, *reply;
12160 int target_frameno = -1, target_tracept = -1;
12161
12162 /* Lookups other than by absolute frame number depend on the current
12163 trace selected, so make sure it is correct on the remote end
12164 first. */
12165 if (type != tfind_number)
12166 set_remote_traceframe ();
12167
12168 p = rs->buf;
12169 strcpy (p, "QTFrame:");
12170 p = strchr (p, '\0');
12171 switch (type)
12172 {
12173 case tfind_number:
12174 xsnprintf (p, endbuf - p, "%x", num);
12175 break;
12176 case tfind_pc:
12177 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12178 break;
12179 case tfind_tp:
12180 xsnprintf (p, endbuf - p, "tdp:%x", num);
12181 break;
12182 case tfind_range:
12183 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12184 phex_nz (addr2, 0));
12185 break;
12186 case tfind_outside:
12187 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12188 phex_nz (addr2, 0));
12189 break;
12190 default:
12191 error (_("Unknown trace find type %d"), type);
12192 }
12193
12194 putpkt (rs->buf);
12195 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12196 if (*reply == '\0')
12197 error (_("Target does not support this command."));
12198
12199 while (reply && *reply)
12200 switch (*reply)
12201 {
12202 case 'F':
12203 p = ++reply;
12204 target_frameno = (int) strtol (p, &reply, 16);
12205 if (reply == p)
12206 error (_("Unable to parse trace frame number"));
12207 /* Don't update our remote traceframe number cache on failure
12208 to select a remote traceframe. */
12209 if (target_frameno == -1)
12210 return -1;
12211 break;
12212 case 'T':
12213 p = ++reply;
12214 target_tracept = (int) strtol (p, &reply, 16);
12215 if (reply == p)
12216 error (_("Unable to parse tracepoint number"));
12217 break;
12218 case 'O': /* "OK"? */
12219 if (reply[1] == 'K' && reply[2] == '\0')
12220 reply += 2;
12221 else
12222 error (_("Bogus reply from target: %s"), reply);
12223 break;
12224 default:
12225 error (_("Bogus reply from target: %s"), reply);
12226 }
12227 if (tpp)
12228 *tpp = target_tracept;
12229
12230 rs->remote_traceframe_number = target_frameno;
12231 return target_frameno;
12232 }
12233
12234 static int
12235 remote_get_trace_state_variable_value (struct target_ops *self,
12236 int tsvnum, LONGEST *val)
12237 {
12238 struct remote_state *rs = get_remote_state ();
12239 char *reply;
12240 ULONGEST uval;
12241
12242 set_remote_traceframe ();
12243
12244 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12245 putpkt (rs->buf);
12246 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12247 if (reply && *reply)
12248 {
12249 if (*reply == 'V')
12250 {
12251 unpack_varlen_hex (reply + 1, &uval);
12252 *val = (LONGEST) uval;
12253 return 1;
12254 }
12255 }
12256 return 0;
12257 }
12258
12259 static int
12260 remote_save_trace_data (struct target_ops *self, const char *filename)
12261 {
12262 struct remote_state *rs = get_remote_state ();
12263 char *p, *reply;
12264
12265 p = rs->buf;
12266 strcpy (p, "QTSave:");
12267 p += strlen (p);
12268 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12269 error (_("Remote file name too long for trace save packet"));
12270 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12271 *p++ = '\0';
12272 putpkt (rs->buf);
12273 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12274 if (*reply == '\0')
12275 error (_("Target does not support this command."));
12276 if (strcmp (reply, "OK") != 0)
12277 error (_("Bogus reply from target: %s"), reply);
12278 return 0;
12279 }
12280
12281 /* This is basically a memory transfer, but needs to be its own packet
12282 because we don't know how the target actually organizes its trace
12283 memory, plus we want to be able to ask for as much as possible, but
12284 not be unhappy if we don't get as much as we ask for. */
12285
12286 static LONGEST
12287 remote_get_raw_trace_data (struct target_ops *self,
12288 gdb_byte *buf, ULONGEST offset, LONGEST len)
12289 {
12290 struct remote_state *rs = get_remote_state ();
12291 char *reply;
12292 char *p;
12293 int rslt;
12294
12295 p = rs->buf;
12296 strcpy (p, "qTBuffer:");
12297 p += strlen (p);
12298 p += hexnumstr (p, offset);
12299 *p++ = ',';
12300 p += hexnumstr (p, len);
12301 *p++ = '\0';
12302
12303 putpkt (rs->buf);
12304 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12305 if (reply && *reply)
12306 {
12307 /* 'l' by itself means we're at the end of the buffer and
12308 there is nothing more to get. */
12309 if (*reply == 'l')
12310 return 0;
12311
12312 /* Convert the reply into binary. Limit the number of bytes to
12313 convert according to our passed-in buffer size, rather than
12314 what was returned in the packet; if the target is
12315 unexpectedly generous and gives us a bigger reply than we
12316 asked for, we don't want to crash. */
12317 rslt = hex2bin (target_buf, buf, len);
12318 return rslt;
12319 }
12320
12321 /* Something went wrong, flag as an error. */
12322 return -1;
12323 }
12324
12325 static void
12326 remote_set_disconnected_tracing (struct target_ops *self, int val)
12327 {
12328 struct remote_state *rs = get_remote_state ();
12329
12330 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12331 {
12332 char *reply;
12333
12334 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12335 putpkt (rs->buf);
12336 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12337 if (*reply == '\0')
12338 error (_("Target does not support this command."));
12339 if (strcmp (reply, "OK") != 0)
12340 error (_("Bogus reply from target: %s"), reply);
12341 }
12342 else if (val)
12343 warning (_("Target does not support disconnected tracing."));
12344 }
12345
12346 static int
12347 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12348 {
12349 struct thread_info *info = find_thread_ptid (ptid);
12350
12351 if (info && info->priv)
12352 return info->priv->core;
12353 return -1;
12354 }
12355
12356 static void
12357 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12358 {
12359 struct remote_state *rs = get_remote_state ();
12360 char *reply;
12361
12362 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12363 putpkt (rs->buf);
12364 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12365 if (*reply == '\0')
12366 error (_("Target does not support this command."));
12367 if (strcmp (reply, "OK") != 0)
12368 error (_("Bogus reply from target: %s"), reply);
12369 }
12370
12371 static struct traceframe_info *
12372 remote_traceframe_info (struct target_ops *self)
12373 {
12374 char *text;
12375
12376 text = target_read_stralloc (&current_target,
12377 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12378 if (text != NULL)
12379 {
12380 struct traceframe_info *info;
12381 struct cleanup *back_to = make_cleanup (xfree, text);
12382
12383 info = parse_traceframe_info (text);
12384 do_cleanups (back_to);
12385 return info;
12386 }
12387
12388 return NULL;
12389 }
12390
12391 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12392 instruction on which a fast tracepoint may be placed. Returns -1
12393 if the packet is not supported, and 0 if the minimum instruction
12394 length is unknown. */
12395
12396 static int
12397 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12398 {
12399 struct remote_state *rs = get_remote_state ();
12400 char *reply;
12401
12402 /* If we're not debugging a process yet, the IPA can't be
12403 loaded. */
12404 if (!target_has_execution)
12405 return 0;
12406
12407 /* Make sure the remote is pointing at the right process. */
12408 set_general_process ();
12409
12410 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12411 putpkt (rs->buf);
12412 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12413 if (*reply == '\0')
12414 return -1;
12415 else
12416 {
12417 ULONGEST min_insn_len;
12418
12419 unpack_varlen_hex (reply, &min_insn_len);
12420
12421 return (int) min_insn_len;
12422 }
12423 }
12424
12425 static void
12426 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12427 {
12428 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12429 {
12430 struct remote_state *rs = get_remote_state ();
12431 char *buf = rs->buf;
12432 char *endbuf = rs->buf + get_remote_packet_size ();
12433 enum packet_result result;
12434
12435 gdb_assert (val >= 0 || val == -1);
12436 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12437 /* Send -1 as literal "-1" to avoid host size dependency. */
12438 if (val < 0)
12439 {
12440 *buf++ = '-';
12441 buf += hexnumstr (buf, (ULONGEST) -val);
12442 }
12443 else
12444 buf += hexnumstr (buf, (ULONGEST) val);
12445
12446 putpkt (rs->buf);
12447 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12448 result = packet_ok (rs->buf,
12449 &remote_protocol_packets[PACKET_QTBuffer_size]);
12450
12451 if (result != PACKET_OK)
12452 warning (_("Bogus reply from target: %s"), rs->buf);
12453 }
12454 }
12455
12456 static int
12457 remote_set_trace_notes (struct target_ops *self,
12458 const char *user, const char *notes,
12459 const char *stop_notes)
12460 {
12461 struct remote_state *rs = get_remote_state ();
12462 char *reply;
12463 char *buf = rs->buf;
12464 char *endbuf = rs->buf + get_remote_packet_size ();
12465 int nbytes;
12466
12467 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12468 if (user)
12469 {
12470 buf += xsnprintf (buf, endbuf - buf, "user:");
12471 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12472 buf += 2 * nbytes;
12473 *buf++ = ';';
12474 }
12475 if (notes)
12476 {
12477 buf += xsnprintf (buf, endbuf - buf, "notes:");
12478 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12479 buf += 2 * nbytes;
12480 *buf++ = ';';
12481 }
12482 if (stop_notes)
12483 {
12484 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12485 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12486 buf += 2 * nbytes;
12487 *buf++ = ';';
12488 }
12489 /* Ensure the buffer is terminated. */
12490 *buf = '\0';
12491
12492 putpkt (rs->buf);
12493 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12494 if (*reply == '\0')
12495 return 0;
12496
12497 if (strcmp (reply, "OK") != 0)
12498 error (_("Bogus reply from target: %s"), reply);
12499
12500 return 1;
12501 }
12502
12503 static int
12504 remote_use_agent (struct target_ops *self, int use)
12505 {
12506 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12507 {
12508 struct remote_state *rs = get_remote_state ();
12509
12510 /* If the stub supports QAgent. */
12511 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12512 putpkt (rs->buf);
12513 getpkt (&rs->buf, &rs->buf_size, 0);
12514
12515 if (strcmp (rs->buf, "OK") == 0)
12516 {
12517 use_agent = use;
12518 return 1;
12519 }
12520 }
12521
12522 return 0;
12523 }
12524
12525 static int
12526 remote_can_use_agent (struct target_ops *self)
12527 {
12528 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12529 }
12530
12531 struct btrace_target_info
12532 {
12533 /* The ptid of the traced thread. */
12534 ptid_t ptid;
12535
12536 /* The obtained branch trace configuration. */
12537 struct btrace_config conf;
12538 };
12539
12540 /* Reset our idea of our target's btrace configuration. */
12541
12542 static void
12543 remote_btrace_reset (void)
12544 {
12545 struct remote_state *rs = get_remote_state ();
12546
12547 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12548 }
12549
12550 /* Check whether the target supports branch tracing. */
12551
12552 static int
12553 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12554 {
12555 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12556 return 0;
12557 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12558 return 0;
12559
12560 switch (format)
12561 {
12562 case BTRACE_FORMAT_NONE:
12563 return 0;
12564
12565 case BTRACE_FORMAT_BTS:
12566 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12567
12568 case BTRACE_FORMAT_PT:
12569 /* The trace is decoded on the host. Even if our target supports it,
12570 we still need to have libipt to decode the trace. */
12571 #if defined (HAVE_LIBIPT)
12572 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12573 #else /* !defined (HAVE_LIBIPT) */
12574 return 0;
12575 #endif /* !defined (HAVE_LIBIPT) */
12576 }
12577
12578 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12579 }
12580
12581 /* Synchronize the configuration with the target. */
12582
12583 static void
12584 btrace_sync_conf (const struct btrace_config *conf)
12585 {
12586 struct packet_config *packet;
12587 struct remote_state *rs;
12588 char *buf, *pos, *endbuf;
12589
12590 rs = get_remote_state ();
12591 buf = rs->buf;
12592 endbuf = buf + get_remote_packet_size ();
12593
12594 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12595 if (packet_config_support (packet) == PACKET_ENABLE
12596 && conf->bts.size != rs->btrace_config.bts.size)
12597 {
12598 pos = buf;
12599 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12600 conf->bts.size);
12601
12602 putpkt (buf);
12603 getpkt (&buf, &rs->buf_size, 0);
12604
12605 if (packet_ok (buf, packet) == PACKET_ERROR)
12606 {
12607 if (buf[0] == 'E' && buf[1] == '.')
12608 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12609 else
12610 error (_("Failed to configure the BTS buffer size."));
12611 }
12612
12613 rs->btrace_config.bts.size = conf->bts.size;
12614 }
12615
12616 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12617 if (packet_config_support (packet) == PACKET_ENABLE
12618 && conf->pt.size != rs->btrace_config.pt.size)
12619 {
12620 pos = buf;
12621 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12622 conf->pt.size);
12623
12624 putpkt (buf);
12625 getpkt (&buf, &rs->buf_size, 0);
12626
12627 if (packet_ok (buf, packet) == PACKET_ERROR)
12628 {
12629 if (buf[0] == 'E' && buf[1] == '.')
12630 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12631 else
12632 error (_("Failed to configure the trace buffer size."));
12633 }
12634
12635 rs->btrace_config.pt.size = conf->pt.size;
12636 }
12637 }
12638
12639 /* Read the current thread's btrace configuration from the target and
12640 store it into CONF. */
12641
12642 static void
12643 btrace_read_config (struct btrace_config *conf)
12644 {
12645 char *xml;
12646
12647 xml = target_read_stralloc (&current_target,
12648 TARGET_OBJECT_BTRACE_CONF, "");
12649 if (xml != NULL)
12650 {
12651 struct cleanup *cleanup;
12652
12653 cleanup = make_cleanup (xfree, xml);
12654 parse_xml_btrace_conf (conf, xml);
12655 do_cleanups (cleanup);
12656 }
12657 }
12658
12659 /* Enable branch tracing. */
12660
12661 static struct btrace_target_info *
12662 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12663 const struct btrace_config *conf)
12664 {
12665 struct btrace_target_info *tinfo = NULL;
12666 struct packet_config *packet = NULL;
12667 struct remote_state *rs = get_remote_state ();
12668 char *buf = rs->buf;
12669 char *endbuf = rs->buf + get_remote_packet_size ();
12670
12671 switch (conf->format)
12672 {
12673 case BTRACE_FORMAT_BTS:
12674 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12675 break;
12676
12677 case BTRACE_FORMAT_PT:
12678 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12679 break;
12680 }
12681
12682 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12683 error (_("Target does not support branch tracing."));
12684
12685 btrace_sync_conf (conf);
12686
12687 set_general_thread (ptid);
12688
12689 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12690 putpkt (rs->buf);
12691 getpkt (&rs->buf, &rs->buf_size, 0);
12692
12693 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12694 {
12695 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12696 error (_("Could not enable branch tracing for %s: %s"),
12697 target_pid_to_str (ptid), rs->buf + 2);
12698 else
12699 error (_("Could not enable branch tracing for %s."),
12700 target_pid_to_str (ptid));
12701 }
12702
12703 tinfo = XCNEW (struct btrace_target_info);
12704 tinfo->ptid = ptid;
12705
12706 /* If we fail to read the configuration, we lose some information, but the
12707 tracing itself is not impacted. */
12708 TRY
12709 {
12710 btrace_read_config (&tinfo->conf);
12711 }
12712 CATCH (err, RETURN_MASK_ERROR)
12713 {
12714 if (err.message != NULL)
12715 warning ("%s", err.message);
12716 }
12717 END_CATCH
12718
12719 return tinfo;
12720 }
12721
12722 /* Disable branch tracing. */
12723
12724 static void
12725 remote_disable_btrace (struct target_ops *self,
12726 struct btrace_target_info *tinfo)
12727 {
12728 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12729 struct remote_state *rs = get_remote_state ();
12730 char *buf = rs->buf;
12731 char *endbuf = rs->buf + get_remote_packet_size ();
12732
12733 if (packet_config_support (packet) != PACKET_ENABLE)
12734 error (_("Target does not support branch tracing."));
12735
12736 set_general_thread (tinfo->ptid);
12737
12738 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12739 putpkt (rs->buf);
12740 getpkt (&rs->buf, &rs->buf_size, 0);
12741
12742 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12743 {
12744 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12745 error (_("Could not disable branch tracing for %s: %s"),
12746 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12747 else
12748 error (_("Could not disable branch tracing for %s."),
12749 target_pid_to_str (tinfo->ptid));
12750 }
12751
12752 xfree (tinfo);
12753 }
12754
12755 /* Teardown branch tracing. */
12756
12757 static void
12758 remote_teardown_btrace (struct target_ops *self,
12759 struct btrace_target_info *tinfo)
12760 {
12761 /* We must not talk to the target during teardown. */
12762 xfree (tinfo);
12763 }
12764
12765 /* Read the branch trace. */
12766
12767 static enum btrace_error
12768 remote_read_btrace (struct target_ops *self,
12769 struct btrace_data *btrace,
12770 struct btrace_target_info *tinfo,
12771 enum btrace_read_type type)
12772 {
12773 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12774 struct remote_state *rs = get_remote_state ();
12775 struct cleanup *cleanup;
12776 const char *annex;
12777 char *xml;
12778
12779 if (packet_config_support (packet) != PACKET_ENABLE)
12780 error (_("Target does not support branch tracing."));
12781
12782 #if !defined(HAVE_LIBEXPAT)
12783 error (_("Cannot process branch tracing result. XML parsing not supported."));
12784 #endif
12785
12786 switch (type)
12787 {
12788 case BTRACE_READ_ALL:
12789 annex = "all";
12790 break;
12791 case BTRACE_READ_NEW:
12792 annex = "new";
12793 break;
12794 case BTRACE_READ_DELTA:
12795 annex = "delta";
12796 break;
12797 default:
12798 internal_error (__FILE__, __LINE__,
12799 _("Bad branch tracing read type: %u."),
12800 (unsigned int) type);
12801 }
12802
12803 xml = target_read_stralloc (&current_target,
12804 TARGET_OBJECT_BTRACE, annex);
12805 if (xml == NULL)
12806 return BTRACE_ERR_UNKNOWN;
12807
12808 cleanup = make_cleanup (xfree, xml);
12809 parse_xml_btrace (btrace, xml);
12810 do_cleanups (cleanup);
12811
12812 return BTRACE_ERR_NONE;
12813 }
12814
12815 static const struct btrace_config *
12816 remote_btrace_conf (struct target_ops *self,
12817 const struct btrace_target_info *tinfo)
12818 {
12819 return &tinfo->conf;
12820 }
12821
12822 static int
12823 remote_augmented_libraries_svr4_read (struct target_ops *self)
12824 {
12825 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12826 == PACKET_ENABLE);
12827 }
12828
12829 /* Implementation of to_load. */
12830
12831 static void
12832 remote_load (struct target_ops *self, const char *name, int from_tty)
12833 {
12834 generic_load (name, from_tty);
12835 }
12836
12837 /* Accepts an integer PID; returns a string representing a file that
12838 can be opened on the remote side to get the symbols for the child
12839 process. Returns NULL if the operation is not supported. */
12840
12841 static char *
12842 remote_pid_to_exec_file (struct target_ops *self, int pid)
12843 {
12844 static char *filename = NULL;
12845 struct inferior *inf;
12846 char *annex = NULL;
12847
12848 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12849 return NULL;
12850
12851 if (filename != NULL)
12852 xfree (filename);
12853
12854 inf = find_inferior_pid (pid);
12855 if (inf == NULL)
12856 internal_error (__FILE__, __LINE__,
12857 _("not currently attached to process %d"), pid);
12858
12859 if (!inf->fake_pid_p)
12860 {
12861 const int annex_size = 9;
12862
12863 annex = (char *) alloca (annex_size);
12864 xsnprintf (annex, annex_size, "%x", pid);
12865 }
12866
12867 filename = target_read_stralloc (&current_target,
12868 TARGET_OBJECT_EXEC_FILE, annex);
12869
12870 return filename;
12871 }
12872
12873 /* Implement the to_can_do_single_step target_ops method. */
12874
12875 static int
12876 remote_can_do_single_step (struct target_ops *ops)
12877 {
12878 /* We can only tell whether target supports single step or not by
12879 supported s and S vCont actions if the stub supports vContSupported
12880 feature. If the stub doesn't support vContSupported feature,
12881 we have conservatively to think target doesn't supports single
12882 step. */
12883 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12884 {
12885 struct remote_state *rs = get_remote_state ();
12886
12887 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12888 remote_vcont_probe (rs);
12889
12890 return rs->supports_vCont.s && rs->supports_vCont.S;
12891 }
12892 else
12893 return 0;
12894 }
12895
12896 static void
12897 init_remote_ops (void)
12898 {
12899 remote_ops.to_shortname = "remote";
12900 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12901 remote_ops.to_doc =
12902 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12903 Specify the serial device it is connected to\n\
12904 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12905 remote_ops.to_open = remote_open;
12906 remote_ops.to_close = remote_close;
12907 remote_ops.to_detach = remote_detach;
12908 remote_ops.to_disconnect = remote_disconnect;
12909 remote_ops.to_resume = remote_resume;
12910 remote_ops.to_wait = remote_wait;
12911 remote_ops.to_fetch_registers = remote_fetch_registers;
12912 remote_ops.to_store_registers = remote_store_registers;
12913 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12914 remote_ops.to_files_info = remote_files_info;
12915 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12916 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12917 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12918 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12919 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12920 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12921 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12922 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12923 remote_ops.to_watchpoint_addr_within_range =
12924 remote_watchpoint_addr_within_range;
12925 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12926 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12927 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12928 remote_ops.to_region_ok_for_hw_watchpoint
12929 = remote_region_ok_for_hw_watchpoint;
12930 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12931 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12932 remote_ops.to_kill = remote_kill;
12933 remote_ops.to_load = remote_load;
12934 remote_ops.to_mourn_inferior = remote_mourn;
12935 remote_ops.to_pass_signals = remote_pass_signals;
12936 remote_ops.to_program_signals = remote_program_signals;
12937 remote_ops.to_thread_alive = remote_thread_alive;
12938 remote_ops.to_thread_name = remote_thread_name;
12939 remote_ops.to_update_thread_list = remote_update_thread_list;
12940 remote_ops.to_pid_to_str = remote_pid_to_str;
12941 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12942 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12943 remote_ops.to_stop = remote_stop;
12944 remote_ops.to_interrupt = remote_interrupt;
12945 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12946 remote_ops.to_xfer_partial = remote_xfer_partial;
12947 remote_ops.to_rcmd = remote_rcmd;
12948 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12949 remote_ops.to_log_command = serial_log_command;
12950 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12951 remote_ops.to_stratum = process_stratum;
12952 remote_ops.to_has_all_memory = default_child_has_all_memory;
12953 remote_ops.to_has_memory = default_child_has_memory;
12954 remote_ops.to_has_stack = default_child_has_stack;
12955 remote_ops.to_has_registers = default_child_has_registers;
12956 remote_ops.to_has_execution = default_child_has_execution;
12957 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12958 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12959 remote_ops.to_magic = OPS_MAGIC;
12960 remote_ops.to_memory_map = remote_memory_map;
12961 remote_ops.to_flash_erase = remote_flash_erase;
12962 remote_ops.to_flash_done = remote_flash_done;
12963 remote_ops.to_read_description = remote_read_description;
12964 remote_ops.to_search_memory = remote_search_memory;
12965 remote_ops.to_can_async_p = remote_can_async_p;
12966 remote_ops.to_is_async_p = remote_is_async_p;
12967 remote_ops.to_async = remote_async;
12968 remote_ops.to_can_do_single_step = remote_can_do_single_step;
12969 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12970 remote_ops.to_terminal_ours = remote_terminal_ours;
12971 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12972 remote_ops.to_supports_multi_process = remote_supports_multi_process;
12973 remote_ops.to_supports_disable_randomization
12974 = remote_supports_disable_randomization;
12975 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12976 remote_ops.to_fileio_open = remote_hostio_open;
12977 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12978 remote_ops.to_fileio_pread = remote_hostio_pread;
12979 remote_ops.to_fileio_fstat = remote_hostio_fstat;
12980 remote_ops.to_fileio_close = remote_hostio_close;
12981 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12982 remote_ops.to_fileio_readlink = remote_hostio_readlink;
12983 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12984 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12985 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12986 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12987 remote_ops.to_trace_init = remote_trace_init;
12988 remote_ops.to_download_tracepoint = remote_download_tracepoint;
12989 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12990 remote_ops.to_download_trace_state_variable
12991 = remote_download_trace_state_variable;
12992 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12993 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12994 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12995 remote_ops.to_trace_start = remote_trace_start;
12996 remote_ops.to_get_trace_status = remote_get_trace_status;
12997 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12998 remote_ops.to_trace_stop = remote_trace_stop;
12999 remote_ops.to_trace_find = remote_trace_find;
13000 remote_ops.to_get_trace_state_variable_value
13001 = remote_get_trace_state_variable_value;
13002 remote_ops.to_save_trace_data = remote_save_trace_data;
13003 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13004 remote_ops.to_upload_trace_state_variables
13005 = remote_upload_trace_state_variables;
13006 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13007 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13008 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13009 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13010 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13011 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13012 remote_ops.to_core_of_thread = remote_core_of_thread;
13013 remote_ops.to_verify_memory = remote_verify_memory;
13014 remote_ops.to_get_tib_address = remote_get_tib_address;
13015 remote_ops.to_set_permissions = remote_set_permissions;
13016 remote_ops.to_static_tracepoint_marker_at
13017 = remote_static_tracepoint_marker_at;
13018 remote_ops.to_static_tracepoint_markers_by_strid
13019 = remote_static_tracepoint_markers_by_strid;
13020 remote_ops.to_traceframe_info = remote_traceframe_info;
13021 remote_ops.to_use_agent = remote_use_agent;
13022 remote_ops.to_can_use_agent = remote_can_use_agent;
13023 remote_ops.to_supports_btrace = remote_supports_btrace;
13024 remote_ops.to_enable_btrace = remote_enable_btrace;
13025 remote_ops.to_disable_btrace = remote_disable_btrace;
13026 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13027 remote_ops.to_read_btrace = remote_read_btrace;
13028 remote_ops.to_btrace_conf = remote_btrace_conf;
13029 remote_ops.to_augmented_libraries_svr4_read =
13030 remote_augmented_libraries_svr4_read;
13031 }
13032
13033 /* Set up the extended remote vector by making a copy of the standard
13034 remote vector and adding to it. */
13035
13036 static void
13037 init_extended_remote_ops (void)
13038 {
13039 extended_remote_ops = remote_ops;
13040
13041 extended_remote_ops.to_shortname = "extended-remote";
13042 extended_remote_ops.to_longname =
13043 "Extended remote serial target in gdb-specific protocol";
13044 extended_remote_ops.to_doc =
13045 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13046 Specify the serial device it is connected to (e.g. /dev/ttya).";
13047 extended_remote_ops.to_open = extended_remote_open;
13048 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13049 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
13050 extended_remote_ops.to_detach = extended_remote_detach;
13051 extended_remote_ops.to_attach = extended_remote_attach;
13052 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13053 extended_remote_ops.to_kill = extended_remote_kill;
13054 extended_remote_ops.to_supports_disable_randomization
13055 = extended_remote_supports_disable_randomization;
13056 extended_remote_ops.to_follow_fork = remote_follow_fork;
13057 extended_remote_ops.to_follow_exec = remote_follow_exec;
13058 extended_remote_ops.to_insert_fork_catchpoint
13059 = remote_insert_fork_catchpoint;
13060 extended_remote_ops.to_remove_fork_catchpoint
13061 = remote_remove_fork_catchpoint;
13062 extended_remote_ops.to_insert_vfork_catchpoint
13063 = remote_insert_vfork_catchpoint;
13064 extended_remote_ops.to_remove_vfork_catchpoint
13065 = remote_remove_vfork_catchpoint;
13066 extended_remote_ops.to_insert_exec_catchpoint
13067 = remote_insert_exec_catchpoint;
13068 extended_remote_ops.to_remove_exec_catchpoint
13069 = remote_remove_exec_catchpoint;
13070 }
13071
13072 static int
13073 remote_can_async_p (struct target_ops *ops)
13074 {
13075 struct remote_state *rs = get_remote_state ();
13076
13077 if (!target_async_permitted)
13078 /* We only enable async when the user specifically asks for it. */
13079 return 0;
13080
13081 /* We're async whenever the serial device is. */
13082 return serial_can_async_p (rs->remote_desc);
13083 }
13084
13085 static int
13086 remote_is_async_p (struct target_ops *ops)
13087 {
13088 struct remote_state *rs = get_remote_state ();
13089
13090 if (!target_async_permitted)
13091 /* We only enable async when the user specifically asks for it. */
13092 return 0;
13093
13094 /* We're async whenever the serial device is. */
13095 return serial_is_async_p (rs->remote_desc);
13096 }
13097
13098 /* Pass the SERIAL event on and up to the client. One day this code
13099 will be able to delay notifying the client of an event until the
13100 point where an entire packet has been received. */
13101
13102 static serial_event_ftype remote_async_serial_handler;
13103
13104 static void
13105 remote_async_serial_handler (struct serial *scb, void *context)
13106 {
13107 struct remote_state *rs = (struct remote_state *) context;
13108
13109 /* Don't propogate error information up to the client. Instead let
13110 the client find out about the error by querying the target. */
13111 inferior_event_handler (INF_REG_EVENT, NULL);
13112 }
13113
13114 static void
13115 remote_async_inferior_event_handler (gdb_client_data data)
13116 {
13117 inferior_event_handler (INF_REG_EVENT, NULL);
13118 }
13119
13120 static void
13121 remote_async (struct target_ops *ops, int enable)
13122 {
13123 struct remote_state *rs = get_remote_state ();
13124
13125 if (enable)
13126 {
13127 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13128
13129 /* If there are pending events in the stop reply queue tell the
13130 event loop to process them. */
13131 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13132 mark_async_event_handler (remote_async_inferior_event_token);
13133 /* For simplicity, below we clear the pending events token
13134 without remembering whether it is marked, so here we always
13135 mark it. If there's actually no pending notification to
13136 process, this ends up being a no-op (other than a spurious
13137 event-loop wakeup). */
13138 if (target_is_non_stop_p ())
13139 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13140 }
13141 else
13142 {
13143 serial_async (rs->remote_desc, NULL, NULL);
13144 /* If the core is disabling async, it doesn't want to be
13145 disturbed with target events. Clear all async event sources
13146 too. */
13147 clear_async_event_handler (remote_async_inferior_event_token);
13148 if (target_is_non_stop_p ())
13149 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13150 }
13151 }
13152
13153 static void
13154 set_remote_cmd (char *args, int from_tty)
13155 {
13156 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13157 }
13158
13159 static void
13160 show_remote_cmd (char *args, int from_tty)
13161 {
13162 /* We can't just use cmd_show_list here, because we want to skip
13163 the redundant "show remote Z-packet" and the legacy aliases. */
13164 struct cleanup *showlist_chain;
13165 struct cmd_list_element *list = remote_show_cmdlist;
13166 struct ui_out *uiout = current_uiout;
13167
13168 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13169 for (; list != NULL; list = list->next)
13170 if (strcmp (list->name, "Z-packet") == 0)
13171 continue;
13172 else if (list->type == not_set_cmd)
13173 /* Alias commands are exactly like the original, except they
13174 don't have the normal type. */
13175 continue;
13176 else
13177 {
13178 struct cleanup *option_chain
13179 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13180
13181 ui_out_field_string (uiout, "name", list->name);
13182 ui_out_text (uiout, ": ");
13183 if (list->type == show_cmd)
13184 do_show_command ((char *) NULL, from_tty, list);
13185 else
13186 cmd_func (list, NULL, from_tty);
13187 /* Close the tuple. */
13188 do_cleanups (option_chain);
13189 }
13190
13191 /* Close the tuple. */
13192 do_cleanups (showlist_chain);
13193 }
13194
13195
13196 /* Function to be called whenever a new objfile (shlib) is detected. */
13197 static void
13198 remote_new_objfile (struct objfile *objfile)
13199 {
13200 struct remote_state *rs = get_remote_state ();
13201
13202 if (rs->remote_desc != 0) /* Have a remote connection. */
13203 remote_check_symbols ();
13204 }
13205
13206 /* Pull all the tracepoints defined on the target and create local
13207 data structures representing them. We don't want to create real
13208 tracepoints yet, we don't want to mess up the user's existing
13209 collection. */
13210
13211 static int
13212 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13213 {
13214 struct remote_state *rs = get_remote_state ();
13215 char *p;
13216
13217 /* Ask for a first packet of tracepoint definition. */
13218 putpkt ("qTfP");
13219 getpkt (&rs->buf, &rs->buf_size, 0);
13220 p = rs->buf;
13221 while (*p && *p != 'l')
13222 {
13223 parse_tracepoint_definition (p, utpp);
13224 /* Ask for another packet of tracepoint definition. */
13225 putpkt ("qTsP");
13226 getpkt (&rs->buf, &rs->buf_size, 0);
13227 p = rs->buf;
13228 }
13229 return 0;
13230 }
13231
13232 static int
13233 remote_upload_trace_state_variables (struct target_ops *self,
13234 struct uploaded_tsv **utsvp)
13235 {
13236 struct remote_state *rs = get_remote_state ();
13237 char *p;
13238
13239 /* Ask for a first packet of variable definition. */
13240 putpkt ("qTfV");
13241 getpkt (&rs->buf, &rs->buf_size, 0);
13242 p = rs->buf;
13243 while (*p && *p != 'l')
13244 {
13245 parse_tsv_definition (p, utsvp);
13246 /* Ask for another packet of variable definition. */
13247 putpkt ("qTsV");
13248 getpkt (&rs->buf, &rs->buf_size, 0);
13249 p = rs->buf;
13250 }
13251 return 0;
13252 }
13253
13254 /* The "set/show range-stepping" show hook. */
13255
13256 static void
13257 show_range_stepping (struct ui_file *file, int from_tty,
13258 struct cmd_list_element *c,
13259 const char *value)
13260 {
13261 fprintf_filtered (file,
13262 _("Debugger's willingness to use range stepping "
13263 "is %s.\n"), value);
13264 }
13265
13266 /* The "set/show range-stepping" set hook. */
13267
13268 static void
13269 set_range_stepping (char *ignore_args, int from_tty,
13270 struct cmd_list_element *c)
13271 {
13272 struct remote_state *rs = get_remote_state ();
13273
13274 /* Whene enabling, check whether range stepping is actually
13275 supported by the target, and warn if not. */
13276 if (use_range_stepping)
13277 {
13278 if (rs->remote_desc != NULL)
13279 {
13280 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13281 remote_vcont_probe (rs);
13282
13283 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13284 && rs->supports_vCont.r)
13285 return;
13286 }
13287
13288 warning (_("Range stepping is not supported by the current target"));
13289 }
13290 }
13291
13292 void
13293 _initialize_remote (void)
13294 {
13295 struct remote_state *rs;
13296 struct cmd_list_element *cmd;
13297 const char *cmd_name;
13298
13299 /* architecture specific data */
13300 remote_gdbarch_data_handle =
13301 gdbarch_data_register_post_init (init_remote_state);
13302 remote_g_packet_data_handle =
13303 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13304
13305 remote_pspace_data
13306 = register_program_space_data_with_cleanup (NULL,
13307 remote_pspace_data_cleanup);
13308
13309 /* Initialize the per-target state. At the moment there is only one
13310 of these, not one per target. Only one target is active at a
13311 time. */
13312 remote_state = new_remote_state ();
13313
13314 init_remote_ops ();
13315 add_target (&remote_ops);
13316
13317 init_extended_remote_ops ();
13318 add_target (&extended_remote_ops);
13319
13320 /* Hook into new objfile notification. */
13321 observer_attach_new_objfile (remote_new_objfile);
13322 /* We're no longer interested in notification events of an inferior
13323 when it exits. */
13324 observer_attach_inferior_exit (discard_pending_stop_replies);
13325
13326 /* Set up signal handlers. */
13327 async_sigint_remote_token =
13328 create_async_signal_handler (async_remote_interrupt, NULL);
13329 async_sigint_remote_twice_token =
13330 create_async_signal_handler (async_remote_interrupt_twice, NULL);
13331
13332 #if 0
13333 init_remote_threadtests ();
13334 #endif
13335
13336 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13337 /* set/show remote ... */
13338
13339 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13340 Remote protocol specific variables\n\
13341 Configure various remote-protocol specific variables such as\n\
13342 the packets being used"),
13343 &remote_set_cmdlist, "set remote ",
13344 0 /* allow-unknown */, &setlist);
13345 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13346 Remote protocol specific variables\n\
13347 Configure various remote-protocol specific variables such as\n\
13348 the packets being used"),
13349 &remote_show_cmdlist, "show remote ",
13350 0 /* allow-unknown */, &showlist);
13351
13352 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13353 Compare section data on target to the exec file.\n\
13354 Argument is a single section name (default: all loaded sections).\n\
13355 To compare only read-only loaded sections, specify the -r option."),
13356 &cmdlist);
13357
13358 add_cmd ("packet", class_maintenance, packet_command, _("\
13359 Send an arbitrary packet to a remote target.\n\
13360 maintenance packet TEXT\n\
13361 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13362 this command sends the string TEXT to the inferior, and displays the\n\
13363 response packet. GDB supplies the initial `$' character, and the\n\
13364 terminating `#' character and checksum."),
13365 &maintenancelist);
13366
13367 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13368 Set whether to send break if interrupted."), _("\
13369 Show whether to send break if interrupted."), _("\
13370 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13371 set_remotebreak, show_remotebreak,
13372 &setlist, &showlist);
13373 cmd_name = "remotebreak";
13374 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13375 deprecate_cmd (cmd, "set remote interrupt-sequence");
13376 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13377 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13378 deprecate_cmd (cmd, "show remote interrupt-sequence");
13379
13380 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13381 interrupt_sequence_modes, &interrupt_sequence_mode,
13382 _("\
13383 Set interrupt sequence to remote target."), _("\
13384 Show interrupt sequence to remote target."), _("\
13385 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13386 NULL, show_interrupt_sequence,
13387 &remote_set_cmdlist,
13388 &remote_show_cmdlist);
13389
13390 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13391 &interrupt_on_connect, _("\
13392 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13393 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13394 If set, interrupt sequence is sent to remote target."),
13395 NULL, NULL,
13396 &remote_set_cmdlist, &remote_show_cmdlist);
13397
13398 /* Install commands for configuring memory read/write packets. */
13399
13400 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13401 Set the maximum number of bytes per memory write packet (deprecated)."),
13402 &setlist);
13403 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13404 Show the maximum number of bytes per memory write packet (deprecated)."),
13405 &showlist);
13406 add_cmd ("memory-write-packet-size", no_class,
13407 set_memory_write_packet_size, _("\
13408 Set the maximum number of bytes per memory-write packet.\n\
13409 Specify the number of bytes in a packet or 0 (zero) for the\n\
13410 default packet size. The actual limit is further reduced\n\
13411 dependent on the target. Specify ``fixed'' to disable the\n\
13412 further restriction and ``limit'' to enable that restriction."),
13413 &remote_set_cmdlist);
13414 add_cmd ("memory-read-packet-size", no_class,
13415 set_memory_read_packet_size, _("\
13416 Set the maximum number of bytes per memory-read packet.\n\
13417 Specify the number of bytes in a packet or 0 (zero) for the\n\
13418 default packet size. The actual limit is further reduced\n\
13419 dependent on the target. Specify ``fixed'' to disable the\n\
13420 further restriction and ``limit'' to enable that restriction."),
13421 &remote_set_cmdlist);
13422 add_cmd ("memory-write-packet-size", no_class,
13423 show_memory_write_packet_size,
13424 _("Show the maximum number of bytes per memory-write packet."),
13425 &remote_show_cmdlist);
13426 add_cmd ("memory-read-packet-size", no_class,
13427 show_memory_read_packet_size,
13428 _("Show the maximum number of bytes per memory-read packet."),
13429 &remote_show_cmdlist);
13430
13431 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13432 &remote_hw_watchpoint_limit, _("\
13433 Set the maximum number of target hardware watchpoints."), _("\
13434 Show the maximum number of target hardware watchpoints."), _("\
13435 Specify a negative limit for unlimited."),
13436 NULL, NULL, /* FIXME: i18n: The maximum
13437 number of target hardware
13438 watchpoints is %s. */
13439 &remote_set_cmdlist, &remote_show_cmdlist);
13440 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13441 &remote_hw_watchpoint_length_limit, _("\
13442 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13443 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13444 Specify a negative limit for unlimited."),
13445 NULL, NULL, /* FIXME: i18n: The maximum
13446 length (in bytes) of a target
13447 hardware watchpoint is %s. */
13448 &remote_set_cmdlist, &remote_show_cmdlist);
13449 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13450 &remote_hw_breakpoint_limit, _("\
13451 Set the maximum number of target hardware breakpoints."), _("\
13452 Show the maximum number of target hardware breakpoints."), _("\
13453 Specify a negative limit for unlimited."),
13454 NULL, NULL, /* FIXME: i18n: The maximum
13455 number of target hardware
13456 breakpoints is %s. */
13457 &remote_set_cmdlist, &remote_show_cmdlist);
13458
13459 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13460 &remote_address_size, _("\
13461 Set the maximum size of the address (in bits) in a memory packet."), _("\
13462 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13463 NULL,
13464 NULL, /* FIXME: i18n: */
13465 &setlist, &showlist);
13466
13467 init_all_packet_configs ();
13468
13469 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13470 "X", "binary-download", 1);
13471
13472 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13473 "vCont", "verbose-resume", 0);
13474
13475 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13476 "QPassSignals", "pass-signals", 0);
13477
13478 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13479 "QProgramSignals", "program-signals", 0);
13480
13481 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13482 "qSymbol", "symbol-lookup", 0);
13483
13484 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13485 "P", "set-register", 1);
13486
13487 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13488 "p", "fetch-register", 1);
13489
13490 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13491 "Z0", "software-breakpoint", 0);
13492
13493 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13494 "Z1", "hardware-breakpoint", 0);
13495
13496 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13497 "Z2", "write-watchpoint", 0);
13498
13499 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13500 "Z3", "read-watchpoint", 0);
13501
13502 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13503 "Z4", "access-watchpoint", 0);
13504
13505 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13506 "qXfer:auxv:read", "read-aux-vector", 0);
13507
13508 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13509 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13510
13511 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13512 "qXfer:features:read", "target-features", 0);
13513
13514 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13515 "qXfer:libraries:read", "library-info", 0);
13516
13517 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13518 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13519
13520 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13521 "qXfer:memory-map:read", "memory-map", 0);
13522
13523 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13524 "qXfer:spu:read", "read-spu-object", 0);
13525
13526 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13527 "qXfer:spu:write", "write-spu-object", 0);
13528
13529 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13530 "qXfer:osdata:read", "osdata", 0);
13531
13532 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13533 "qXfer:threads:read", "threads", 0);
13534
13535 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13536 "qXfer:siginfo:read", "read-siginfo-object", 0);
13537
13538 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13539 "qXfer:siginfo:write", "write-siginfo-object", 0);
13540
13541 add_packet_config_cmd
13542 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13543 "qXfer:traceframe-info:read", "traceframe-info", 0);
13544
13545 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13546 "qXfer:uib:read", "unwind-info-block", 0);
13547
13548 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13549 "qGetTLSAddr", "get-thread-local-storage-address",
13550 0);
13551
13552 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13553 "qGetTIBAddr", "get-thread-information-block-address",
13554 0);
13555
13556 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13557 "bc", "reverse-continue", 0);
13558
13559 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13560 "bs", "reverse-step", 0);
13561
13562 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13563 "qSupported", "supported-packets", 0);
13564
13565 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13566 "qSearch:memory", "search-memory", 0);
13567
13568 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13569 "qTStatus", "trace-status", 0);
13570
13571 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13572 "vFile:setfs", "hostio-setfs", 0);
13573
13574 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13575 "vFile:open", "hostio-open", 0);
13576
13577 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13578 "vFile:pread", "hostio-pread", 0);
13579
13580 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13581 "vFile:pwrite", "hostio-pwrite", 0);
13582
13583 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13584 "vFile:close", "hostio-close", 0);
13585
13586 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13587 "vFile:unlink", "hostio-unlink", 0);
13588
13589 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13590 "vFile:readlink", "hostio-readlink", 0);
13591
13592 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13593 "vFile:fstat", "hostio-fstat", 0);
13594
13595 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13596 "vAttach", "attach", 0);
13597
13598 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13599 "vRun", "run", 0);
13600
13601 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13602 "QStartNoAckMode", "noack", 0);
13603
13604 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13605 "vKill", "kill", 0);
13606
13607 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13608 "qAttached", "query-attached", 0);
13609
13610 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13611 "ConditionalTracepoints",
13612 "conditional-tracepoints", 0);
13613
13614 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13615 "ConditionalBreakpoints",
13616 "conditional-breakpoints", 0);
13617
13618 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13619 "BreakpointCommands",
13620 "breakpoint-commands", 0);
13621
13622 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13623 "FastTracepoints", "fast-tracepoints", 0);
13624
13625 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13626 "TracepointSource", "TracepointSource", 0);
13627
13628 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13629 "QAllow", "allow", 0);
13630
13631 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13632 "StaticTracepoints", "static-tracepoints", 0);
13633
13634 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13635 "InstallInTrace", "install-in-trace", 0);
13636
13637 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13638 "qXfer:statictrace:read", "read-sdata-object", 0);
13639
13640 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13641 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13642
13643 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13644 "QDisableRandomization", "disable-randomization", 0);
13645
13646 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13647 "QAgent", "agent", 0);
13648
13649 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13650 "QTBuffer:size", "trace-buffer-size", 0);
13651
13652 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13653 "Qbtrace:off", "disable-btrace", 0);
13654
13655 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13656 "Qbtrace:bts", "enable-btrace-bts", 0);
13657
13658 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13659 "Qbtrace:pt", "enable-btrace-pt", 0);
13660
13661 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13662 "qXfer:btrace", "read-btrace", 0);
13663
13664 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13665 "qXfer:btrace-conf", "read-btrace-conf", 0);
13666
13667 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13668 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13669
13670 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13671 "multiprocess-feature", "multiprocess-feature", 0);
13672
13673 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13674 "swbreak-feature", "swbreak-feature", 0);
13675
13676 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13677 "hwbreak-feature", "hwbreak-feature", 0);
13678
13679 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13680 "fork-event-feature", "fork-event-feature", 0);
13681
13682 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13683 "vfork-event-feature", "vfork-event-feature", 0);
13684
13685 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13686 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13687
13688 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13689 "vContSupported", "verbose-resume-supported", 0);
13690
13691 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13692 "exec-event-feature", "exec-event-feature", 0);
13693
13694 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13695 "vCtrlC", "ctrl-c", 0);
13696
13697 /* Assert that we've registered "set remote foo-packet" commands
13698 for all packet configs. */
13699 {
13700 int i;
13701
13702 for (i = 0; i < PACKET_MAX; i++)
13703 {
13704 /* Ideally all configs would have a command associated. Some
13705 still don't though. */
13706 int excepted;
13707
13708 switch (i)
13709 {
13710 case PACKET_QNonStop:
13711 case PACKET_EnableDisableTracepoints_feature:
13712 case PACKET_tracenz_feature:
13713 case PACKET_DisconnectedTracing_feature:
13714 case PACKET_augmented_libraries_svr4_read_feature:
13715 case PACKET_qCRC:
13716 /* Additions to this list need to be well justified:
13717 pre-existing packets are OK; new packets are not. */
13718 excepted = 1;
13719 break;
13720 default:
13721 excepted = 0;
13722 break;
13723 }
13724
13725 /* This catches both forgetting to add a config command, and
13726 forgetting to remove a packet from the exception list. */
13727 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13728 }
13729 }
13730
13731 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13732 Z sub-packet has its own set and show commands, but users may
13733 have sets to this variable in their .gdbinit files (or in their
13734 documentation). */
13735 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13736 &remote_Z_packet_detect, _("\
13737 Set use of remote protocol `Z' packets"), _("\
13738 Show use of remote protocol `Z' packets "), _("\
13739 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13740 packets."),
13741 set_remote_protocol_Z_packet_cmd,
13742 show_remote_protocol_Z_packet_cmd,
13743 /* FIXME: i18n: Use of remote protocol
13744 `Z' packets is %s. */
13745 &remote_set_cmdlist, &remote_show_cmdlist);
13746
13747 add_prefix_cmd ("remote", class_files, remote_command, _("\
13748 Manipulate files on the remote system\n\
13749 Transfer files to and from the remote target system."),
13750 &remote_cmdlist, "remote ",
13751 0 /* allow-unknown */, &cmdlist);
13752
13753 add_cmd ("put", class_files, remote_put_command,
13754 _("Copy a local file to the remote system."),
13755 &remote_cmdlist);
13756
13757 add_cmd ("get", class_files, remote_get_command,
13758 _("Copy a remote file to the local system."),
13759 &remote_cmdlist);
13760
13761 add_cmd ("delete", class_files, remote_delete_command,
13762 _("Delete a remote file."),
13763 &remote_cmdlist);
13764
13765 add_setshow_string_noescape_cmd ("exec-file", class_files,
13766 &remote_exec_file_var, _("\
13767 Set the remote pathname for \"run\""), _("\
13768 Show the remote pathname for \"run\""), NULL,
13769 set_remote_exec_file,
13770 show_remote_exec_file,
13771 &remote_set_cmdlist,
13772 &remote_show_cmdlist);
13773
13774 add_setshow_boolean_cmd ("range-stepping", class_run,
13775 &use_range_stepping, _("\
13776 Enable or disable range stepping."), _("\
13777 Show whether target-assisted range stepping is enabled."), _("\
13778 If on, and the target supports it, when stepping a source line, GDB\n\
13779 tells the target to step the corresponding range of addresses itself instead\n\
13780 of issuing multiple single-steps. This speeds up source level\n\
13781 stepping. If off, GDB always issues single-steps, even if range\n\
13782 stepping is supported by the target. The default is on."),
13783 set_range_stepping,
13784 show_range_stepping,
13785 &setlist,
13786 &showlist);
13787
13788 /* Eventually initialize fileio. See fileio.c */
13789 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13790
13791 /* Take advantage of the fact that the TID field is not used, to tag
13792 special ptids with it set to != 0. */
13793 magic_null_ptid = ptid_build (42000, -1, 1);
13794 not_sent_ptid = ptid_build (42000, -2, 1);
13795 any_thread_ptid = ptid_build (42000, 0, 1);
13796
13797 target_buf_size = 2048;
13798 target_buf = (char *) xmalloc (target_buf_size);
13799 }
13800