gdbserver crash running gdb.threads/non-ldr-exc-1.exp
[deliverable/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 /* This is set to the data address of the access causing the target
405 to stop for a watchpoint. */
406 CORE_ADDR remote_watch_data_address;
407
408 /* Whether the target stopped for a breakpoint/watchpoint. */
409 enum target_stop_reason stop_reason;
410
411 threadref echo_nextthread;
412 threadref nextthread;
413 threadref resultthreadlist[MAXTHREADLISTRESULTS];
414
415 /* The state of remote notification. */
416 struct remote_notif_state *notif_state;
417
418 /* The branch trace configuration. */
419 struct btrace_config btrace_config;
420
421 /* The argument to the last "vFile:setfs:" packet we sent, used
422 to avoid sending repeated unnecessary "vFile:setfs:" packets.
423 Initialized to -1 to indicate that no "vFile:setfs:" packet
424 has yet been sent. */
425 int fs_pid;
426
427 /* A readahead cache for vFile:pread. Often, reading a binary
428 involves a sequence of small reads. E.g., when parsing an ELF
429 file. A readahead cache helps mostly the case of remote
430 debugging on a connection with higher latency, due to the
431 request/reply nature of the RSP. We only cache data for a single
432 file descriptor at a time. */
433 struct readahead_cache readahead_cache;
434 };
435
436 /* Private data that we'll store in (struct thread_info)->private. */
437 struct private_thread_info
438 {
439 char *extra;
440 char *name;
441 int core;
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 PACKET_MAX
1484 };
1485
1486 static struct packet_config remote_protocol_packets[PACKET_MAX];
1487
1488 /* Returns the packet's corresponding "set remote foo-packet" command
1489 state. See struct packet_config for more details. */
1490
1491 static enum auto_boolean
1492 packet_set_cmd_state (int packet)
1493 {
1494 return remote_protocol_packets[packet].detect;
1495 }
1496
1497 /* Returns whether a given packet or feature is supported. This takes
1498 into account the state of the corresponding "set remote foo-packet"
1499 command, which may be used to bypass auto-detection. */
1500
1501 static enum packet_support
1502 packet_config_support (struct packet_config *config)
1503 {
1504 switch (config->detect)
1505 {
1506 case AUTO_BOOLEAN_TRUE:
1507 return PACKET_ENABLE;
1508 case AUTO_BOOLEAN_FALSE:
1509 return PACKET_DISABLE;
1510 case AUTO_BOOLEAN_AUTO:
1511 return config->support;
1512 default:
1513 gdb_assert_not_reached (_("bad switch"));
1514 }
1515 }
1516
1517 /* Same as packet_config_support, but takes the packet's enum value as
1518 argument. */
1519
1520 static enum packet_support
1521 packet_support (int packet)
1522 {
1523 struct packet_config *config = &remote_protocol_packets[packet];
1524
1525 return packet_config_support (config);
1526 }
1527
1528 static void
1529 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1530 struct cmd_list_element *c,
1531 const char *value)
1532 {
1533 struct packet_config *packet;
1534
1535 for (packet = remote_protocol_packets;
1536 packet < &remote_protocol_packets[PACKET_MAX];
1537 packet++)
1538 {
1539 if (&packet->detect == c->var)
1540 {
1541 show_packet_config_cmd (packet);
1542 return;
1543 }
1544 }
1545 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1546 c->name);
1547 }
1548
1549 /* Should we try one of the 'Z' requests? */
1550
1551 enum Z_packet_type
1552 {
1553 Z_PACKET_SOFTWARE_BP,
1554 Z_PACKET_HARDWARE_BP,
1555 Z_PACKET_WRITE_WP,
1556 Z_PACKET_READ_WP,
1557 Z_PACKET_ACCESS_WP,
1558 NR_Z_PACKET_TYPES
1559 };
1560
1561 /* For compatibility with older distributions. Provide a ``set remote
1562 Z-packet ...'' command that updates all the Z packet types. */
1563
1564 static enum auto_boolean remote_Z_packet_detect;
1565
1566 static void
1567 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1568 struct cmd_list_element *c)
1569 {
1570 int i;
1571
1572 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1573 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1574 }
1575
1576 static void
1577 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1578 struct cmd_list_element *c,
1579 const char *value)
1580 {
1581 int i;
1582
1583 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1584 {
1585 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1586 }
1587 }
1588
1589 /* Returns true if the multi-process extensions are in effect. */
1590
1591 static int
1592 remote_multi_process_p (struct remote_state *rs)
1593 {
1594 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1595 }
1596
1597 /* Returns true if fork events are supported. */
1598
1599 static int
1600 remote_fork_event_p (struct remote_state *rs)
1601 {
1602 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1603 }
1604
1605 /* Returns true if vfork events are supported. */
1606
1607 static int
1608 remote_vfork_event_p (struct remote_state *rs)
1609 {
1610 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1611 }
1612
1613 /* Returns true if exec events are supported. */
1614
1615 static int
1616 remote_exec_event_p (struct remote_state *rs)
1617 {
1618 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1619 }
1620
1621 /* Insert fork catchpoint target routine. If fork events are enabled
1622 then return success, nothing more to do. */
1623
1624 static int
1625 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1626 {
1627 struct remote_state *rs = get_remote_state ();
1628
1629 return !remote_fork_event_p (rs);
1630 }
1631
1632 /* Remove fork catchpoint target routine. Nothing to do, just
1633 return success. */
1634
1635 static int
1636 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1637 {
1638 return 0;
1639 }
1640
1641 /* Insert vfork catchpoint target routine. If vfork events are enabled
1642 then return success, nothing more to do. */
1643
1644 static int
1645 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1646 {
1647 struct remote_state *rs = get_remote_state ();
1648
1649 return !remote_vfork_event_p (rs);
1650 }
1651
1652 /* Remove vfork catchpoint target routine. Nothing to do, just
1653 return success. */
1654
1655 static int
1656 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1657 {
1658 return 0;
1659 }
1660
1661 /* Insert exec catchpoint target routine. If exec events are
1662 enabled, just return success. */
1663
1664 static int
1665 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1666 {
1667 struct remote_state *rs = get_remote_state ();
1668
1669 return !remote_exec_event_p (rs);
1670 }
1671
1672 /* Remove exec catchpoint target routine. Nothing to do, just
1673 return success. */
1674
1675 static int
1676 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1677 {
1678 return 0;
1679 }
1680
1681 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1682 static struct async_signal_handler *async_sigint_remote_twice_token;
1683 static struct async_signal_handler *async_sigint_remote_token;
1684
1685 \f
1686 /* Asynchronous signal handle registered as event loop source for
1687 when we have pending events ready to be passed to the core. */
1688
1689 static struct async_event_handler *remote_async_inferior_event_token;
1690
1691 \f
1692
1693 static ptid_t magic_null_ptid;
1694 static ptid_t not_sent_ptid;
1695 static ptid_t any_thread_ptid;
1696
1697 /* Find out if the stub attached to PID (and hence GDB should offer to
1698 detach instead of killing it when bailing out). */
1699
1700 static int
1701 remote_query_attached (int pid)
1702 {
1703 struct remote_state *rs = get_remote_state ();
1704 size_t size = get_remote_packet_size ();
1705
1706 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1707 return 0;
1708
1709 if (remote_multi_process_p (rs))
1710 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1711 else
1712 xsnprintf (rs->buf, size, "qAttached");
1713
1714 putpkt (rs->buf);
1715 getpkt (&rs->buf, &rs->buf_size, 0);
1716
1717 switch (packet_ok (rs->buf,
1718 &remote_protocol_packets[PACKET_qAttached]))
1719 {
1720 case PACKET_OK:
1721 if (strcmp (rs->buf, "1") == 0)
1722 return 1;
1723 break;
1724 case PACKET_ERROR:
1725 warning (_("Remote failure reply: %s"), rs->buf);
1726 break;
1727 case PACKET_UNKNOWN:
1728 break;
1729 }
1730
1731 return 0;
1732 }
1733
1734 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1735 has been invented by GDB, instead of reported by the target. Since
1736 we can be connected to a remote system before before knowing about
1737 any inferior, mark the target with execution when we find the first
1738 inferior. If ATTACHED is 1, then we had just attached to this
1739 inferior. If it is 0, then we just created this inferior. If it
1740 is -1, then try querying the remote stub to find out if it had
1741 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1742 attempt to open this inferior's executable as the main executable
1743 if no main executable is open already. */
1744
1745 static struct inferior *
1746 remote_add_inferior (int fake_pid_p, int pid, int attached,
1747 int try_open_exec)
1748 {
1749 struct inferior *inf;
1750
1751 /* Check whether this process we're learning about is to be
1752 considered attached, or if is to be considered to have been
1753 spawned by the stub. */
1754 if (attached == -1)
1755 attached = remote_query_attached (pid);
1756
1757 if (gdbarch_has_global_solist (target_gdbarch ()))
1758 {
1759 /* If the target shares code across all inferiors, then every
1760 attach adds a new inferior. */
1761 inf = add_inferior (pid);
1762
1763 /* ... and every inferior is bound to the same program space.
1764 However, each inferior may still have its own address
1765 space. */
1766 inf->aspace = maybe_new_address_space ();
1767 inf->pspace = current_program_space;
1768 }
1769 else
1770 {
1771 /* In the traditional debugging scenario, there's a 1-1 match
1772 between program/address spaces. We simply bind the inferior
1773 to the program space's address space. */
1774 inf = current_inferior ();
1775 inferior_appeared (inf, pid);
1776 }
1777
1778 inf->attach_flag = attached;
1779 inf->fake_pid_p = fake_pid_p;
1780
1781 /* If no main executable is currently open then attempt to
1782 open the file that was executed to create this inferior. */
1783 if (try_open_exec && get_exec_file (0) == NULL)
1784 exec_file_locate_attach (pid, 1);
1785
1786 return inf;
1787 }
1788
1789 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1790 according to RUNNING. */
1791
1792 static void
1793 remote_add_thread (ptid_t ptid, int running)
1794 {
1795 struct remote_state *rs = get_remote_state ();
1796
1797 /* GDB historically didn't pull threads in the initial connection
1798 setup. If the remote target doesn't even have a concept of
1799 threads (e.g., a bare-metal target), even if internally we
1800 consider that a single-threaded target, mentioning a new thread
1801 might be confusing to the user. Be silent then, preserving the
1802 age old behavior. */
1803 if (rs->starting_up)
1804 add_thread_silent (ptid);
1805 else
1806 add_thread (ptid);
1807
1808 set_executing (ptid, running);
1809 set_running (ptid, running);
1810 }
1811
1812 /* Come here when we learn about a thread id from the remote target.
1813 It may be the first time we hear about such thread, so take the
1814 opportunity to add it to GDB's thread list. In case this is the
1815 first time we're noticing its corresponding inferior, add it to
1816 GDB's inferior list as well. */
1817
1818 static void
1819 remote_notice_new_inferior (ptid_t currthread, int running)
1820 {
1821 /* If this is a new thread, add it to GDB's thread list.
1822 If we leave it up to WFI to do this, bad things will happen. */
1823
1824 if (in_thread_list (currthread) && is_exited (currthread))
1825 {
1826 /* We're seeing an event on a thread id we knew had exited.
1827 This has to be a new thread reusing the old id. Add it. */
1828 remote_add_thread (currthread, running);
1829 return;
1830 }
1831
1832 if (!in_thread_list (currthread))
1833 {
1834 struct inferior *inf = NULL;
1835 int pid = ptid_get_pid (currthread);
1836
1837 if (ptid_is_pid (inferior_ptid)
1838 && pid == ptid_get_pid (inferior_ptid))
1839 {
1840 /* inferior_ptid has no thread member yet. This can happen
1841 with the vAttach -> remote_wait,"TAAthread:" path if the
1842 stub doesn't support qC. This is the first stop reported
1843 after an attach, so this is the main thread. Update the
1844 ptid in the thread list. */
1845 if (in_thread_list (pid_to_ptid (pid)))
1846 thread_change_ptid (inferior_ptid, currthread);
1847 else
1848 {
1849 remote_add_thread (currthread, running);
1850 inferior_ptid = currthread;
1851 }
1852 return;
1853 }
1854
1855 if (ptid_equal (magic_null_ptid, inferior_ptid))
1856 {
1857 /* inferior_ptid is not set yet. This can happen with the
1858 vRun -> remote_wait,"TAAthread:" path if the stub
1859 doesn't support qC. This is the first stop reported
1860 after an attach, so this is the main thread. Update the
1861 ptid in the thread list. */
1862 thread_change_ptid (inferior_ptid, currthread);
1863 return;
1864 }
1865
1866 /* When connecting to a target remote, or to a target
1867 extended-remote which already was debugging an inferior, we
1868 may not know about it yet. Add it before adding its child
1869 thread, so notifications are emitted in a sensible order. */
1870 if (!in_inferior_list (ptid_get_pid (currthread)))
1871 {
1872 struct remote_state *rs = get_remote_state ();
1873 int fake_pid_p = !remote_multi_process_p (rs);
1874
1875 inf = remote_add_inferior (fake_pid_p,
1876 ptid_get_pid (currthread), -1, 1);
1877 }
1878
1879 /* This is really a new thread. Add it. */
1880 remote_add_thread (currthread, running);
1881
1882 /* If we found a new inferior, let the common code do whatever
1883 it needs to with it (e.g., read shared libraries, insert
1884 breakpoints), unless we're just setting up an all-stop
1885 connection. */
1886 if (inf != NULL)
1887 {
1888 struct remote_state *rs = get_remote_state ();
1889
1890 if (!rs->starting_up)
1891 notice_new_inferior (currthread, running, 0);
1892 }
1893 }
1894 }
1895
1896 /* Return the private thread data, creating it if necessary. */
1897
1898 static struct private_thread_info *
1899 demand_private_info (ptid_t ptid)
1900 {
1901 struct thread_info *info = find_thread_ptid (ptid);
1902
1903 gdb_assert (info);
1904
1905 if (!info->priv)
1906 {
1907 info->priv = XNEW (struct private_thread_info);
1908 info->private_dtor = free_private_thread_info;
1909 info->priv->core = -1;
1910 info->priv->extra = 0;
1911 }
1912
1913 return info->priv;
1914 }
1915
1916 /* Call this function as a result of
1917 1) A halt indication (T packet) containing a thread id
1918 2) A direct query of currthread
1919 3) Successful execution of set thread */
1920
1921 static void
1922 record_currthread (struct remote_state *rs, ptid_t currthread)
1923 {
1924 rs->general_thread = currthread;
1925 }
1926
1927 /* If 'QPassSignals' is supported, tell the remote stub what signals
1928 it can simply pass through to the inferior without reporting. */
1929
1930 static void
1931 remote_pass_signals (struct target_ops *self,
1932 int numsigs, unsigned char *pass_signals)
1933 {
1934 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1935 {
1936 char *pass_packet, *p;
1937 int count = 0, i;
1938 struct remote_state *rs = get_remote_state ();
1939
1940 gdb_assert (numsigs < 256);
1941 for (i = 0; i < numsigs; i++)
1942 {
1943 if (pass_signals[i])
1944 count++;
1945 }
1946 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1947 strcpy (pass_packet, "QPassSignals:");
1948 p = pass_packet + strlen (pass_packet);
1949 for (i = 0; i < numsigs; i++)
1950 {
1951 if (pass_signals[i])
1952 {
1953 if (i >= 16)
1954 *p++ = tohex (i >> 4);
1955 *p++ = tohex (i & 15);
1956 if (count)
1957 *p++ = ';';
1958 else
1959 break;
1960 count--;
1961 }
1962 }
1963 *p = 0;
1964 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1965 {
1966 putpkt (pass_packet);
1967 getpkt (&rs->buf, &rs->buf_size, 0);
1968 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1969 if (rs->last_pass_packet)
1970 xfree (rs->last_pass_packet);
1971 rs->last_pass_packet = pass_packet;
1972 }
1973 else
1974 xfree (pass_packet);
1975 }
1976 }
1977
1978 /* If 'QProgramSignals' is supported, tell the remote stub what
1979 signals it should pass through to the inferior when detaching. */
1980
1981 static void
1982 remote_program_signals (struct target_ops *self,
1983 int numsigs, unsigned char *signals)
1984 {
1985 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1986 {
1987 char *packet, *p;
1988 int count = 0, i;
1989 struct remote_state *rs = get_remote_state ();
1990
1991 gdb_assert (numsigs < 256);
1992 for (i = 0; i < numsigs; i++)
1993 {
1994 if (signals[i])
1995 count++;
1996 }
1997 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1998 strcpy (packet, "QProgramSignals:");
1999 p = packet + strlen (packet);
2000 for (i = 0; i < numsigs; i++)
2001 {
2002 if (signal_pass_state (i))
2003 {
2004 if (i >= 16)
2005 *p++ = tohex (i >> 4);
2006 *p++ = tohex (i & 15);
2007 if (count)
2008 *p++ = ';';
2009 else
2010 break;
2011 count--;
2012 }
2013 }
2014 *p = 0;
2015 if (!rs->last_program_signals_packet
2016 || strcmp (rs->last_program_signals_packet, packet) != 0)
2017 {
2018 putpkt (packet);
2019 getpkt (&rs->buf, &rs->buf_size, 0);
2020 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2021 xfree (rs->last_program_signals_packet);
2022 rs->last_program_signals_packet = packet;
2023 }
2024 else
2025 xfree (packet);
2026 }
2027 }
2028
2029 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2030 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2031 thread. If GEN is set, set the general thread, if not, then set
2032 the step/continue thread. */
2033 static void
2034 set_thread (struct ptid ptid, int gen)
2035 {
2036 struct remote_state *rs = get_remote_state ();
2037 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2038 char *buf = rs->buf;
2039 char *endbuf = rs->buf + get_remote_packet_size ();
2040
2041 if (ptid_equal (state, ptid))
2042 return;
2043
2044 *buf++ = 'H';
2045 *buf++ = gen ? 'g' : 'c';
2046 if (ptid_equal (ptid, magic_null_ptid))
2047 xsnprintf (buf, endbuf - buf, "0");
2048 else if (ptid_equal (ptid, any_thread_ptid))
2049 xsnprintf (buf, endbuf - buf, "0");
2050 else if (ptid_equal (ptid, minus_one_ptid))
2051 xsnprintf (buf, endbuf - buf, "-1");
2052 else
2053 write_ptid (buf, endbuf, ptid);
2054 putpkt (rs->buf);
2055 getpkt (&rs->buf, &rs->buf_size, 0);
2056 if (gen)
2057 rs->general_thread = ptid;
2058 else
2059 rs->continue_thread = ptid;
2060 }
2061
2062 static void
2063 set_general_thread (struct ptid ptid)
2064 {
2065 set_thread (ptid, 1);
2066 }
2067
2068 static void
2069 set_continue_thread (struct ptid ptid)
2070 {
2071 set_thread (ptid, 0);
2072 }
2073
2074 /* Change the remote current process. Which thread within the process
2075 ends up selected isn't important, as long as it is the same process
2076 as what INFERIOR_PTID points to.
2077
2078 This comes from that fact that there is no explicit notion of
2079 "selected process" in the protocol. The selected process for
2080 general operations is the process the selected general thread
2081 belongs to. */
2082
2083 static void
2084 set_general_process (void)
2085 {
2086 struct remote_state *rs = get_remote_state ();
2087
2088 /* If the remote can't handle multiple processes, don't bother. */
2089 if (!rs->extended || !remote_multi_process_p (rs))
2090 return;
2091
2092 /* We only need to change the remote current thread if it's pointing
2093 at some other process. */
2094 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2095 set_general_thread (inferior_ptid);
2096 }
2097
2098 \f
2099 /* Return nonzero if this is the main thread that we made up ourselves
2100 to model non-threaded targets as single-threaded. */
2101
2102 static int
2103 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2104 {
2105 struct remote_state *rs = get_remote_state ();
2106 char *p, *endp;
2107
2108 if (ptid_equal (ptid, magic_null_ptid))
2109 /* The main thread is always alive. */
2110 return 1;
2111
2112 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2113 /* The main thread is always alive. This can happen after a
2114 vAttach, if the remote side doesn't support
2115 multi-threading. */
2116 return 1;
2117
2118 return 0;
2119 }
2120
2121 /* Return nonzero if the thread PTID is still alive on the remote
2122 system. */
2123
2124 static int
2125 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2126 {
2127 struct remote_state *rs = get_remote_state ();
2128 char *p, *endp;
2129
2130 /* Check if this is a thread that we made up ourselves to model
2131 non-threaded targets as single-threaded. */
2132 if (remote_thread_always_alive (ops, ptid))
2133 return 1;
2134
2135 p = rs->buf;
2136 endp = rs->buf + get_remote_packet_size ();
2137
2138 *p++ = 'T';
2139 write_ptid (p, endp, ptid);
2140
2141 putpkt (rs->buf);
2142 getpkt (&rs->buf, &rs->buf_size, 0);
2143 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2144 }
2145
2146 /* Return a pointer to a thread name if we know it and NULL otherwise.
2147 The thread_info object owns the memory for the name. */
2148
2149 static const char *
2150 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2151 {
2152 if (info->priv != NULL)
2153 return info->priv->name;
2154
2155 return NULL;
2156 }
2157
2158 /* About these extended threadlist and threadinfo packets. They are
2159 variable length packets but, the fields within them are often fixed
2160 length. They are redundent enough to send over UDP as is the
2161 remote protocol in general. There is a matching unit test module
2162 in libstub. */
2163
2164 /* WARNING: This threadref data structure comes from the remote O.S.,
2165 libstub protocol encoding, and remote.c. It is not particularly
2166 changable. */
2167
2168 /* Right now, the internal structure is int. We want it to be bigger.
2169 Plan to fix this. */
2170
2171 typedef int gdb_threadref; /* Internal GDB thread reference. */
2172
2173 /* gdb_ext_thread_info is an internal GDB data structure which is
2174 equivalent to the reply of the remote threadinfo packet. */
2175
2176 struct gdb_ext_thread_info
2177 {
2178 threadref threadid; /* External form of thread reference. */
2179 int active; /* Has state interesting to GDB?
2180 regs, stack. */
2181 char display[256]; /* Brief state display, name,
2182 blocked/suspended. */
2183 char shortname[32]; /* To be used to name threads. */
2184 char more_display[256]; /* Long info, statistics, queue depth,
2185 whatever. */
2186 };
2187
2188 /* The volume of remote transfers can be limited by submitting
2189 a mask containing bits specifying the desired information.
2190 Use a union of these values as the 'selection' parameter to
2191 get_thread_info. FIXME: Make these TAG names more thread specific. */
2192
2193 #define TAG_THREADID 1
2194 #define TAG_EXISTS 2
2195 #define TAG_DISPLAY 4
2196 #define TAG_THREADNAME 8
2197 #define TAG_MOREDISPLAY 16
2198
2199 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2200
2201 static char *unpack_nibble (char *buf, int *val);
2202
2203 static char *unpack_byte (char *buf, int *value);
2204
2205 static char *pack_int (char *buf, int value);
2206
2207 static char *unpack_int (char *buf, int *value);
2208
2209 static char *unpack_string (char *src, char *dest, int length);
2210
2211 static char *pack_threadid (char *pkt, threadref *id);
2212
2213 static char *unpack_threadid (char *inbuf, threadref *id);
2214
2215 void int_to_threadref (threadref *id, int value);
2216
2217 static int threadref_to_int (threadref *ref);
2218
2219 static void copy_threadref (threadref *dest, threadref *src);
2220
2221 static int threadmatch (threadref *dest, threadref *src);
2222
2223 static char *pack_threadinfo_request (char *pkt, int mode,
2224 threadref *id);
2225
2226 static int remote_unpack_thread_info_response (char *pkt,
2227 threadref *expectedref,
2228 struct gdb_ext_thread_info
2229 *info);
2230
2231
2232 static int remote_get_threadinfo (threadref *threadid,
2233 int fieldset, /*TAG mask */
2234 struct gdb_ext_thread_info *info);
2235
2236 static char *pack_threadlist_request (char *pkt, int startflag,
2237 int threadcount,
2238 threadref *nextthread);
2239
2240 static int parse_threadlist_response (char *pkt,
2241 int result_limit,
2242 threadref *original_echo,
2243 threadref *resultlist,
2244 int *doneflag);
2245
2246 static int remote_get_threadlist (int startflag,
2247 threadref *nextthread,
2248 int result_limit,
2249 int *done,
2250 int *result_count,
2251 threadref *threadlist);
2252
2253 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2254
2255 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2256 void *context, int looplimit);
2257
2258 static int remote_newthread_step (threadref *ref, void *context);
2259
2260
2261 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2262 buffer we're allowed to write to. Returns
2263 BUF+CHARACTERS_WRITTEN. */
2264
2265 static char *
2266 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2267 {
2268 int pid, tid;
2269 struct remote_state *rs = get_remote_state ();
2270
2271 if (remote_multi_process_p (rs))
2272 {
2273 pid = ptid_get_pid (ptid);
2274 if (pid < 0)
2275 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2276 else
2277 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2278 }
2279 tid = ptid_get_lwp (ptid);
2280 if (tid < 0)
2281 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2282 else
2283 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2284
2285 return buf;
2286 }
2287
2288 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2289 passed the last parsed char. Returns null_ptid on error. */
2290
2291 static ptid_t
2292 read_ptid (char *buf, char **obuf)
2293 {
2294 char *p = buf;
2295 char *pp;
2296 ULONGEST pid = 0, tid = 0;
2297
2298 if (*p == 'p')
2299 {
2300 /* Multi-process ptid. */
2301 pp = unpack_varlen_hex (p + 1, &pid);
2302 if (*pp != '.')
2303 error (_("invalid remote ptid: %s"), p);
2304
2305 p = pp;
2306 pp = unpack_varlen_hex (p + 1, &tid);
2307 if (obuf)
2308 *obuf = pp;
2309 return ptid_build (pid, tid, 0);
2310 }
2311
2312 /* No multi-process. Just a tid. */
2313 pp = unpack_varlen_hex (p, &tid);
2314
2315 /* Return null_ptid when no thread id is found. */
2316 if (p == pp)
2317 {
2318 if (obuf)
2319 *obuf = pp;
2320 return null_ptid;
2321 }
2322
2323 /* Since the stub is not sending a process id, then default to
2324 what's in inferior_ptid, unless it's null at this point. If so,
2325 then since there's no way to know the pid of the reported
2326 threads, use the magic number. */
2327 if (ptid_equal (inferior_ptid, null_ptid))
2328 pid = ptid_get_pid (magic_null_ptid);
2329 else
2330 pid = ptid_get_pid (inferior_ptid);
2331
2332 if (obuf)
2333 *obuf = pp;
2334 return ptid_build (pid, tid, 0);
2335 }
2336
2337 static int
2338 stubhex (int ch)
2339 {
2340 if (ch >= 'a' && ch <= 'f')
2341 return ch - 'a' + 10;
2342 if (ch >= '0' && ch <= '9')
2343 return ch - '0';
2344 if (ch >= 'A' && ch <= 'F')
2345 return ch - 'A' + 10;
2346 return -1;
2347 }
2348
2349 static int
2350 stub_unpack_int (char *buff, int fieldlength)
2351 {
2352 int nibble;
2353 int retval = 0;
2354
2355 while (fieldlength)
2356 {
2357 nibble = stubhex (*buff++);
2358 retval |= nibble;
2359 fieldlength--;
2360 if (fieldlength)
2361 retval = retval << 4;
2362 }
2363 return retval;
2364 }
2365
2366 static char *
2367 unpack_nibble (char *buf, int *val)
2368 {
2369 *val = fromhex (*buf++);
2370 return buf;
2371 }
2372
2373 static char *
2374 unpack_byte (char *buf, int *value)
2375 {
2376 *value = stub_unpack_int (buf, 2);
2377 return buf + 2;
2378 }
2379
2380 static char *
2381 pack_int (char *buf, int value)
2382 {
2383 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2384 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2385 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2386 buf = pack_hex_byte (buf, (value & 0xff));
2387 return buf;
2388 }
2389
2390 static char *
2391 unpack_int (char *buf, int *value)
2392 {
2393 *value = stub_unpack_int (buf, 8);
2394 return buf + 8;
2395 }
2396
2397 #if 0 /* Currently unused, uncomment when needed. */
2398 static char *pack_string (char *pkt, char *string);
2399
2400 static char *
2401 pack_string (char *pkt, char *string)
2402 {
2403 char ch;
2404 int len;
2405
2406 len = strlen (string);
2407 if (len > 200)
2408 len = 200; /* Bigger than most GDB packets, junk??? */
2409 pkt = pack_hex_byte (pkt, len);
2410 while (len-- > 0)
2411 {
2412 ch = *string++;
2413 if ((ch == '\0') || (ch == '#'))
2414 ch = '*'; /* Protect encapsulation. */
2415 *pkt++ = ch;
2416 }
2417 return pkt;
2418 }
2419 #endif /* 0 (unused) */
2420
2421 static char *
2422 unpack_string (char *src, char *dest, int length)
2423 {
2424 while (length--)
2425 *dest++ = *src++;
2426 *dest = '\0';
2427 return src;
2428 }
2429
2430 static char *
2431 pack_threadid (char *pkt, threadref *id)
2432 {
2433 char *limit;
2434 unsigned char *altid;
2435
2436 altid = (unsigned char *) id;
2437 limit = pkt + BUF_THREAD_ID_SIZE;
2438 while (pkt < limit)
2439 pkt = pack_hex_byte (pkt, *altid++);
2440 return pkt;
2441 }
2442
2443
2444 static char *
2445 unpack_threadid (char *inbuf, threadref *id)
2446 {
2447 char *altref;
2448 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2449 int x, y;
2450
2451 altref = (char *) id;
2452
2453 while (inbuf < limit)
2454 {
2455 x = stubhex (*inbuf++);
2456 y = stubhex (*inbuf++);
2457 *altref++ = (x << 4) | y;
2458 }
2459 return inbuf;
2460 }
2461
2462 /* Externally, threadrefs are 64 bits but internally, they are still
2463 ints. This is due to a mismatch of specifications. We would like
2464 to use 64bit thread references internally. This is an adapter
2465 function. */
2466
2467 void
2468 int_to_threadref (threadref *id, int value)
2469 {
2470 unsigned char *scan;
2471
2472 scan = (unsigned char *) id;
2473 {
2474 int i = 4;
2475 while (i--)
2476 *scan++ = 0;
2477 }
2478 *scan++ = (value >> 24) & 0xff;
2479 *scan++ = (value >> 16) & 0xff;
2480 *scan++ = (value >> 8) & 0xff;
2481 *scan++ = (value & 0xff);
2482 }
2483
2484 static int
2485 threadref_to_int (threadref *ref)
2486 {
2487 int i, value = 0;
2488 unsigned char *scan;
2489
2490 scan = *ref;
2491 scan += 4;
2492 i = 4;
2493 while (i-- > 0)
2494 value = (value << 8) | ((*scan++) & 0xff);
2495 return value;
2496 }
2497
2498 static void
2499 copy_threadref (threadref *dest, threadref *src)
2500 {
2501 int i;
2502 unsigned char *csrc, *cdest;
2503
2504 csrc = (unsigned char *) src;
2505 cdest = (unsigned char *) dest;
2506 i = 8;
2507 while (i--)
2508 *cdest++ = *csrc++;
2509 }
2510
2511 static int
2512 threadmatch (threadref *dest, threadref *src)
2513 {
2514 /* Things are broken right now, so just assume we got a match. */
2515 #if 0
2516 unsigned char *srcp, *destp;
2517 int i, result;
2518 srcp = (char *) src;
2519 destp = (char *) dest;
2520
2521 result = 1;
2522 while (i-- > 0)
2523 result &= (*srcp++ == *destp++) ? 1 : 0;
2524 return result;
2525 #endif
2526 return 1;
2527 }
2528
2529 /*
2530 threadid:1, # always request threadid
2531 context_exists:2,
2532 display:4,
2533 unique_name:8,
2534 more_display:16
2535 */
2536
2537 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2538
2539 static char *
2540 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2541 {
2542 *pkt++ = 'q'; /* Info Query */
2543 *pkt++ = 'P'; /* process or thread info */
2544 pkt = pack_int (pkt, mode); /* mode */
2545 pkt = pack_threadid (pkt, id); /* threadid */
2546 *pkt = '\0'; /* terminate */
2547 return pkt;
2548 }
2549
2550 /* These values tag the fields in a thread info response packet. */
2551 /* Tagging the fields allows us to request specific fields and to
2552 add more fields as time goes by. */
2553
2554 #define TAG_THREADID 1 /* Echo the thread identifier. */
2555 #define TAG_EXISTS 2 /* Is this process defined enough to
2556 fetch registers and its stack? */
2557 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2558 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2559 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2560 the process. */
2561
2562 static int
2563 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2564 struct gdb_ext_thread_info *info)
2565 {
2566 struct remote_state *rs = get_remote_state ();
2567 int mask, length;
2568 int tag;
2569 threadref ref;
2570 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2571 int retval = 1;
2572
2573 /* info->threadid = 0; FIXME: implement zero_threadref. */
2574 info->active = 0;
2575 info->display[0] = '\0';
2576 info->shortname[0] = '\0';
2577 info->more_display[0] = '\0';
2578
2579 /* Assume the characters indicating the packet type have been
2580 stripped. */
2581 pkt = unpack_int (pkt, &mask); /* arg mask */
2582 pkt = unpack_threadid (pkt, &ref);
2583
2584 if (mask == 0)
2585 warning (_("Incomplete response to threadinfo request."));
2586 if (!threadmatch (&ref, expectedref))
2587 { /* This is an answer to a different request. */
2588 warning (_("ERROR RMT Thread info mismatch."));
2589 return 0;
2590 }
2591 copy_threadref (&info->threadid, &ref);
2592
2593 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2594
2595 /* Packets are terminated with nulls. */
2596 while ((pkt < limit) && mask && *pkt)
2597 {
2598 pkt = unpack_int (pkt, &tag); /* tag */
2599 pkt = unpack_byte (pkt, &length); /* length */
2600 if (!(tag & mask)) /* Tags out of synch with mask. */
2601 {
2602 warning (_("ERROR RMT: threadinfo tag mismatch."));
2603 retval = 0;
2604 break;
2605 }
2606 if (tag == TAG_THREADID)
2607 {
2608 if (length != 16)
2609 {
2610 warning (_("ERROR RMT: length of threadid is not 16."));
2611 retval = 0;
2612 break;
2613 }
2614 pkt = unpack_threadid (pkt, &ref);
2615 mask = mask & ~TAG_THREADID;
2616 continue;
2617 }
2618 if (tag == TAG_EXISTS)
2619 {
2620 info->active = stub_unpack_int (pkt, length);
2621 pkt += length;
2622 mask = mask & ~(TAG_EXISTS);
2623 if (length > 8)
2624 {
2625 warning (_("ERROR RMT: 'exists' length too long."));
2626 retval = 0;
2627 break;
2628 }
2629 continue;
2630 }
2631 if (tag == TAG_THREADNAME)
2632 {
2633 pkt = unpack_string (pkt, &info->shortname[0], length);
2634 mask = mask & ~TAG_THREADNAME;
2635 continue;
2636 }
2637 if (tag == TAG_DISPLAY)
2638 {
2639 pkt = unpack_string (pkt, &info->display[0], length);
2640 mask = mask & ~TAG_DISPLAY;
2641 continue;
2642 }
2643 if (tag == TAG_MOREDISPLAY)
2644 {
2645 pkt = unpack_string (pkt, &info->more_display[0], length);
2646 mask = mask & ~TAG_MOREDISPLAY;
2647 continue;
2648 }
2649 warning (_("ERROR RMT: unknown thread info tag."));
2650 break; /* Not a tag we know about. */
2651 }
2652 return retval;
2653 }
2654
2655 static int
2656 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2657 struct gdb_ext_thread_info *info)
2658 {
2659 struct remote_state *rs = get_remote_state ();
2660 int result;
2661
2662 pack_threadinfo_request (rs->buf, fieldset, threadid);
2663 putpkt (rs->buf);
2664 getpkt (&rs->buf, &rs->buf_size, 0);
2665
2666 if (rs->buf[0] == '\0')
2667 return 0;
2668
2669 result = remote_unpack_thread_info_response (rs->buf + 2,
2670 threadid, info);
2671 return result;
2672 }
2673
2674 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2675
2676 static char *
2677 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2678 threadref *nextthread)
2679 {
2680 *pkt++ = 'q'; /* info query packet */
2681 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2682 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2683 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2684 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2685 *pkt = '\0';
2686 return pkt;
2687 }
2688
2689 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2690
2691 static int
2692 parse_threadlist_response (char *pkt, int result_limit,
2693 threadref *original_echo, threadref *resultlist,
2694 int *doneflag)
2695 {
2696 struct remote_state *rs = get_remote_state ();
2697 char *limit;
2698 int count, resultcount, done;
2699
2700 resultcount = 0;
2701 /* Assume the 'q' and 'M chars have been stripped. */
2702 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2703 /* done parse past here */
2704 pkt = unpack_byte (pkt, &count); /* count field */
2705 pkt = unpack_nibble (pkt, &done);
2706 /* The first threadid is the argument threadid. */
2707 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2708 while ((count-- > 0) && (pkt < limit))
2709 {
2710 pkt = unpack_threadid (pkt, resultlist++);
2711 if (resultcount++ >= result_limit)
2712 break;
2713 }
2714 if (doneflag)
2715 *doneflag = done;
2716 return resultcount;
2717 }
2718
2719 /* Fetch the next batch of threads from the remote. Returns -1 if the
2720 qL packet is not supported, 0 on error and 1 on success. */
2721
2722 static int
2723 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2724 int *done, int *result_count, threadref *threadlist)
2725 {
2726 struct remote_state *rs = get_remote_state ();
2727 int result = 1;
2728
2729 /* Trancate result limit to be smaller than the packet size. */
2730 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2731 >= get_remote_packet_size ())
2732 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2733
2734 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2735 putpkt (rs->buf);
2736 getpkt (&rs->buf, &rs->buf_size, 0);
2737 if (*rs->buf == '\0')
2738 {
2739 /* Packet not supported. */
2740 return -1;
2741 }
2742
2743 *result_count =
2744 parse_threadlist_response (rs->buf + 2, result_limit,
2745 &rs->echo_nextthread, threadlist, done);
2746
2747 if (!threadmatch (&rs->echo_nextthread, nextthread))
2748 {
2749 /* FIXME: This is a good reason to drop the packet. */
2750 /* Possably, there is a duplicate response. */
2751 /* Possabilities :
2752 retransmit immediatly - race conditions
2753 retransmit after timeout - yes
2754 exit
2755 wait for packet, then exit
2756 */
2757 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2758 return 0; /* I choose simply exiting. */
2759 }
2760 if (*result_count <= 0)
2761 {
2762 if (*done != 1)
2763 {
2764 warning (_("RMT ERROR : failed to get remote thread list."));
2765 result = 0;
2766 }
2767 return result; /* break; */
2768 }
2769 if (*result_count > result_limit)
2770 {
2771 *result_count = 0;
2772 warning (_("RMT ERROR: threadlist response longer than requested."));
2773 return 0;
2774 }
2775 return result;
2776 }
2777
2778 /* Fetch the list of remote threads, with the qL packet, and call
2779 STEPFUNCTION for each thread found. Stops iterating and returns 1
2780 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2781 STEPFUNCTION returns false. If the packet is not supported,
2782 returns -1. */
2783
2784 static int
2785 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2786 int looplimit)
2787 {
2788 struct remote_state *rs = get_remote_state ();
2789 int done, i, result_count;
2790 int startflag = 1;
2791 int result = 1;
2792 int loopcount = 0;
2793
2794 done = 0;
2795 while (!done)
2796 {
2797 if (loopcount++ > looplimit)
2798 {
2799 result = 0;
2800 warning (_("Remote fetch threadlist -infinite loop-."));
2801 break;
2802 }
2803 result = remote_get_threadlist (startflag, &rs->nextthread,
2804 MAXTHREADLISTRESULTS,
2805 &done, &result_count,
2806 rs->resultthreadlist);
2807 if (result <= 0)
2808 break;
2809 /* Clear for later iterations. */
2810 startflag = 0;
2811 /* Setup to resume next batch of thread references, set nextthread. */
2812 if (result_count >= 1)
2813 copy_threadref (&rs->nextthread,
2814 &rs->resultthreadlist[result_count - 1]);
2815 i = 0;
2816 while (result_count--)
2817 {
2818 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2819 {
2820 result = 0;
2821 break;
2822 }
2823 }
2824 }
2825 return result;
2826 }
2827
2828 /* A thread found on the remote target. */
2829
2830 typedef struct thread_item
2831 {
2832 /* The thread's PTID. */
2833 ptid_t ptid;
2834
2835 /* The thread's extra info. May be NULL. */
2836 char *extra;
2837
2838 /* The thread's name. May be NULL. */
2839 char *name;
2840
2841 /* The core the thread was running on. -1 if not known. */
2842 int core;
2843 } thread_item_t;
2844 DEF_VEC_O(thread_item_t);
2845
2846 /* Context passed around to the various methods listing remote
2847 threads. As new threads are found, they're added to the ITEMS
2848 vector. */
2849
2850 struct threads_listing_context
2851 {
2852 /* The threads found on the remote target. */
2853 VEC (thread_item_t) *items;
2854 };
2855
2856 /* Discard the contents of the constructed thread listing context. */
2857
2858 static void
2859 clear_threads_listing_context (void *p)
2860 {
2861 struct threads_listing_context *context
2862 = (struct threads_listing_context *) p;
2863 int i;
2864 struct thread_item *item;
2865
2866 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2867 {
2868 xfree (item->extra);
2869 xfree (item->name);
2870 }
2871
2872 VEC_free (thread_item_t, context->items);
2873 }
2874
2875 /* Remove the thread specified as the related_pid field of WS
2876 from the CONTEXT list. */
2877
2878 static void
2879 threads_listing_context_remove (struct target_waitstatus *ws,
2880 struct threads_listing_context *context)
2881 {
2882 struct thread_item *item;
2883 int i;
2884 ptid_t child_ptid = ws->value.related_pid;
2885
2886 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2887 {
2888 if (ptid_equal (item->ptid, child_ptid))
2889 {
2890 VEC_ordered_remove (thread_item_t, context->items, i);
2891 break;
2892 }
2893 }
2894 }
2895
2896 static int
2897 remote_newthread_step (threadref *ref, void *data)
2898 {
2899 struct threads_listing_context *context
2900 = (struct threads_listing_context *) data;
2901 struct thread_item item;
2902 int pid = ptid_get_pid (inferior_ptid);
2903
2904 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2905 item.core = -1;
2906 item.extra = NULL;
2907
2908 VEC_safe_push (thread_item_t, context->items, &item);
2909
2910 return 1; /* continue iterator */
2911 }
2912
2913 #define CRAZY_MAX_THREADS 1000
2914
2915 static ptid_t
2916 remote_current_thread (ptid_t oldpid)
2917 {
2918 struct remote_state *rs = get_remote_state ();
2919
2920 putpkt ("qC");
2921 getpkt (&rs->buf, &rs->buf_size, 0);
2922 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2923 {
2924 char *obuf;
2925 ptid_t result;
2926
2927 result = read_ptid (&rs->buf[2], &obuf);
2928 if (*obuf != '\0' && remote_debug)
2929 fprintf_unfiltered (gdb_stdlog,
2930 "warning: garbage in qC reply\n");
2931
2932 return result;
2933 }
2934 else
2935 return oldpid;
2936 }
2937
2938 /* List remote threads using the deprecated qL packet. */
2939
2940 static int
2941 remote_get_threads_with_ql (struct target_ops *ops,
2942 struct threads_listing_context *context)
2943 {
2944 if (remote_threadlist_iterator (remote_newthread_step, context,
2945 CRAZY_MAX_THREADS) >= 0)
2946 return 1;
2947
2948 return 0;
2949 }
2950
2951 #if defined(HAVE_LIBEXPAT)
2952
2953 static void
2954 start_thread (struct gdb_xml_parser *parser,
2955 const struct gdb_xml_element *element,
2956 void *user_data, VEC(gdb_xml_value_s) *attributes)
2957 {
2958 struct threads_listing_context *data
2959 = (struct threads_listing_context *) user_data;
2960
2961 struct thread_item item;
2962 char *id;
2963 struct gdb_xml_value *attr;
2964
2965 id = (char *) xml_find_attribute (attributes, "id")->value;
2966 item.ptid = read_ptid (id, NULL);
2967
2968 attr = xml_find_attribute (attributes, "core");
2969 if (attr != NULL)
2970 item.core = *(ULONGEST *) attr->value;
2971 else
2972 item.core = -1;
2973
2974 attr = xml_find_attribute (attributes, "name");
2975 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
2976
2977 item.extra = 0;
2978
2979 VEC_safe_push (thread_item_t, data->items, &item);
2980 }
2981
2982 static void
2983 end_thread (struct gdb_xml_parser *parser,
2984 const struct gdb_xml_element *element,
2985 void *user_data, const char *body_text)
2986 {
2987 struct threads_listing_context *data
2988 = (struct threads_listing_context *) user_data;
2989
2990 if (body_text && *body_text)
2991 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2992 }
2993
2994 const struct gdb_xml_attribute thread_attributes[] = {
2995 { "id", GDB_XML_AF_NONE, NULL, NULL },
2996 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2997 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
2998 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2999 };
3000
3001 const struct gdb_xml_element thread_children[] = {
3002 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3003 };
3004
3005 const struct gdb_xml_element threads_children[] = {
3006 { "thread", thread_attributes, thread_children,
3007 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3008 start_thread, end_thread },
3009 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3010 };
3011
3012 const struct gdb_xml_element threads_elements[] = {
3013 { "threads", NULL, threads_children,
3014 GDB_XML_EF_NONE, NULL, NULL },
3015 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3016 };
3017
3018 #endif
3019
3020 /* List remote threads using qXfer:threads:read. */
3021
3022 static int
3023 remote_get_threads_with_qxfer (struct target_ops *ops,
3024 struct threads_listing_context *context)
3025 {
3026 #if defined(HAVE_LIBEXPAT)
3027 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3028 {
3029 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3030 struct cleanup *back_to = make_cleanup (xfree, xml);
3031
3032 if (xml != NULL && *xml != '\0')
3033 {
3034 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3035 threads_elements, xml, context);
3036 }
3037
3038 do_cleanups (back_to);
3039 return 1;
3040 }
3041 #endif
3042
3043 return 0;
3044 }
3045
3046 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3047
3048 static int
3049 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3050 struct threads_listing_context *context)
3051 {
3052 struct remote_state *rs = get_remote_state ();
3053
3054 if (rs->use_threadinfo_query)
3055 {
3056 char *bufp;
3057
3058 putpkt ("qfThreadInfo");
3059 getpkt (&rs->buf, &rs->buf_size, 0);
3060 bufp = rs->buf;
3061 if (bufp[0] != '\0') /* q packet recognized */
3062 {
3063 while (*bufp++ == 'm') /* reply contains one or more TID */
3064 {
3065 do
3066 {
3067 struct thread_item item;
3068
3069 item.ptid = read_ptid (bufp, &bufp);
3070 item.core = -1;
3071 item.extra = NULL;
3072
3073 VEC_safe_push (thread_item_t, context->items, &item);
3074 }
3075 while (*bufp++ == ','); /* comma-separated list */
3076 putpkt ("qsThreadInfo");
3077 getpkt (&rs->buf, &rs->buf_size, 0);
3078 bufp = rs->buf;
3079 }
3080 return 1;
3081 }
3082 else
3083 {
3084 /* Packet not recognized. */
3085 rs->use_threadinfo_query = 0;
3086 }
3087 }
3088
3089 return 0;
3090 }
3091
3092 /* Implement the to_update_thread_list function for the remote
3093 targets. */
3094
3095 static void
3096 remote_update_thread_list (struct target_ops *ops)
3097 {
3098 struct remote_state *rs = get_remote_state ();
3099 struct threads_listing_context context;
3100 struct cleanup *old_chain;
3101 int got_list = 0;
3102
3103 context.items = NULL;
3104 old_chain = make_cleanup (clear_threads_listing_context, &context);
3105
3106 /* We have a few different mechanisms to fetch the thread list. Try
3107 them all, starting with the most preferred one first, falling
3108 back to older methods. */
3109 if (remote_get_threads_with_qxfer (ops, &context)
3110 || remote_get_threads_with_qthreadinfo (ops, &context)
3111 || remote_get_threads_with_ql (ops, &context))
3112 {
3113 int i;
3114 struct thread_item *item;
3115 struct thread_info *tp, *tmp;
3116
3117 got_list = 1;
3118
3119 if (VEC_empty (thread_item_t, context.items)
3120 && remote_thread_always_alive (ops, inferior_ptid))
3121 {
3122 /* Some targets don't really support threads, but still
3123 reply an (empty) thread list in response to the thread
3124 listing packets, instead of replying "packet not
3125 supported". Exit early so we don't delete the main
3126 thread. */
3127 do_cleanups (old_chain);
3128 return;
3129 }
3130
3131 /* CONTEXT now holds the current thread list on the remote
3132 target end. Delete GDB-side threads no longer found on the
3133 target. */
3134 ALL_THREADS_SAFE (tp, tmp)
3135 {
3136 for (i = 0;
3137 VEC_iterate (thread_item_t, context.items, i, item);
3138 ++i)
3139 {
3140 if (ptid_equal (item->ptid, tp->ptid))
3141 break;
3142 }
3143
3144 if (i == VEC_length (thread_item_t, context.items))
3145 {
3146 /* Not found. */
3147 delete_thread (tp->ptid);
3148 }
3149 }
3150
3151 /* Remove any unreported fork child threads from CONTEXT so
3152 that we don't interfere with follow fork, which is where
3153 creation of such threads is handled. */
3154 remove_new_fork_children (&context);
3155
3156 /* And now add threads we don't know about yet to our list. */
3157 for (i = 0;
3158 VEC_iterate (thread_item_t, context.items, i, item);
3159 ++i)
3160 {
3161 if (!ptid_equal (item->ptid, null_ptid))
3162 {
3163 struct private_thread_info *info;
3164 /* In non-stop mode, we assume new found threads are
3165 running until proven otherwise with a stop reply. In
3166 all-stop, we can only get here if all threads are
3167 stopped. */
3168 int running = target_is_non_stop_p () ? 1 : 0;
3169
3170 remote_notice_new_inferior (item->ptid, running);
3171
3172 info = demand_private_info (item->ptid);
3173 info->core = item->core;
3174 info->extra = item->extra;
3175 item->extra = NULL;
3176 info->name = item->name;
3177 item->name = NULL;
3178 }
3179 }
3180 }
3181
3182 if (!got_list)
3183 {
3184 /* If no thread listing method is supported, then query whether
3185 each known thread is alive, one by one, with the T packet.
3186 If the target doesn't support threads at all, then this is a
3187 no-op. See remote_thread_alive. */
3188 prune_threads ();
3189 }
3190
3191 do_cleanups (old_chain);
3192 }
3193
3194 /*
3195 * Collect a descriptive string about the given thread.
3196 * The target may say anything it wants to about the thread
3197 * (typically info about its blocked / runnable state, name, etc.).
3198 * This string will appear in the info threads display.
3199 *
3200 * Optional: targets are not required to implement this function.
3201 */
3202
3203 static char *
3204 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3205 {
3206 struct remote_state *rs = get_remote_state ();
3207 int result;
3208 int set;
3209 threadref id;
3210 struct gdb_ext_thread_info threadinfo;
3211 static char display_buf[100]; /* arbitrary... */
3212 int n = 0; /* position in display_buf */
3213
3214 if (rs->remote_desc == 0) /* paranoia */
3215 internal_error (__FILE__, __LINE__,
3216 _("remote_threads_extra_info"));
3217
3218 if (ptid_equal (tp->ptid, magic_null_ptid)
3219 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3220 /* This is the main thread which was added by GDB. The remote
3221 server doesn't know about it. */
3222 return NULL;
3223
3224 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3225 {
3226 struct thread_info *info = find_thread_ptid (tp->ptid);
3227
3228 if (info && info->priv)
3229 return info->priv->extra;
3230 else
3231 return NULL;
3232 }
3233
3234 if (rs->use_threadextra_query)
3235 {
3236 char *b = rs->buf;
3237 char *endb = rs->buf + get_remote_packet_size ();
3238
3239 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3240 b += strlen (b);
3241 write_ptid (b, endb, tp->ptid);
3242
3243 putpkt (rs->buf);
3244 getpkt (&rs->buf, &rs->buf_size, 0);
3245 if (rs->buf[0] != 0)
3246 {
3247 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3248 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3249 display_buf [result] = '\0';
3250 return display_buf;
3251 }
3252 }
3253
3254 /* If the above query fails, fall back to the old method. */
3255 rs->use_threadextra_query = 0;
3256 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3257 | TAG_MOREDISPLAY | TAG_DISPLAY;
3258 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3259 if (remote_get_threadinfo (&id, set, &threadinfo))
3260 if (threadinfo.active)
3261 {
3262 if (*threadinfo.shortname)
3263 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3264 " Name: %s,", threadinfo.shortname);
3265 if (*threadinfo.display)
3266 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3267 " State: %s,", threadinfo.display);
3268 if (*threadinfo.more_display)
3269 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3270 " Priority: %s", threadinfo.more_display);
3271
3272 if (n > 0)
3273 {
3274 /* For purely cosmetic reasons, clear up trailing commas. */
3275 if (',' == display_buf[n-1])
3276 display_buf[n-1] = ' ';
3277 return display_buf;
3278 }
3279 }
3280 return NULL;
3281 }
3282 \f
3283
3284 static int
3285 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3286 struct static_tracepoint_marker *marker)
3287 {
3288 struct remote_state *rs = get_remote_state ();
3289 char *p = rs->buf;
3290
3291 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3292 p += strlen (p);
3293 p += hexnumstr (p, addr);
3294 putpkt (rs->buf);
3295 getpkt (&rs->buf, &rs->buf_size, 0);
3296 p = rs->buf;
3297
3298 if (*p == 'E')
3299 error (_("Remote failure reply: %s"), p);
3300
3301 if (*p++ == 'm')
3302 {
3303 parse_static_tracepoint_marker_definition (p, &p, marker);
3304 return 1;
3305 }
3306
3307 return 0;
3308 }
3309
3310 static VEC(static_tracepoint_marker_p) *
3311 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3312 const char *strid)
3313 {
3314 struct remote_state *rs = get_remote_state ();
3315 VEC(static_tracepoint_marker_p) *markers = NULL;
3316 struct static_tracepoint_marker *marker = NULL;
3317 struct cleanup *old_chain;
3318 char *p;
3319
3320 /* Ask for a first packet of static tracepoint marker
3321 definition. */
3322 putpkt ("qTfSTM");
3323 getpkt (&rs->buf, &rs->buf_size, 0);
3324 p = rs->buf;
3325 if (*p == 'E')
3326 error (_("Remote failure reply: %s"), p);
3327
3328 old_chain = make_cleanup (free_current_marker, &marker);
3329
3330 while (*p++ == 'm')
3331 {
3332 if (marker == NULL)
3333 marker = XCNEW (struct static_tracepoint_marker);
3334
3335 do
3336 {
3337 parse_static_tracepoint_marker_definition (p, &p, marker);
3338
3339 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3340 {
3341 VEC_safe_push (static_tracepoint_marker_p,
3342 markers, marker);
3343 marker = NULL;
3344 }
3345 else
3346 {
3347 release_static_tracepoint_marker (marker);
3348 memset (marker, 0, sizeof (*marker));
3349 }
3350 }
3351 while (*p++ == ','); /* comma-separated list */
3352 /* Ask for another packet of static tracepoint definition. */
3353 putpkt ("qTsSTM");
3354 getpkt (&rs->buf, &rs->buf_size, 0);
3355 p = rs->buf;
3356 }
3357
3358 do_cleanups (old_chain);
3359 return markers;
3360 }
3361
3362 \f
3363 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3364
3365 static ptid_t
3366 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3367 {
3368 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3369 }
3370 \f
3371
3372 /* Restart the remote side; this is an extended protocol operation. */
3373
3374 static void
3375 extended_remote_restart (void)
3376 {
3377 struct remote_state *rs = get_remote_state ();
3378
3379 /* Send the restart command; for reasons I don't understand the
3380 remote side really expects a number after the "R". */
3381 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3382 putpkt (rs->buf);
3383
3384 remote_fileio_reset ();
3385 }
3386 \f
3387 /* Clean up connection to a remote debugger. */
3388
3389 static void
3390 remote_close (struct target_ops *self)
3391 {
3392 struct remote_state *rs = get_remote_state ();
3393
3394 if (rs->remote_desc == NULL)
3395 return; /* already closed */
3396
3397 /* Make sure we leave stdin registered in the event loop, and we
3398 don't leave the async SIGINT signal handler installed. */
3399 remote_terminal_ours (self);
3400
3401 serial_close (rs->remote_desc);
3402 rs->remote_desc = NULL;
3403
3404 /* We don't have a connection to the remote stub anymore. Get rid
3405 of all the inferiors and their threads we were controlling.
3406 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3407 will be unable to find the thread corresponding to (pid, 0, 0). */
3408 inferior_ptid = null_ptid;
3409 discard_all_inferiors ();
3410
3411 /* We are closing the remote target, so we should discard
3412 everything of this target. */
3413 discard_pending_stop_replies_in_queue (rs);
3414
3415 if (remote_async_inferior_event_token)
3416 delete_async_event_handler (&remote_async_inferior_event_token);
3417
3418 remote_notif_state_xfree (rs->notif_state);
3419
3420 trace_reset_local_state ();
3421 }
3422
3423 /* Query the remote side for the text, data and bss offsets. */
3424
3425 static void
3426 get_offsets (void)
3427 {
3428 struct remote_state *rs = get_remote_state ();
3429 char *buf;
3430 char *ptr;
3431 int lose, num_segments = 0, do_sections, do_segments;
3432 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3433 struct section_offsets *offs;
3434 struct symfile_segment_data *data;
3435
3436 if (symfile_objfile == NULL)
3437 return;
3438
3439 putpkt ("qOffsets");
3440 getpkt (&rs->buf, &rs->buf_size, 0);
3441 buf = rs->buf;
3442
3443 if (buf[0] == '\000')
3444 return; /* Return silently. Stub doesn't support
3445 this command. */
3446 if (buf[0] == 'E')
3447 {
3448 warning (_("Remote failure reply: %s"), buf);
3449 return;
3450 }
3451
3452 /* Pick up each field in turn. This used to be done with scanf, but
3453 scanf will make trouble if CORE_ADDR size doesn't match
3454 conversion directives correctly. The following code will work
3455 with any size of CORE_ADDR. */
3456 text_addr = data_addr = bss_addr = 0;
3457 ptr = buf;
3458 lose = 0;
3459
3460 if (startswith (ptr, "Text="))
3461 {
3462 ptr += 5;
3463 /* Don't use strtol, could lose on big values. */
3464 while (*ptr && *ptr != ';')
3465 text_addr = (text_addr << 4) + fromhex (*ptr++);
3466
3467 if (startswith (ptr, ";Data="))
3468 {
3469 ptr += 6;
3470 while (*ptr && *ptr != ';')
3471 data_addr = (data_addr << 4) + fromhex (*ptr++);
3472 }
3473 else
3474 lose = 1;
3475
3476 if (!lose && startswith (ptr, ";Bss="))
3477 {
3478 ptr += 5;
3479 while (*ptr && *ptr != ';')
3480 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3481
3482 if (bss_addr != data_addr)
3483 warning (_("Target reported unsupported offsets: %s"), buf);
3484 }
3485 else
3486 lose = 1;
3487 }
3488 else if (startswith (ptr, "TextSeg="))
3489 {
3490 ptr += 8;
3491 /* Don't use strtol, could lose on big values. */
3492 while (*ptr && *ptr != ';')
3493 text_addr = (text_addr << 4) + fromhex (*ptr++);
3494 num_segments = 1;
3495
3496 if (startswith (ptr, ";DataSeg="))
3497 {
3498 ptr += 9;
3499 while (*ptr && *ptr != ';')
3500 data_addr = (data_addr << 4) + fromhex (*ptr++);
3501 num_segments++;
3502 }
3503 }
3504 else
3505 lose = 1;
3506
3507 if (lose)
3508 error (_("Malformed response to offset query, %s"), buf);
3509 else if (*ptr != '\0')
3510 warning (_("Target reported unsupported offsets: %s"), buf);
3511
3512 offs = ((struct section_offsets *)
3513 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3514 memcpy (offs, symfile_objfile->section_offsets,
3515 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3516
3517 data = get_symfile_segment_data (symfile_objfile->obfd);
3518 do_segments = (data != NULL);
3519 do_sections = num_segments == 0;
3520
3521 if (num_segments > 0)
3522 {
3523 segments[0] = text_addr;
3524 segments[1] = data_addr;
3525 }
3526 /* If we have two segments, we can still try to relocate everything
3527 by assuming that the .text and .data offsets apply to the whole
3528 text and data segments. Convert the offsets given in the packet
3529 to base addresses for symfile_map_offsets_to_segments. */
3530 else if (data && data->num_segments == 2)
3531 {
3532 segments[0] = data->segment_bases[0] + text_addr;
3533 segments[1] = data->segment_bases[1] + data_addr;
3534 num_segments = 2;
3535 }
3536 /* If the object file has only one segment, assume that it is text
3537 rather than data; main programs with no writable data are rare,
3538 but programs with no code are useless. Of course the code might
3539 have ended up in the data segment... to detect that we would need
3540 the permissions here. */
3541 else if (data && data->num_segments == 1)
3542 {
3543 segments[0] = data->segment_bases[0] + text_addr;
3544 num_segments = 1;
3545 }
3546 /* There's no way to relocate by segment. */
3547 else
3548 do_segments = 0;
3549
3550 if (do_segments)
3551 {
3552 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3553 offs, num_segments, segments);
3554
3555 if (ret == 0 && !do_sections)
3556 error (_("Can not handle qOffsets TextSeg "
3557 "response with this symbol file"));
3558
3559 if (ret > 0)
3560 do_sections = 0;
3561 }
3562
3563 if (data)
3564 free_symfile_segment_data (data);
3565
3566 if (do_sections)
3567 {
3568 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3569
3570 /* This is a temporary kludge to force data and bss to use the
3571 same offsets because that's what nlmconv does now. The real
3572 solution requires changes to the stub and remote.c that I
3573 don't have time to do right now. */
3574
3575 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3576 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3577 }
3578
3579 objfile_relocate (symfile_objfile, offs);
3580 }
3581
3582 /* Send interrupt_sequence to remote target. */
3583 static void
3584 send_interrupt_sequence (void)
3585 {
3586 struct remote_state *rs = get_remote_state ();
3587
3588 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3589 remote_serial_write ("\x03", 1);
3590 else if (interrupt_sequence_mode == interrupt_sequence_break)
3591 serial_send_break (rs->remote_desc);
3592 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3593 {
3594 serial_send_break (rs->remote_desc);
3595 remote_serial_write ("g", 1);
3596 }
3597 else
3598 internal_error (__FILE__, __LINE__,
3599 _("Invalid value for interrupt_sequence_mode: %s."),
3600 interrupt_sequence_mode);
3601 }
3602
3603
3604 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3605 and extract the PTID. Returns NULL_PTID if not found. */
3606
3607 static ptid_t
3608 stop_reply_extract_thread (char *stop_reply)
3609 {
3610 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3611 {
3612 char *p;
3613
3614 /* Txx r:val ; r:val (...) */
3615 p = &stop_reply[3];
3616
3617 /* Look for "register" named "thread". */
3618 while (*p != '\0')
3619 {
3620 char *p1;
3621
3622 p1 = strchr (p, ':');
3623 if (p1 == NULL)
3624 return null_ptid;
3625
3626 if (strncmp (p, "thread", p1 - p) == 0)
3627 return read_ptid (++p1, &p);
3628
3629 p1 = strchr (p, ';');
3630 if (p1 == NULL)
3631 return null_ptid;
3632 p1++;
3633
3634 p = p1;
3635 }
3636 }
3637
3638 return null_ptid;
3639 }
3640
3641 /* Determine the remote side's current thread. If we have a stop
3642 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3643 "thread" register we can extract the current thread from. If not,
3644 ask the remote which is the current thread with qC. The former
3645 method avoids a roundtrip. */
3646
3647 static ptid_t
3648 get_current_thread (char *wait_status)
3649 {
3650 ptid_t ptid = null_ptid;
3651
3652 /* Note we don't use remote_parse_stop_reply as that makes use of
3653 the target architecture, which we haven't yet fully determined at
3654 this point. */
3655 if (wait_status != NULL)
3656 ptid = stop_reply_extract_thread (wait_status);
3657 if (ptid_equal (ptid, null_ptid))
3658 ptid = remote_current_thread (inferior_ptid);
3659
3660 return ptid;
3661 }
3662
3663 /* Query the remote target for which is the current thread/process,
3664 add it to our tables, and update INFERIOR_PTID. The caller is
3665 responsible for setting the state such that the remote end is ready
3666 to return the current thread.
3667
3668 This function is called after handling the '?' or 'vRun' packets,
3669 whose response is a stop reply from which we can also try
3670 extracting the thread. If the target doesn't support the explicit
3671 qC query, we infer the current thread from that stop reply, passed
3672 in in WAIT_STATUS, which may be NULL. */
3673
3674 static void
3675 add_current_inferior_and_thread (char *wait_status)
3676 {
3677 struct remote_state *rs = get_remote_state ();
3678 int fake_pid_p = 0;
3679 ptid_t ptid;
3680
3681 inferior_ptid = null_ptid;
3682
3683 /* Now, if we have thread information, update inferior_ptid. */
3684 ptid = get_current_thread (wait_status);
3685
3686 if (!ptid_equal (ptid, null_ptid))
3687 {
3688 if (!remote_multi_process_p (rs))
3689 fake_pid_p = 1;
3690
3691 inferior_ptid = ptid;
3692 }
3693 else
3694 {
3695 /* Without this, some commands which require an active target
3696 (such as kill) won't work. This variable serves (at least)
3697 double duty as both the pid of the target process (if it has
3698 such), and as a flag indicating that a target is active. */
3699 inferior_ptid = magic_null_ptid;
3700 fake_pid_p = 1;
3701 }
3702
3703 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3704
3705 /* Add the main thread. */
3706 add_thread_silent (inferior_ptid);
3707 }
3708
3709 /* Print info about a thread that was found already stopped on
3710 connection. */
3711
3712 static void
3713 print_one_stopped_thread (struct thread_info *thread)
3714 {
3715 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3716
3717 switch_to_thread (thread->ptid);
3718 stop_pc = get_frame_pc (get_current_frame ());
3719 set_current_sal_from_frame (get_current_frame ());
3720
3721 thread->suspend.waitstatus_pending_p = 0;
3722
3723 if (ws->kind == TARGET_WAITKIND_STOPPED)
3724 {
3725 enum gdb_signal sig = ws->value.sig;
3726
3727 if (signal_print_state (sig))
3728 observer_notify_signal_received (sig);
3729 }
3730 observer_notify_normal_stop (NULL, 1);
3731 }
3732
3733 /* Process all initial stop replies the remote side sent in response
3734 to the ? packet. These indicate threads that were already stopped
3735 on initial connection. We mark these threads as stopped and print
3736 their current frame before giving the user the prompt. */
3737
3738 static void
3739 process_initial_stop_replies (int from_tty)
3740 {
3741 int pending_stop_replies = stop_reply_queue_length ();
3742 struct inferior *inf;
3743 struct thread_info *thread;
3744 struct thread_info *selected = NULL;
3745 struct thread_info *lowest_stopped = NULL;
3746 struct thread_info *first = NULL;
3747
3748 /* Consume the initial pending events. */
3749 while (pending_stop_replies-- > 0)
3750 {
3751 ptid_t waiton_ptid = minus_one_ptid;
3752 ptid_t event_ptid;
3753 struct target_waitstatus ws;
3754 int ignore_event = 0;
3755 struct thread_info *thread;
3756
3757 memset (&ws, 0, sizeof (ws));
3758 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3759 if (remote_debug)
3760 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3761
3762 switch (ws.kind)
3763 {
3764 case TARGET_WAITKIND_IGNORE:
3765 case TARGET_WAITKIND_NO_RESUMED:
3766 case TARGET_WAITKIND_SIGNALLED:
3767 case TARGET_WAITKIND_EXITED:
3768 /* We shouldn't see these, but if we do, just ignore. */
3769 if (remote_debug)
3770 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3771 ignore_event = 1;
3772 break;
3773
3774 case TARGET_WAITKIND_EXECD:
3775 xfree (ws.value.execd_pathname);
3776 break;
3777 default:
3778 break;
3779 }
3780
3781 if (ignore_event)
3782 continue;
3783
3784 thread = find_thread_ptid (event_ptid);
3785
3786 if (ws.kind == TARGET_WAITKIND_STOPPED)
3787 {
3788 enum gdb_signal sig = ws.value.sig;
3789
3790 /* Stubs traditionally report SIGTRAP as initial signal,
3791 instead of signal 0. Suppress it. */
3792 if (sig == GDB_SIGNAL_TRAP)
3793 sig = GDB_SIGNAL_0;
3794 thread->suspend.stop_signal = sig;
3795 ws.value.sig = sig;
3796 }
3797
3798 thread->suspend.waitstatus = ws;
3799
3800 if (ws.kind != TARGET_WAITKIND_STOPPED
3801 || ws.value.sig != GDB_SIGNAL_0)
3802 thread->suspend.waitstatus_pending_p = 1;
3803
3804 set_executing (event_ptid, 0);
3805 set_running (event_ptid, 0);
3806 }
3807
3808 /* "Notice" the new inferiors before anything related to
3809 registers/memory. */
3810 ALL_INFERIORS (inf)
3811 {
3812 if (inf->pid == 0)
3813 continue;
3814
3815 inf->needs_setup = 1;
3816
3817 if (non_stop)
3818 {
3819 thread = any_live_thread_of_process (inf->pid);
3820 notice_new_inferior (thread->ptid,
3821 thread->state == THREAD_RUNNING,
3822 from_tty);
3823 }
3824 }
3825
3826 /* If all-stop on top of non-stop, pause all threads. Note this
3827 records the threads' stop pc, so must be done after "noticing"
3828 the inferiors. */
3829 if (!non_stop)
3830 {
3831 stop_all_threads ();
3832
3833 /* If all threads of an inferior were already stopped, we
3834 haven't setup the inferior yet. */
3835 ALL_INFERIORS (inf)
3836 {
3837 if (inf->pid == 0)
3838 continue;
3839
3840 if (inf->needs_setup)
3841 {
3842 thread = any_live_thread_of_process (inf->pid);
3843 switch_to_thread_no_regs (thread);
3844 setup_inferior (0);
3845 }
3846 }
3847 }
3848
3849 /* Now go over all threads that are stopped, and print their current
3850 frame. If all-stop, then if there's a signalled thread, pick
3851 that as current. */
3852 ALL_NON_EXITED_THREADS (thread)
3853 {
3854 struct target_waitstatus *ws;
3855
3856 if (first == NULL)
3857 first = thread;
3858
3859 if (!non_stop)
3860 set_running (thread->ptid, 0);
3861 else if (thread->state != THREAD_STOPPED)
3862 continue;
3863
3864 ws = &thread->suspend.waitstatus;
3865
3866 if (selected == NULL
3867 && thread->suspend.waitstatus_pending_p)
3868 selected = thread;
3869
3870 if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3871 lowest_stopped = thread;
3872
3873 if (non_stop)
3874 print_one_stopped_thread (thread);
3875 }
3876
3877 /* In all-stop, we only print the status of one thread, and leave
3878 others with their status pending. */
3879 if (!non_stop)
3880 {
3881 thread = selected;
3882 if (thread == NULL)
3883 thread = lowest_stopped;
3884 if (thread == NULL)
3885 thread = first;
3886
3887 print_one_stopped_thread (thread);
3888 }
3889
3890 /* For "info program". */
3891 thread = inferior_thread ();
3892 if (thread->state == THREAD_STOPPED)
3893 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3894 }
3895
3896 static void
3897 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3898 {
3899 struct remote_state *rs = get_remote_state ();
3900 struct packet_config *noack_config;
3901 char *wait_status = NULL;
3902
3903 immediate_quit++; /* Allow user to interrupt it. */
3904 QUIT;
3905
3906 if (interrupt_on_connect)
3907 send_interrupt_sequence ();
3908
3909 /* Ack any packet which the remote side has already sent. */
3910 serial_write (rs->remote_desc, "+", 1);
3911
3912 /* Signal other parts that we're going through the initial setup,
3913 and so things may not be stable yet. */
3914 rs->starting_up = 1;
3915
3916 /* The first packet we send to the target is the optional "supported
3917 packets" request. If the target can answer this, it will tell us
3918 which later probes to skip. */
3919 remote_query_supported ();
3920
3921 /* If the stub wants to get a QAllow, compose one and send it. */
3922 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3923 remote_set_permissions (target);
3924
3925 /* Next, we possibly activate noack mode.
3926
3927 If the QStartNoAckMode packet configuration is set to AUTO,
3928 enable noack mode if the stub reported a wish for it with
3929 qSupported.
3930
3931 If set to TRUE, then enable noack mode even if the stub didn't
3932 report it in qSupported. If the stub doesn't reply OK, the
3933 session ends with an error.
3934
3935 If FALSE, then don't activate noack mode, regardless of what the
3936 stub claimed should be the default with qSupported. */
3937
3938 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3939 if (packet_config_support (noack_config) != PACKET_DISABLE)
3940 {
3941 putpkt ("QStartNoAckMode");
3942 getpkt (&rs->buf, &rs->buf_size, 0);
3943 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3944 rs->noack_mode = 1;
3945 }
3946
3947 if (extended_p)
3948 {
3949 /* Tell the remote that we are using the extended protocol. */
3950 putpkt ("!");
3951 getpkt (&rs->buf, &rs->buf_size, 0);
3952 }
3953
3954 /* Let the target know which signals it is allowed to pass down to
3955 the program. */
3956 update_signals_program_target ();
3957
3958 /* Next, if the target can specify a description, read it. We do
3959 this before anything involving memory or registers. */
3960 target_find_description ();
3961
3962 /* Next, now that we know something about the target, update the
3963 address spaces in the program spaces. */
3964 update_address_spaces ();
3965
3966 /* On OSs where the list of libraries is global to all
3967 processes, we fetch them early. */
3968 if (gdbarch_has_global_solist (target_gdbarch ()))
3969 solib_add (NULL, from_tty, target, auto_solib_add);
3970
3971 if (target_is_non_stop_p ())
3972 {
3973 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3974 error (_("Non-stop mode requested, but remote "
3975 "does not support non-stop"));
3976
3977 putpkt ("QNonStop:1");
3978 getpkt (&rs->buf, &rs->buf_size, 0);
3979
3980 if (strcmp (rs->buf, "OK") != 0)
3981 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3982
3983 /* Find about threads and processes the stub is already
3984 controlling. We default to adding them in the running state.
3985 The '?' query below will then tell us about which threads are
3986 stopped. */
3987 remote_update_thread_list (target);
3988 }
3989 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3990 {
3991 /* Don't assume that the stub can operate in all-stop mode.
3992 Request it explicitly. */
3993 putpkt ("QNonStop:0");
3994 getpkt (&rs->buf, &rs->buf_size, 0);
3995
3996 if (strcmp (rs->buf, "OK") != 0)
3997 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3998 }
3999
4000 /* Upload TSVs regardless of whether the target is running or not. The
4001 remote stub, such as GDBserver, may have some predefined or builtin
4002 TSVs, even if the target is not running. */
4003 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4004 {
4005 struct uploaded_tsv *uploaded_tsvs = NULL;
4006
4007 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4008 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4009 }
4010
4011 /* Check whether the target is running now. */
4012 putpkt ("?");
4013 getpkt (&rs->buf, &rs->buf_size, 0);
4014
4015 if (!target_is_non_stop_p ())
4016 {
4017 ptid_t ptid;
4018 int fake_pid_p = 0;
4019 struct inferior *inf;
4020
4021 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4022 {
4023 if (!extended_p)
4024 error (_("The target is not running (try extended-remote?)"));
4025
4026 /* We're connected, but not running. Drop out before we
4027 call start_remote. */
4028 rs->starting_up = 0;
4029 return;
4030 }
4031 else
4032 {
4033 /* Save the reply for later. */
4034 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4035 strcpy (wait_status, rs->buf);
4036 }
4037
4038 /* Fetch thread list. */
4039 target_update_thread_list ();
4040
4041 /* Let the stub know that we want it to return the thread. */
4042 set_continue_thread (minus_one_ptid);
4043
4044 if (thread_count () == 0)
4045 {
4046 /* Target has no concept of threads at all. GDB treats
4047 non-threaded target as single-threaded; add a main
4048 thread. */
4049 add_current_inferior_and_thread (wait_status);
4050 }
4051 else
4052 {
4053 /* We have thread information; select the thread the target
4054 says should be current. If we're reconnecting to a
4055 multi-threaded program, this will ideally be the thread
4056 that last reported an event before GDB disconnected. */
4057 inferior_ptid = get_current_thread (wait_status);
4058 if (ptid_equal (inferior_ptid, null_ptid))
4059 {
4060 /* Odd... The target was able to list threads, but not
4061 tell us which thread was current (no "thread"
4062 register in T stop reply?). Just pick the first
4063 thread in the thread list then. */
4064
4065 if (remote_debug)
4066 fprintf_unfiltered (gdb_stdlog,
4067 "warning: couldn't determine remote "
4068 "current thread; picking first in list.\n");
4069
4070 inferior_ptid = thread_list->ptid;
4071 }
4072 }
4073
4074 /* init_wait_for_inferior should be called before get_offsets in order
4075 to manage `inserted' flag in bp loc in a correct state.
4076 breakpoint_init_inferior, called from init_wait_for_inferior, set
4077 `inserted' flag to 0, while before breakpoint_re_set, called from
4078 start_remote, set `inserted' flag to 1. In the initialization of
4079 inferior, breakpoint_init_inferior should be called first, and then
4080 breakpoint_re_set can be called. If this order is broken, state of
4081 `inserted' flag is wrong, and cause some problems on breakpoint
4082 manipulation. */
4083 init_wait_for_inferior ();
4084
4085 get_offsets (); /* Get text, data & bss offsets. */
4086
4087 /* If we could not find a description using qXfer, and we know
4088 how to do it some other way, try again. This is not
4089 supported for non-stop; it could be, but it is tricky if
4090 there are no stopped threads when we connect. */
4091 if (remote_read_description_p (target)
4092 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4093 {
4094 target_clear_description ();
4095 target_find_description ();
4096 }
4097
4098 /* Use the previously fetched status. */
4099 gdb_assert (wait_status != NULL);
4100 strcpy (rs->buf, wait_status);
4101 rs->cached_wait_status = 1;
4102
4103 immediate_quit--;
4104 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4105 }
4106 else
4107 {
4108 /* Clear WFI global state. Do this before finding about new
4109 threads and inferiors, and setting the current inferior.
4110 Otherwise we would clear the proceed status of the current
4111 inferior when we want its stop_soon state to be preserved
4112 (see notice_new_inferior). */
4113 init_wait_for_inferior ();
4114
4115 /* In non-stop, we will either get an "OK", meaning that there
4116 are no stopped threads at this time; or, a regular stop
4117 reply. In the latter case, there may be more than one thread
4118 stopped --- we pull them all out using the vStopped
4119 mechanism. */
4120 if (strcmp (rs->buf, "OK") != 0)
4121 {
4122 struct notif_client *notif = &notif_client_stop;
4123
4124 /* remote_notif_get_pending_replies acks this one, and gets
4125 the rest out. */
4126 rs->notif_state->pending_event[notif_client_stop.id]
4127 = remote_notif_parse (notif, rs->buf);
4128 remote_notif_get_pending_events (notif);
4129 }
4130
4131 if (thread_count () == 0)
4132 {
4133 if (!extended_p)
4134 error (_("The target is not running (try extended-remote?)"));
4135
4136 /* We're connected, but not running. Drop out before we
4137 call start_remote. */
4138 rs->starting_up = 0;
4139 return;
4140 }
4141
4142 /* In non-stop mode, any cached wait status will be stored in
4143 the stop reply queue. */
4144 gdb_assert (wait_status == NULL);
4145
4146 /* Report all signals during attach/startup. */
4147 remote_pass_signals (target, 0, NULL);
4148
4149 /* If there are already stopped threads, mark them stopped and
4150 report their stops before giving the prompt to the user. */
4151 process_initial_stop_replies (from_tty);
4152
4153 if (target_can_async_p ())
4154 target_async (1);
4155 }
4156
4157 /* If we connected to a live target, do some additional setup. */
4158 if (target_has_execution)
4159 {
4160 if (symfile_objfile) /* No use without a symbol-file. */
4161 remote_check_symbols ();
4162 }
4163
4164 /* Possibly the target has been engaged in a trace run started
4165 previously; find out where things are at. */
4166 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4167 {
4168 struct uploaded_tp *uploaded_tps = NULL;
4169
4170 if (current_trace_status ()->running)
4171 printf_filtered (_("Trace is already running on the target.\n"));
4172
4173 remote_upload_tracepoints (target, &uploaded_tps);
4174
4175 merge_uploaded_tracepoints (&uploaded_tps);
4176 }
4177
4178 /* The thread and inferior lists are now synchronized with the
4179 target, our symbols have been relocated, and we're merged the
4180 target's tracepoints with ours. We're done with basic start
4181 up. */
4182 rs->starting_up = 0;
4183
4184 /* Maybe breakpoints are global and need to be inserted now. */
4185 if (breakpoints_should_be_inserted_now ())
4186 insert_breakpoints ();
4187 }
4188
4189 /* Open a connection to a remote debugger.
4190 NAME is the filename used for communication. */
4191
4192 static void
4193 remote_open (const char *name, int from_tty)
4194 {
4195 remote_open_1 (name, from_tty, &remote_ops, 0);
4196 }
4197
4198 /* Open a connection to a remote debugger using the extended
4199 remote gdb protocol. NAME is the filename used for communication. */
4200
4201 static void
4202 extended_remote_open (const char *name, int from_tty)
4203 {
4204 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4205 }
4206
4207 /* Reset all packets back to "unknown support". Called when opening a
4208 new connection to a remote target. */
4209
4210 static void
4211 reset_all_packet_configs_support (void)
4212 {
4213 int i;
4214
4215 for (i = 0; i < PACKET_MAX; i++)
4216 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4217 }
4218
4219 /* Initialize all packet configs. */
4220
4221 static void
4222 init_all_packet_configs (void)
4223 {
4224 int i;
4225
4226 for (i = 0; i < PACKET_MAX; i++)
4227 {
4228 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4229 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4230 }
4231 }
4232
4233 /* Symbol look-up. */
4234
4235 static void
4236 remote_check_symbols (void)
4237 {
4238 struct remote_state *rs = get_remote_state ();
4239 char *msg, *reply, *tmp;
4240 struct bound_minimal_symbol sym;
4241 int end;
4242 struct cleanup *old_chain;
4243
4244 /* The remote side has no concept of inferiors that aren't running
4245 yet, it only knows about running processes. If we're connected
4246 but our current inferior is not running, we should not invite the
4247 remote target to request symbol lookups related to its
4248 (unrelated) current process. */
4249 if (!target_has_execution)
4250 return;
4251
4252 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4253 return;
4254
4255 /* Make sure the remote is pointing at the right process. Note
4256 there's no way to select "no process". */
4257 set_general_process ();
4258
4259 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4260 because we need both at the same time. */
4261 msg = (char *) xmalloc (get_remote_packet_size ());
4262 old_chain = make_cleanup (xfree, msg);
4263
4264 /* Invite target to request symbol lookups. */
4265
4266 putpkt ("qSymbol::");
4267 getpkt (&rs->buf, &rs->buf_size, 0);
4268 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4269 reply = rs->buf;
4270
4271 while (startswith (reply, "qSymbol:"))
4272 {
4273 struct bound_minimal_symbol sym;
4274
4275 tmp = &reply[8];
4276 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4277 msg[end] = '\0';
4278 sym = lookup_minimal_symbol (msg, NULL, NULL);
4279 if (sym.minsym == NULL)
4280 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4281 else
4282 {
4283 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4284 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4285
4286 /* If this is a function address, return the start of code
4287 instead of any data function descriptor. */
4288 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4289 sym_addr,
4290 &current_target);
4291
4292 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4293 phex_nz (sym_addr, addr_size), &reply[8]);
4294 }
4295
4296 putpkt (msg);
4297 getpkt (&rs->buf, &rs->buf_size, 0);
4298 reply = rs->buf;
4299 }
4300
4301 do_cleanups (old_chain);
4302 }
4303
4304 static struct serial *
4305 remote_serial_open (const char *name)
4306 {
4307 static int udp_warning = 0;
4308
4309 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4310 of in ser-tcp.c, because it is the remote protocol assuming that the
4311 serial connection is reliable and not the serial connection promising
4312 to be. */
4313 if (!udp_warning && startswith (name, "udp:"))
4314 {
4315 warning (_("The remote protocol may be unreliable over UDP.\n"
4316 "Some events may be lost, rendering further debugging "
4317 "impossible."));
4318 udp_warning = 1;
4319 }
4320
4321 return serial_open (name);
4322 }
4323
4324 /* Inform the target of our permission settings. The permission flags
4325 work without this, but if the target knows the settings, it can do
4326 a couple things. First, it can add its own check, to catch cases
4327 that somehow manage to get by the permissions checks in target
4328 methods. Second, if the target is wired to disallow particular
4329 settings (for instance, a system in the field that is not set up to
4330 be able to stop at a breakpoint), it can object to any unavailable
4331 permissions. */
4332
4333 void
4334 remote_set_permissions (struct target_ops *self)
4335 {
4336 struct remote_state *rs = get_remote_state ();
4337
4338 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4339 "WriteReg:%x;WriteMem:%x;"
4340 "InsertBreak:%x;InsertTrace:%x;"
4341 "InsertFastTrace:%x;Stop:%x",
4342 may_write_registers, may_write_memory,
4343 may_insert_breakpoints, may_insert_tracepoints,
4344 may_insert_fast_tracepoints, may_stop);
4345 putpkt (rs->buf);
4346 getpkt (&rs->buf, &rs->buf_size, 0);
4347
4348 /* If the target didn't like the packet, warn the user. Do not try
4349 to undo the user's settings, that would just be maddening. */
4350 if (strcmp (rs->buf, "OK") != 0)
4351 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4352 }
4353
4354 /* This type describes each known response to the qSupported
4355 packet. */
4356 struct protocol_feature
4357 {
4358 /* The name of this protocol feature. */
4359 const char *name;
4360
4361 /* The default for this protocol feature. */
4362 enum packet_support default_support;
4363
4364 /* The function to call when this feature is reported, or after
4365 qSupported processing if the feature is not supported.
4366 The first argument points to this structure. The second
4367 argument indicates whether the packet requested support be
4368 enabled, disabled, or probed (or the default, if this function
4369 is being called at the end of processing and this feature was
4370 not reported). The third argument may be NULL; if not NULL, it
4371 is a NUL-terminated string taken from the packet following
4372 this feature's name and an equals sign. */
4373 void (*func) (const struct protocol_feature *, enum packet_support,
4374 const char *);
4375
4376 /* The corresponding packet for this feature. Only used if
4377 FUNC is remote_supported_packet. */
4378 int packet;
4379 };
4380
4381 static void
4382 remote_supported_packet (const struct protocol_feature *feature,
4383 enum packet_support support,
4384 const char *argument)
4385 {
4386 if (argument)
4387 {
4388 warning (_("Remote qSupported response supplied an unexpected value for"
4389 " \"%s\"."), feature->name);
4390 return;
4391 }
4392
4393 remote_protocol_packets[feature->packet].support = support;
4394 }
4395
4396 static void
4397 remote_packet_size (const struct protocol_feature *feature,
4398 enum packet_support support, const char *value)
4399 {
4400 struct remote_state *rs = get_remote_state ();
4401
4402 int packet_size;
4403 char *value_end;
4404
4405 if (support != PACKET_ENABLE)
4406 return;
4407
4408 if (value == NULL || *value == '\0')
4409 {
4410 warning (_("Remote target reported \"%s\" without a size."),
4411 feature->name);
4412 return;
4413 }
4414
4415 errno = 0;
4416 packet_size = strtol (value, &value_end, 16);
4417 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4418 {
4419 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4420 feature->name, value);
4421 return;
4422 }
4423
4424 /* Record the new maximum packet size. */
4425 rs->explicit_packet_size = packet_size;
4426 }
4427
4428 static const struct protocol_feature remote_protocol_features[] = {
4429 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4430 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4431 PACKET_qXfer_auxv },
4432 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4433 PACKET_qXfer_exec_file },
4434 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4435 PACKET_qXfer_features },
4436 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4437 PACKET_qXfer_libraries },
4438 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4439 PACKET_qXfer_libraries_svr4 },
4440 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4441 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4442 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4443 PACKET_qXfer_memory_map },
4444 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4445 PACKET_qXfer_spu_read },
4446 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4447 PACKET_qXfer_spu_write },
4448 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4449 PACKET_qXfer_osdata },
4450 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4451 PACKET_qXfer_threads },
4452 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4453 PACKET_qXfer_traceframe_info },
4454 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4455 PACKET_QPassSignals },
4456 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4457 PACKET_QProgramSignals },
4458 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4459 PACKET_QStartNoAckMode },
4460 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4461 PACKET_multiprocess_feature },
4462 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4463 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4464 PACKET_qXfer_siginfo_read },
4465 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4466 PACKET_qXfer_siginfo_write },
4467 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4468 PACKET_ConditionalTracepoints },
4469 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4470 PACKET_ConditionalBreakpoints },
4471 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4472 PACKET_BreakpointCommands },
4473 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4474 PACKET_FastTracepoints },
4475 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4476 PACKET_StaticTracepoints },
4477 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4478 PACKET_InstallInTrace},
4479 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4480 PACKET_DisconnectedTracing_feature },
4481 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4482 PACKET_bc },
4483 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4484 PACKET_bs },
4485 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4486 PACKET_TracepointSource },
4487 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4488 PACKET_QAllow },
4489 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4490 PACKET_EnableDisableTracepoints_feature },
4491 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4492 PACKET_qXfer_fdpic },
4493 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4494 PACKET_qXfer_uib },
4495 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4496 PACKET_QDisableRandomization },
4497 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4498 { "QTBuffer:size", PACKET_DISABLE,
4499 remote_supported_packet, PACKET_QTBuffer_size},
4500 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4501 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4502 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4503 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4504 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4505 PACKET_qXfer_btrace },
4506 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4507 PACKET_qXfer_btrace_conf },
4508 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4509 PACKET_Qbtrace_conf_bts_size },
4510 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4511 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4512 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4513 PACKET_fork_event_feature },
4514 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4515 PACKET_vfork_event_feature },
4516 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4517 PACKET_exec_event_feature },
4518 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4519 PACKET_Qbtrace_conf_pt_size },
4520 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported }
4521 };
4522
4523 static char *remote_support_xml;
4524
4525 /* Register string appended to "xmlRegisters=" in qSupported query. */
4526
4527 void
4528 register_remote_support_xml (const char *xml)
4529 {
4530 #if defined(HAVE_LIBEXPAT)
4531 if (remote_support_xml == NULL)
4532 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4533 else
4534 {
4535 char *copy = xstrdup (remote_support_xml + 13);
4536 char *p = strtok (copy, ",");
4537
4538 do
4539 {
4540 if (strcmp (p, xml) == 0)
4541 {
4542 /* already there */
4543 xfree (copy);
4544 return;
4545 }
4546 }
4547 while ((p = strtok (NULL, ",")) != NULL);
4548 xfree (copy);
4549
4550 remote_support_xml = reconcat (remote_support_xml,
4551 remote_support_xml, ",", xml,
4552 (char *) NULL);
4553 }
4554 #endif
4555 }
4556
4557 static char *
4558 remote_query_supported_append (char *msg, const char *append)
4559 {
4560 if (msg)
4561 return reconcat (msg, msg, ";", append, (char *) NULL);
4562 else
4563 return xstrdup (append);
4564 }
4565
4566 static void
4567 remote_query_supported (void)
4568 {
4569 struct remote_state *rs = get_remote_state ();
4570 char *next;
4571 int i;
4572 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4573
4574 /* The packet support flags are handled differently for this packet
4575 than for most others. We treat an error, a disabled packet, and
4576 an empty response identically: any features which must be reported
4577 to be used will be automatically disabled. An empty buffer
4578 accomplishes this, since that is also the representation for a list
4579 containing no features. */
4580
4581 rs->buf[0] = 0;
4582 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4583 {
4584 char *q = NULL;
4585 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4586
4587 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4588 q = remote_query_supported_append (q, "multiprocess+");
4589
4590 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4591 q = remote_query_supported_append (q, "swbreak+");
4592 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4593 q = remote_query_supported_append (q, "hwbreak+");
4594
4595 q = remote_query_supported_append (q, "qRelocInsn+");
4596
4597 if (rs->extended)
4598 {
4599 if (packet_set_cmd_state (PACKET_fork_event_feature)
4600 != AUTO_BOOLEAN_FALSE)
4601 q = remote_query_supported_append (q, "fork-events+");
4602 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4603 != AUTO_BOOLEAN_FALSE)
4604 q = remote_query_supported_append (q, "vfork-events+");
4605 if (packet_set_cmd_state (PACKET_exec_event_feature)
4606 != AUTO_BOOLEAN_FALSE)
4607 q = remote_query_supported_append (q, "exec-events+");
4608 }
4609
4610 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4611 q = remote_query_supported_append (q, "vContSupported+");
4612
4613 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4614 the qSupported:xmlRegisters=i386 handling. */
4615 if (remote_support_xml != NULL)
4616 q = remote_query_supported_append (q, remote_support_xml);
4617
4618 q = reconcat (q, "qSupported:", q, (char *) NULL);
4619 putpkt (q);
4620
4621 do_cleanups (old_chain);
4622
4623 getpkt (&rs->buf, &rs->buf_size, 0);
4624
4625 /* If an error occured, warn, but do not return - just reset the
4626 buffer to empty and go on to disable features. */
4627 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4628 == PACKET_ERROR)
4629 {
4630 warning (_("Remote failure reply: %s"), rs->buf);
4631 rs->buf[0] = 0;
4632 }
4633 }
4634
4635 memset (seen, 0, sizeof (seen));
4636
4637 next = rs->buf;
4638 while (*next)
4639 {
4640 enum packet_support is_supported;
4641 char *p, *end, *name_end, *value;
4642
4643 /* First separate out this item from the rest of the packet. If
4644 there's another item after this, we overwrite the separator
4645 (terminated strings are much easier to work with). */
4646 p = next;
4647 end = strchr (p, ';');
4648 if (end == NULL)
4649 {
4650 end = p + strlen (p);
4651 next = end;
4652 }
4653 else
4654 {
4655 *end = '\0';
4656 next = end + 1;
4657
4658 if (end == p)
4659 {
4660 warning (_("empty item in \"qSupported\" response"));
4661 continue;
4662 }
4663 }
4664
4665 name_end = strchr (p, '=');
4666 if (name_end)
4667 {
4668 /* This is a name=value entry. */
4669 is_supported = PACKET_ENABLE;
4670 value = name_end + 1;
4671 *name_end = '\0';
4672 }
4673 else
4674 {
4675 value = NULL;
4676 switch (end[-1])
4677 {
4678 case '+':
4679 is_supported = PACKET_ENABLE;
4680 break;
4681
4682 case '-':
4683 is_supported = PACKET_DISABLE;
4684 break;
4685
4686 case '?':
4687 is_supported = PACKET_SUPPORT_UNKNOWN;
4688 break;
4689
4690 default:
4691 warning (_("unrecognized item \"%s\" "
4692 "in \"qSupported\" response"), p);
4693 continue;
4694 }
4695 end[-1] = '\0';
4696 }
4697
4698 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4699 if (strcmp (remote_protocol_features[i].name, p) == 0)
4700 {
4701 const struct protocol_feature *feature;
4702
4703 seen[i] = 1;
4704 feature = &remote_protocol_features[i];
4705 feature->func (feature, is_supported, value);
4706 break;
4707 }
4708 }
4709
4710 /* If we increased the packet size, make sure to increase the global
4711 buffer size also. We delay this until after parsing the entire
4712 qSupported packet, because this is the same buffer we were
4713 parsing. */
4714 if (rs->buf_size < rs->explicit_packet_size)
4715 {
4716 rs->buf_size = rs->explicit_packet_size;
4717 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4718 }
4719
4720 /* Handle the defaults for unmentioned features. */
4721 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4722 if (!seen[i])
4723 {
4724 const struct protocol_feature *feature;
4725
4726 feature = &remote_protocol_features[i];
4727 feature->func (feature, feature->default_support, NULL);
4728 }
4729 }
4730
4731 /* Remove any of the remote.c targets from target stack. Upper targets depend
4732 on it so remove them first. */
4733
4734 static void
4735 remote_unpush_target (void)
4736 {
4737 pop_all_targets_at_and_above (process_stratum);
4738 }
4739
4740 static void
4741 remote_open_1 (const char *name, int from_tty,
4742 struct target_ops *target, int extended_p)
4743 {
4744 struct remote_state *rs = get_remote_state ();
4745
4746 if (name == 0)
4747 error (_("To open a remote debug connection, you need to specify what\n"
4748 "serial device is attached to the remote system\n"
4749 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4750
4751 /* See FIXME above. */
4752 if (!target_async_permitted)
4753 wait_forever_enabled_p = 1;
4754
4755 /* If we're connected to a running target, target_preopen will kill it.
4756 Ask this question first, before target_preopen has a chance to kill
4757 anything. */
4758 if (rs->remote_desc != NULL && !have_inferiors ())
4759 {
4760 if (from_tty
4761 && !query (_("Already connected to a remote target. Disconnect? ")))
4762 error (_("Still connected."));
4763 }
4764
4765 /* Here the possibly existing remote target gets unpushed. */
4766 target_preopen (from_tty);
4767
4768 /* Make sure we send the passed signals list the next time we resume. */
4769 xfree (rs->last_pass_packet);
4770 rs->last_pass_packet = NULL;
4771
4772 /* Make sure we send the program signals list the next time we
4773 resume. */
4774 xfree (rs->last_program_signals_packet);
4775 rs->last_program_signals_packet = NULL;
4776
4777 remote_fileio_reset ();
4778 reopen_exec_file ();
4779 reread_symbols ();
4780
4781 rs->remote_desc = remote_serial_open (name);
4782 if (!rs->remote_desc)
4783 perror_with_name (name);
4784
4785 if (baud_rate != -1)
4786 {
4787 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4788 {
4789 /* The requested speed could not be set. Error out to
4790 top level after closing remote_desc. Take care to
4791 set remote_desc to NULL to avoid closing remote_desc
4792 more than once. */
4793 serial_close (rs->remote_desc);
4794 rs->remote_desc = NULL;
4795 perror_with_name (name);
4796 }
4797 }
4798
4799 serial_setparity (rs->remote_desc, serial_parity);
4800 serial_raw (rs->remote_desc);
4801
4802 /* If there is something sitting in the buffer we might take it as a
4803 response to a command, which would be bad. */
4804 serial_flush_input (rs->remote_desc);
4805
4806 if (from_tty)
4807 {
4808 puts_filtered ("Remote debugging using ");
4809 puts_filtered (name);
4810 puts_filtered ("\n");
4811 }
4812 push_target (target); /* Switch to using remote target now. */
4813
4814 /* Register extra event sources in the event loop. */
4815 remote_async_inferior_event_token
4816 = create_async_event_handler (remote_async_inferior_event_handler,
4817 NULL);
4818 rs->notif_state = remote_notif_state_allocate ();
4819
4820 /* Reset the target state; these things will be queried either by
4821 remote_query_supported or as they are needed. */
4822 reset_all_packet_configs_support ();
4823 rs->cached_wait_status = 0;
4824 rs->explicit_packet_size = 0;
4825 rs->noack_mode = 0;
4826 rs->extended = extended_p;
4827 rs->waiting_for_stop_reply = 0;
4828 rs->ctrlc_pending_p = 0;
4829
4830 rs->general_thread = not_sent_ptid;
4831 rs->continue_thread = not_sent_ptid;
4832 rs->remote_traceframe_number = -1;
4833
4834 /* Probe for ability to use "ThreadInfo" query, as required. */
4835 rs->use_threadinfo_query = 1;
4836 rs->use_threadextra_query = 1;
4837
4838 readahead_cache_invalidate ();
4839
4840 if (target_async_permitted)
4841 {
4842 /* With this target we start out by owning the terminal. */
4843 remote_async_terminal_ours_p = 1;
4844
4845 /* FIXME: cagney/1999-09-23: During the initial connection it is
4846 assumed that the target is already ready and able to respond to
4847 requests. Unfortunately remote_start_remote() eventually calls
4848 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4849 around this. Eventually a mechanism that allows
4850 wait_for_inferior() to expect/get timeouts will be
4851 implemented. */
4852 wait_forever_enabled_p = 0;
4853 }
4854
4855 /* First delete any symbols previously loaded from shared libraries. */
4856 no_shared_libraries (NULL, 0);
4857
4858 /* Start afresh. */
4859 init_thread_list ();
4860
4861 /* Start the remote connection. If error() or QUIT, discard this
4862 target (we'd otherwise be in an inconsistent state) and then
4863 propogate the error on up the exception chain. This ensures that
4864 the caller doesn't stumble along blindly assuming that the
4865 function succeeded. The CLI doesn't have this problem but other
4866 UI's, such as MI do.
4867
4868 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4869 this function should return an error indication letting the
4870 caller restore the previous state. Unfortunately the command
4871 ``target remote'' is directly wired to this function making that
4872 impossible. On a positive note, the CLI side of this problem has
4873 been fixed - the function set_cmd_context() makes it possible for
4874 all the ``target ....'' commands to share a common callback
4875 function. See cli-dump.c. */
4876 {
4877
4878 TRY
4879 {
4880 remote_start_remote (from_tty, target, extended_p);
4881 }
4882 CATCH (ex, RETURN_MASK_ALL)
4883 {
4884 /* Pop the partially set up target - unless something else did
4885 already before throwing the exception. */
4886 if (rs->remote_desc != NULL)
4887 remote_unpush_target ();
4888 if (target_async_permitted)
4889 wait_forever_enabled_p = 1;
4890 throw_exception (ex);
4891 }
4892 END_CATCH
4893 }
4894
4895 remote_btrace_reset ();
4896
4897 if (target_async_permitted)
4898 wait_forever_enabled_p = 1;
4899 }
4900
4901 /* Detach the specified process. */
4902
4903 static void
4904 remote_detach_pid (int pid)
4905 {
4906 struct remote_state *rs = get_remote_state ();
4907
4908 if (remote_multi_process_p (rs))
4909 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4910 else
4911 strcpy (rs->buf, "D");
4912
4913 putpkt (rs->buf);
4914 getpkt (&rs->buf, &rs->buf_size, 0);
4915
4916 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4917 ;
4918 else if (rs->buf[0] == '\0')
4919 error (_("Remote doesn't know how to detach"));
4920 else
4921 error (_("Can't detach process."));
4922 }
4923
4924 /* This detaches a program to which we previously attached, using
4925 inferior_ptid to identify the process. After this is done, GDB
4926 can be used to debug some other program. We better not have left
4927 any breakpoints in the target program or it'll die when it hits
4928 one. */
4929
4930 static void
4931 remote_detach_1 (const char *args, int from_tty)
4932 {
4933 int pid = ptid_get_pid (inferior_ptid);
4934 struct remote_state *rs = get_remote_state ();
4935 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4936 int is_fork_parent;
4937
4938 if (args)
4939 error (_("Argument given to \"detach\" when remotely debugging."));
4940
4941 if (!target_has_execution)
4942 error (_("No process to detach from."));
4943
4944 if (from_tty)
4945 {
4946 char *exec_file = get_exec_file (0);
4947 if (exec_file == NULL)
4948 exec_file = "";
4949 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4950 target_pid_to_str (pid_to_ptid (pid)));
4951 gdb_flush (gdb_stdout);
4952 }
4953
4954 /* Tell the remote target to detach. */
4955 remote_detach_pid (pid);
4956
4957 if (from_tty && !rs->extended)
4958 puts_filtered (_("Ending remote debugging.\n"));
4959
4960 /* Check to see if we are detaching a fork parent. Note that if we
4961 are detaching a fork child, tp == NULL. */
4962 is_fork_parent = (tp != NULL
4963 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4964
4965 /* If doing detach-on-fork, we don't mourn, because that will delete
4966 breakpoints that should be available for the followed inferior. */
4967 if (!is_fork_parent)
4968 target_mourn_inferior ();
4969 else
4970 {
4971 inferior_ptid = null_ptid;
4972 detach_inferior (pid);
4973 }
4974 }
4975
4976 static void
4977 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4978 {
4979 remote_detach_1 (args, from_tty);
4980 }
4981
4982 static void
4983 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4984 {
4985 remote_detach_1 (args, from_tty);
4986 }
4987
4988 /* Target follow-fork function for remote targets. On entry, and
4989 at return, the current inferior is the fork parent.
4990
4991 Note that although this is currently only used for extended-remote,
4992 it is named remote_follow_fork in anticipation of using it for the
4993 remote target as well. */
4994
4995 static int
4996 remote_follow_fork (struct target_ops *ops, int follow_child,
4997 int detach_fork)
4998 {
4999 struct remote_state *rs = get_remote_state ();
5000 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5001
5002 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5003 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5004 {
5005 /* When following the parent and detaching the child, we detach
5006 the child here. For the case of following the child and
5007 detaching the parent, the detach is done in the target-
5008 independent follow fork code in infrun.c. We can't use
5009 target_detach when detaching an unfollowed child because
5010 the client side doesn't know anything about the child. */
5011 if (detach_fork && !follow_child)
5012 {
5013 /* Detach the fork child. */
5014 ptid_t child_ptid;
5015 pid_t child_pid;
5016
5017 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5018 child_pid = ptid_get_pid (child_ptid);
5019
5020 remote_detach_pid (child_pid);
5021 detach_inferior (child_pid);
5022 }
5023 }
5024 return 0;
5025 }
5026
5027 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5028 in the program space of the new inferior. On entry and at return the
5029 current inferior is the exec'ing inferior. INF is the new exec'd
5030 inferior, which may be the same as the exec'ing inferior unless
5031 follow-exec-mode is "new". */
5032
5033 static void
5034 remote_follow_exec (struct target_ops *ops,
5035 struct inferior *inf, char *execd_pathname)
5036 {
5037 /* We know that this is a target file name, so if it has the "target:"
5038 prefix we strip it off before saving it in the program space. */
5039 if (is_target_filename (execd_pathname))
5040 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5041
5042 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5043 }
5044
5045 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5046
5047 static void
5048 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5049 {
5050 if (args)
5051 error (_("Argument given to \"disconnect\" when remotely debugging."));
5052
5053 /* Make sure we unpush even the extended remote targets; mourn
5054 won't do it. So call remote_mourn directly instead of
5055 target_mourn_inferior. */
5056 remote_mourn (target);
5057
5058 if (from_tty)
5059 puts_filtered ("Ending remote debugging.\n");
5060 }
5061
5062 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5063 be chatty about it. */
5064
5065 static void
5066 extended_remote_attach (struct target_ops *target, const char *args,
5067 int from_tty)
5068 {
5069 struct remote_state *rs = get_remote_state ();
5070 int pid;
5071 char *wait_status = NULL;
5072
5073 pid = parse_pid_to_attach (args);
5074
5075 /* Remote PID can be freely equal to getpid, do not check it here the same
5076 way as in other targets. */
5077
5078 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5079 error (_("This target does not support attaching to a process"));
5080
5081 if (from_tty)
5082 {
5083 char *exec_file = get_exec_file (0);
5084
5085 if (exec_file)
5086 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5087 target_pid_to_str (pid_to_ptid (pid)));
5088 else
5089 printf_unfiltered (_("Attaching to %s\n"),
5090 target_pid_to_str (pid_to_ptid (pid)));
5091
5092 gdb_flush (gdb_stdout);
5093 }
5094
5095 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5096 putpkt (rs->buf);
5097 getpkt (&rs->buf, &rs->buf_size, 0);
5098
5099 switch (packet_ok (rs->buf,
5100 &remote_protocol_packets[PACKET_vAttach]))
5101 {
5102 case PACKET_OK:
5103 if (!target_is_non_stop_p ())
5104 {
5105 /* Save the reply for later. */
5106 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5107 strcpy (wait_status, rs->buf);
5108 }
5109 else if (strcmp (rs->buf, "OK") != 0)
5110 error (_("Attaching to %s failed with: %s"),
5111 target_pid_to_str (pid_to_ptid (pid)),
5112 rs->buf);
5113 break;
5114 case PACKET_UNKNOWN:
5115 error (_("This target does not support attaching to a process"));
5116 default:
5117 error (_("Attaching to %s failed"),
5118 target_pid_to_str (pid_to_ptid (pid)));
5119 }
5120
5121 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5122
5123 inferior_ptid = pid_to_ptid (pid);
5124
5125 if (target_is_non_stop_p ())
5126 {
5127 struct thread_info *thread;
5128
5129 /* Get list of threads. */
5130 remote_update_thread_list (target);
5131
5132 thread = first_thread_of_process (pid);
5133 if (thread)
5134 inferior_ptid = thread->ptid;
5135 else
5136 inferior_ptid = pid_to_ptid (pid);
5137
5138 /* Invalidate our notion of the remote current thread. */
5139 record_currthread (rs, minus_one_ptid);
5140 }
5141 else
5142 {
5143 /* Now, if we have thread information, update inferior_ptid. */
5144 inferior_ptid = remote_current_thread (inferior_ptid);
5145
5146 /* Add the main thread to the thread list. */
5147 add_thread_silent (inferior_ptid);
5148 }
5149
5150 /* Next, if the target can specify a description, read it. We do
5151 this before anything involving memory or registers. */
5152 target_find_description ();
5153
5154 if (!target_is_non_stop_p ())
5155 {
5156 /* Use the previously fetched status. */
5157 gdb_assert (wait_status != NULL);
5158
5159 if (target_can_async_p ())
5160 {
5161 struct notif_event *reply
5162 = remote_notif_parse (&notif_client_stop, wait_status);
5163
5164 push_stop_reply ((struct stop_reply *) reply);
5165
5166 target_async (1);
5167 }
5168 else
5169 {
5170 gdb_assert (wait_status != NULL);
5171 strcpy (rs->buf, wait_status);
5172 rs->cached_wait_status = 1;
5173 }
5174 }
5175 else
5176 gdb_assert (wait_status == NULL);
5177 }
5178
5179 /* Implementation of the to_post_attach method. */
5180
5181 static void
5182 extended_remote_post_attach (struct target_ops *ops, int pid)
5183 {
5184 /* Get text, data & bss offsets. */
5185 get_offsets ();
5186
5187 /* In certain cases GDB might not have had the chance to start
5188 symbol lookup up until now. This could happen if the debugged
5189 binary is not using shared libraries, the vsyscall page is not
5190 present (on Linux) and the binary itself hadn't changed since the
5191 debugging process was started. */
5192 if (symfile_objfile != NULL)
5193 remote_check_symbols();
5194 }
5195
5196 \f
5197 /* Check for the availability of vCont. This function should also check
5198 the response. */
5199
5200 static void
5201 remote_vcont_probe (struct remote_state *rs)
5202 {
5203 char *buf;
5204
5205 strcpy (rs->buf, "vCont?");
5206 putpkt (rs->buf);
5207 getpkt (&rs->buf, &rs->buf_size, 0);
5208 buf = rs->buf;
5209
5210 /* Make sure that the features we assume are supported. */
5211 if (startswith (buf, "vCont"))
5212 {
5213 char *p = &buf[5];
5214 int support_c, support_C;
5215
5216 rs->supports_vCont.s = 0;
5217 rs->supports_vCont.S = 0;
5218 support_c = 0;
5219 support_C = 0;
5220 rs->supports_vCont.t = 0;
5221 rs->supports_vCont.r = 0;
5222 while (p && *p == ';')
5223 {
5224 p++;
5225 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5226 rs->supports_vCont.s = 1;
5227 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5228 rs->supports_vCont.S = 1;
5229 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5230 support_c = 1;
5231 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5232 support_C = 1;
5233 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5234 rs->supports_vCont.t = 1;
5235 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5236 rs->supports_vCont.r = 1;
5237
5238 p = strchr (p, ';');
5239 }
5240
5241 /* If c, and C are not all supported, we can't use vCont. Clearing
5242 BUF will make packet_ok disable the packet. */
5243 if (!support_c || !support_C)
5244 buf[0] = 0;
5245 }
5246
5247 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5248 }
5249
5250 /* Helper function for building "vCont" resumptions. Write a
5251 resumption to P. ENDP points to one-passed-the-end of the buffer
5252 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5253 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5254 resumed thread should be single-stepped and/or signalled. If PTID
5255 equals minus_one_ptid, then all threads are resumed; if PTID
5256 represents a process, then all threads of the process are resumed;
5257 the thread to be stepped and/or signalled is given in the global
5258 INFERIOR_PTID. */
5259
5260 static char *
5261 append_resumption (char *p, char *endp,
5262 ptid_t ptid, int step, enum gdb_signal siggnal)
5263 {
5264 struct remote_state *rs = get_remote_state ();
5265
5266 if (step && siggnal != GDB_SIGNAL_0)
5267 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5268 else if (step
5269 /* GDB is willing to range step. */
5270 && use_range_stepping
5271 /* Target supports range stepping. */
5272 && rs->supports_vCont.r
5273 /* We don't currently support range stepping multiple
5274 threads with a wildcard (though the protocol allows it,
5275 so stubs shouldn't make an active effort to forbid
5276 it). */
5277 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5278 {
5279 struct thread_info *tp;
5280
5281 if (ptid_equal (ptid, minus_one_ptid))
5282 {
5283 /* If we don't know about the target thread's tid, then
5284 we're resuming magic_null_ptid (see caller). */
5285 tp = find_thread_ptid (magic_null_ptid);
5286 }
5287 else
5288 tp = find_thread_ptid (ptid);
5289 gdb_assert (tp != NULL);
5290
5291 if (tp->control.may_range_step)
5292 {
5293 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5294
5295 p += xsnprintf (p, endp - p, ";r%s,%s",
5296 phex_nz (tp->control.step_range_start,
5297 addr_size),
5298 phex_nz (tp->control.step_range_end,
5299 addr_size));
5300 }
5301 else
5302 p += xsnprintf (p, endp - p, ";s");
5303 }
5304 else if (step)
5305 p += xsnprintf (p, endp - p, ";s");
5306 else if (siggnal != GDB_SIGNAL_0)
5307 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5308 else
5309 p += xsnprintf (p, endp - p, ";c");
5310
5311 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5312 {
5313 ptid_t nptid;
5314
5315 /* All (-1) threads of process. */
5316 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5317
5318 p += xsnprintf (p, endp - p, ":");
5319 p = write_ptid (p, endp, nptid);
5320 }
5321 else if (!ptid_equal (ptid, minus_one_ptid))
5322 {
5323 p += xsnprintf (p, endp - p, ":");
5324 p = write_ptid (p, endp, ptid);
5325 }
5326
5327 return p;
5328 }
5329
5330 /* Append a vCont continue-with-signal action for threads that have a
5331 non-zero stop signal. */
5332
5333 static char *
5334 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5335 {
5336 struct thread_info *thread;
5337
5338 ALL_NON_EXITED_THREADS (thread)
5339 if (ptid_match (thread->ptid, ptid)
5340 && !ptid_equal (inferior_ptid, thread->ptid)
5341 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5342 {
5343 p = append_resumption (p, endp, thread->ptid,
5344 0, thread->suspend.stop_signal);
5345 thread->suspend.stop_signal = GDB_SIGNAL_0;
5346 }
5347
5348 return p;
5349 }
5350
5351 /* Resume the remote inferior by using a "vCont" packet. The thread
5352 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5353 resumed thread should be single-stepped and/or signalled. If PTID
5354 equals minus_one_ptid, then all threads are resumed; the thread to
5355 be stepped and/or signalled is given in the global INFERIOR_PTID.
5356 This function returns non-zero iff it resumes the inferior.
5357
5358 This function issues a strict subset of all possible vCont commands at the
5359 moment. */
5360
5361 static int
5362 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5363 {
5364 struct remote_state *rs = get_remote_state ();
5365 char *p;
5366 char *endp;
5367
5368 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5369 remote_vcont_probe (rs);
5370
5371 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5372 return 0;
5373
5374 p = rs->buf;
5375 endp = rs->buf + get_remote_packet_size ();
5376
5377 /* If we could generate a wider range of packets, we'd have to worry
5378 about overflowing BUF. Should there be a generic
5379 "multi-part-packet" packet? */
5380
5381 p += xsnprintf (p, endp - p, "vCont");
5382
5383 if (ptid_equal (ptid, magic_null_ptid))
5384 {
5385 /* MAGIC_NULL_PTID means that we don't have any active threads,
5386 so we don't have any TID numbers the inferior will
5387 understand. Make sure to only send forms that do not specify
5388 a TID. */
5389 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5390 }
5391 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5392 {
5393 /* Resume all threads (of all processes, or of a single
5394 process), with preference for INFERIOR_PTID. This assumes
5395 inferior_ptid belongs to the set of all threads we are about
5396 to resume. */
5397 if (step || siggnal != GDB_SIGNAL_0)
5398 {
5399 /* Step inferior_ptid, with or without signal. */
5400 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5401 }
5402
5403 /* Also pass down any pending signaled resumption for other
5404 threads not the current. */
5405 p = append_pending_thread_resumptions (p, endp, ptid);
5406
5407 /* And continue others without a signal. */
5408 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5409 }
5410 else
5411 {
5412 /* Scheduler locking; resume only PTID. */
5413 append_resumption (p, endp, ptid, step, siggnal);
5414 }
5415
5416 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5417 putpkt (rs->buf);
5418
5419 if (target_is_non_stop_p ())
5420 {
5421 /* In non-stop, the stub replies to vCont with "OK". The stop
5422 reply will be reported asynchronously by means of a `%Stop'
5423 notification. */
5424 getpkt (&rs->buf, &rs->buf_size, 0);
5425 if (strcmp (rs->buf, "OK") != 0)
5426 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5427 }
5428
5429 return 1;
5430 }
5431
5432 /* Tell the remote machine to resume. */
5433
5434 static void
5435 remote_resume (struct target_ops *ops,
5436 ptid_t ptid, int step, enum gdb_signal siggnal)
5437 {
5438 struct remote_state *rs = get_remote_state ();
5439 char *buf;
5440
5441 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5442 (explained in remote-notif.c:handle_notification) so
5443 remote_notif_process is not called. We need find a place where
5444 it is safe to start a 'vNotif' sequence. It is good to do it
5445 before resuming inferior, because inferior was stopped and no RSP
5446 traffic at that moment. */
5447 if (!target_is_non_stop_p ())
5448 remote_notif_process (rs->notif_state, &notif_client_stop);
5449
5450 rs->last_sent_signal = siggnal;
5451 rs->last_sent_step = step;
5452
5453 /* The vCont packet doesn't need to specify threads via Hc. */
5454 /* No reverse support (yet) for vCont. */
5455 if (execution_direction != EXEC_REVERSE)
5456 if (remote_vcont_resume (ptid, step, siggnal))
5457 goto done;
5458
5459 /* All other supported resume packets do use Hc, so set the continue
5460 thread. */
5461 if (ptid_equal (ptid, minus_one_ptid))
5462 set_continue_thread (any_thread_ptid);
5463 else
5464 set_continue_thread (ptid);
5465
5466 buf = rs->buf;
5467 if (execution_direction == EXEC_REVERSE)
5468 {
5469 /* We don't pass signals to the target in reverse exec mode. */
5470 if (info_verbose && siggnal != GDB_SIGNAL_0)
5471 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5472 siggnal);
5473
5474 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5475 error (_("Remote reverse-step not supported."));
5476 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5477 error (_("Remote reverse-continue not supported."));
5478
5479 strcpy (buf, step ? "bs" : "bc");
5480 }
5481 else if (siggnal != GDB_SIGNAL_0)
5482 {
5483 buf[0] = step ? 'S' : 'C';
5484 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5485 buf[2] = tohex (((int) siggnal) & 0xf);
5486 buf[3] = '\0';
5487 }
5488 else
5489 strcpy (buf, step ? "s" : "c");
5490
5491 putpkt (buf);
5492
5493 done:
5494 /* We are about to start executing the inferior, let's register it
5495 with the event loop. NOTE: this is the one place where all the
5496 execution commands end up. We could alternatively do this in each
5497 of the execution commands in infcmd.c. */
5498 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5499 into infcmd.c in order to allow inferior function calls to work
5500 NOT asynchronously. */
5501 if (target_can_async_p ())
5502 target_async (1);
5503
5504 /* We've just told the target to resume. The remote server will
5505 wait for the inferior to stop, and then send a stop reply. In
5506 the mean time, we can't start another command/query ourselves
5507 because the stub wouldn't be ready to process it. This applies
5508 only to the base all-stop protocol, however. In non-stop (which
5509 only supports vCont), the stub replies with an "OK", and is
5510 immediate able to process further serial input. */
5511 if (!target_is_non_stop_p ())
5512 rs->waiting_for_stop_reply = 1;
5513 }
5514 \f
5515
5516 /* Set up the signal handler for SIGINT, while the target is
5517 executing, ovewriting the 'regular' SIGINT signal handler. */
5518 static void
5519 async_initialize_sigint_signal_handler (void)
5520 {
5521 signal (SIGINT, async_handle_remote_sigint);
5522 }
5523
5524 /* Signal handler for SIGINT, while the target is executing. */
5525 static void
5526 async_handle_remote_sigint (int sig)
5527 {
5528 signal (sig, async_handle_remote_sigint_twice);
5529 /* Note we need to go through gdb_call_async_signal_handler in order
5530 to wake up the event loop on Windows. */
5531 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5532 }
5533
5534 /* Signal handler for SIGINT, installed after SIGINT has already been
5535 sent once. It will take effect the second time that the user sends
5536 a ^C. */
5537 static void
5538 async_handle_remote_sigint_twice (int sig)
5539 {
5540 signal (sig, async_handle_remote_sigint);
5541 /* See note in async_handle_remote_sigint. */
5542 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5543 }
5544
5545 /* Implementation of to_check_pending_interrupt. */
5546
5547 static void
5548 remote_check_pending_interrupt (struct target_ops *self)
5549 {
5550 struct async_signal_handler *token = async_sigint_remote_twice_token;
5551
5552 if (async_signal_handler_is_marked (token))
5553 {
5554 clear_async_signal_handler (token);
5555 call_async_signal_handler (token);
5556 }
5557 }
5558
5559 /* Perform the real interruption of the target execution, in response
5560 to a ^C. */
5561 static void
5562 async_remote_interrupt (gdb_client_data arg)
5563 {
5564 if (remote_debug)
5565 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5566
5567 target_stop (inferior_ptid);
5568 }
5569
5570 /* Perform interrupt, if the first attempt did not succeed. Just give
5571 up on the target alltogether. */
5572 static void
5573 async_remote_interrupt_twice (gdb_client_data arg)
5574 {
5575 if (remote_debug)
5576 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5577
5578 interrupt_query ();
5579 }
5580
5581 /* Reinstall the usual SIGINT handlers, after the target has
5582 stopped. */
5583 static void
5584 async_cleanup_sigint_signal_handler (void *dummy)
5585 {
5586 signal (SIGINT, handle_sigint);
5587 }
5588
5589 /* Send ^C to target to halt it. Target will respond, and send us a
5590 packet. */
5591 static void (*ofunc) (int);
5592
5593 /* The command line interface's interrupt routine. This function is installed
5594 as a signal handler for SIGINT. The first time a user requests an
5595 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5596 response from the target (it didn't stop when the user requested it),
5597 we ask the user if he'd like to detach from the target. */
5598
5599 static void
5600 sync_remote_interrupt (int signo)
5601 {
5602 /* If this doesn't work, try more severe steps. */
5603 signal (signo, sync_remote_interrupt_twice);
5604
5605 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5606 }
5607
5608 /* The user typed ^C twice. */
5609
5610 static void
5611 sync_remote_interrupt_twice (int signo)
5612 {
5613 signal (signo, ofunc);
5614 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5615 signal (signo, sync_remote_interrupt);
5616 }
5617
5618 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5619 thread, all threads of a remote process, or all threads of all
5620 processes. */
5621
5622 static void
5623 remote_stop_ns (ptid_t ptid)
5624 {
5625 struct remote_state *rs = get_remote_state ();
5626 char *p = rs->buf;
5627 char *endp = rs->buf + get_remote_packet_size ();
5628
5629 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5630 remote_vcont_probe (rs);
5631
5632 if (!rs->supports_vCont.t)
5633 error (_("Remote server does not support stopping threads"));
5634
5635 if (ptid_equal (ptid, minus_one_ptid)
5636 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5637 p += xsnprintf (p, endp - p, "vCont;t");
5638 else
5639 {
5640 ptid_t nptid;
5641
5642 p += xsnprintf (p, endp - p, "vCont;t:");
5643
5644 if (ptid_is_pid (ptid))
5645 /* All (-1) threads of process. */
5646 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5647 else
5648 {
5649 /* Small optimization: if we already have a stop reply for
5650 this thread, no use in telling the stub we want this
5651 stopped. */
5652 if (peek_stop_reply (ptid))
5653 return;
5654
5655 nptid = ptid;
5656 }
5657
5658 write_ptid (p, endp, nptid);
5659 }
5660
5661 /* In non-stop, we get an immediate OK reply. The stop reply will
5662 come in asynchronously by notification. */
5663 putpkt (rs->buf);
5664 getpkt (&rs->buf, &rs->buf_size, 0);
5665 if (strcmp (rs->buf, "OK") != 0)
5666 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5667 }
5668
5669 /* All-stop version of target_interrupt. Sends a break or a ^C to
5670 interrupt the remote target. It is undefined which thread of which
5671 process reports the interrupt. */
5672
5673 static void
5674 remote_interrupt_as (ptid_t ptid)
5675 {
5676 struct remote_state *rs = get_remote_state ();
5677
5678 rs->ctrlc_pending_p = 1;
5679
5680 /* If the inferior is stopped already, but the core didn't know
5681 about it yet, just ignore the request. The cached wait status
5682 will be collected in remote_wait. */
5683 if (rs->cached_wait_status)
5684 return;
5685
5686 /* Send interrupt_sequence to remote target. */
5687 send_interrupt_sequence ();
5688 }
5689
5690 /* Implement the to_stop function for the remote targets. */
5691
5692 static void
5693 remote_stop (struct target_ops *self, ptid_t ptid)
5694 {
5695 if (remote_debug)
5696 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5697
5698 if (target_is_non_stop_p ())
5699 remote_stop_ns (ptid);
5700 else
5701 {
5702 /* We don't currently have a way to transparently pause the
5703 remote target in all-stop mode. Interrupt it instead. */
5704 remote_interrupt_as (ptid);
5705 }
5706 }
5707
5708 /* Implement the to_interrupt function for the remote targets. */
5709
5710 static void
5711 remote_interrupt (struct target_ops *self, ptid_t ptid)
5712 {
5713 if (remote_debug)
5714 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5715
5716 if (target_is_non_stop_p ())
5717 {
5718 /* We don't currently have a way to ^C the remote target in
5719 non-stop mode. Stop it (with no signal) instead. */
5720 remote_stop_ns (ptid);
5721 }
5722 else
5723 remote_interrupt_as (ptid);
5724 }
5725
5726 /* Ask the user what to do when an interrupt is received. */
5727
5728 static void
5729 interrupt_query (void)
5730 {
5731 struct remote_state *rs = get_remote_state ();
5732 struct cleanup *old_chain;
5733
5734 old_chain = make_cleanup_restore_target_terminal ();
5735 target_terminal_ours ();
5736
5737 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5738 {
5739 if (query (_("The target is not responding to interrupt requests.\n"
5740 "Stop debugging it? ")))
5741 {
5742 remote_unpush_target ();
5743 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5744 }
5745 }
5746 else
5747 {
5748 if (query (_("Interrupted while waiting for the program.\n"
5749 "Give up waiting? ")))
5750 quit ();
5751 }
5752
5753 do_cleanups (old_chain);
5754 }
5755
5756 /* Enable/disable target terminal ownership. Most targets can use
5757 terminal groups to control terminal ownership. Remote targets are
5758 different in that explicit transfer of ownership to/from GDB/target
5759 is required. */
5760
5761 static void
5762 remote_terminal_inferior (struct target_ops *self)
5763 {
5764 if (!target_async_permitted)
5765 /* Nothing to do. */
5766 return;
5767
5768 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5769 idempotent. The event-loop GDB talking to an asynchronous target
5770 with a synchronous command calls this function from both
5771 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5772 transfer the terminal to the target when it shouldn't this guard
5773 can go away. */
5774 if (!remote_async_terminal_ours_p)
5775 return;
5776 delete_file_handler (input_fd);
5777 remote_async_terminal_ours_p = 0;
5778 async_initialize_sigint_signal_handler ();
5779 /* NOTE: At this point we could also register our selves as the
5780 recipient of all input. Any characters typed could then be
5781 passed on down to the target. */
5782 }
5783
5784 static void
5785 remote_terminal_ours (struct target_ops *self)
5786 {
5787 if (!target_async_permitted)
5788 /* Nothing to do. */
5789 return;
5790
5791 /* See FIXME in remote_terminal_inferior. */
5792 if (remote_async_terminal_ours_p)
5793 return;
5794 async_cleanup_sigint_signal_handler (NULL);
5795 add_file_handler (input_fd, stdin_event_handler, 0);
5796 remote_async_terminal_ours_p = 1;
5797 }
5798
5799 static void
5800 remote_console_output (char *msg)
5801 {
5802 char *p;
5803
5804 for (p = msg; p[0] && p[1]; p += 2)
5805 {
5806 char tb[2];
5807 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5808
5809 tb[0] = c;
5810 tb[1] = 0;
5811 fputs_unfiltered (tb, gdb_stdtarg);
5812 }
5813 gdb_flush (gdb_stdtarg);
5814 }
5815
5816 typedef struct cached_reg
5817 {
5818 int num;
5819 gdb_byte data[MAX_REGISTER_SIZE];
5820 } cached_reg_t;
5821
5822 DEF_VEC_O(cached_reg_t);
5823
5824 typedef struct stop_reply
5825 {
5826 struct notif_event base;
5827
5828 /* The identifier of the thread about this event */
5829 ptid_t ptid;
5830
5831 /* The remote state this event is associated with. When the remote
5832 connection, represented by a remote_state object, is closed,
5833 all the associated stop_reply events should be released. */
5834 struct remote_state *rs;
5835
5836 struct target_waitstatus ws;
5837
5838 /* Expedited registers. This makes remote debugging a bit more
5839 efficient for those targets that provide critical registers as
5840 part of their normal status mechanism (as another roundtrip to
5841 fetch them is avoided). */
5842 VEC(cached_reg_t) *regcache;
5843
5844 enum target_stop_reason stop_reason;
5845
5846 CORE_ADDR watch_data_address;
5847
5848 int core;
5849 } *stop_reply_p;
5850
5851 DECLARE_QUEUE_P (stop_reply_p);
5852 DEFINE_QUEUE_P (stop_reply_p);
5853 /* The list of already fetched and acknowledged stop events. This
5854 queue is used for notification Stop, and other notifications
5855 don't need queue for their events, because the notification events
5856 of Stop can't be consumed immediately, so that events should be
5857 queued first, and be consumed by remote_wait_{ns,as} one per
5858 time. Other notifications can consume their events immediately,
5859 so queue is not needed for them. */
5860 static QUEUE (stop_reply_p) *stop_reply_queue;
5861
5862 static void
5863 stop_reply_xfree (struct stop_reply *r)
5864 {
5865 notif_event_xfree ((struct notif_event *) r);
5866 }
5867
5868 /* Return the length of the stop reply queue. */
5869
5870 static int
5871 stop_reply_queue_length (void)
5872 {
5873 return QUEUE_length (stop_reply_p, stop_reply_queue);
5874 }
5875
5876 static void
5877 remote_notif_stop_parse (struct notif_client *self, char *buf,
5878 struct notif_event *event)
5879 {
5880 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5881 }
5882
5883 static void
5884 remote_notif_stop_ack (struct notif_client *self, char *buf,
5885 struct notif_event *event)
5886 {
5887 struct stop_reply *stop_reply = (struct stop_reply *) event;
5888
5889 /* acknowledge */
5890 putpkt ((char *) self->ack_command);
5891
5892 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5893 /* We got an unknown stop reply. */
5894 error (_("Unknown stop reply"));
5895
5896 push_stop_reply (stop_reply);
5897 }
5898
5899 static int
5900 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5901 {
5902 /* We can't get pending events in remote_notif_process for
5903 notification stop, and we have to do this in remote_wait_ns
5904 instead. If we fetch all queued events from stub, remote stub
5905 may exit and we have no chance to process them back in
5906 remote_wait_ns. */
5907 mark_async_event_handler (remote_async_inferior_event_token);
5908 return 0;
5909 }
5910
5911 static void
5912 stop_reply_dtr (struct notif_event *event)
5913 {
5914 struct stop_reply *r = (struct stop_reply *) event;
5915
5916 VEC_free (cached_reg_t, r->regcache);
5917 }
5918
5919 static struct notif_event *
5920 remote_notif_stop_alloc_reply (void)
5921 {
5922 /* We cast to a pointer to the "base class". */
5923 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5924
5925 r->dtr = stop_reply_dtr;
5926
5927 return r;
5928 }
5929
5930 /* A client of notification Stop. */
5931
5932 struct notif_client notif_client_stop =
5933 {
5934 "Stop",
5935 "vStopped",
5936 remote_notif_stop_parse,
5937 remote_notif_stop_ack,
5938 remote_notif_stop_can_get_pending_events,
5939 remote_notif_stop_alloc_reply,
5940 REMOTE_NOTIF_STOP,
5941 };
5942
5943 /* A parameter to pass data in and out. */
5944
5945 struct queue_iter_param
5946 {
5947 void *input;
5948 struct stop_reply *output;
5949 };
5950
5951 /* Determine if THREAD is a pending fork parent thread. ARG contains
5952 the pid of the process that owns the threads we want to check, or
5953 -1 if we want to check all threads. */
5954
5955 static int
5956 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5957 ptid_t thread_ptid)
5958 {
5959 if (ws->kind == TARGET_WAITKIND_FORKED
5960 || ws->kind == TARGET_WAITKIND_VFORKED)
5961 {
5962 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5963 return 1;
5964 }
5965
5966 return 0;
5967 }
5968
5969 /* Check whether EVENT is a fork event, and if it is, remove the
5970 fork child from the context list passed in DATA. */
5971
5972 static int
5973 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5974 QUEUE_ITER (stop_reply_p) *iter,
5975 stop_reply_p event,
5976 void *data)
5977 {
5978 struct queue_iter_param *param = (struct queue_iter_param *) data;
5979 struct threads_listing_context *context
5980 = (struct threads_listing_context *) param->input;
5981
5982 if (event->ws.kind == TARGET_WAITKIND_FORKED
5983 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5984 {
5985 threads_listing_context_remove (&event->ws, context);
5986 }
5987
5988 return 1;
5989 }
5990
5991 /* If CONTEXT contains any fork child threads that have not been
5992 reported yet, remove them from the CONTEXT list. If such a
5993 thread exists it is because we are stopped at a fork catchpoint
5994 and have not yet called follow_fork, which will set up the
5995 host-side data structures for the new process. */
5996
5997 static void
5998 remove_new_fork_children (struct threads_listing_context *context)
5999 {
6000 struct thread_info * thread;
6001 int pid = -1;
6002 struct notif_client *notif = &notif_client_stop;
6003 struct queue_iter_param param;
6004
6005 /* For any threads stopped at a fork event, remove the corresponding
6006 fork child threads from the CONTEXT list. */
6007 ALL_NON_EXITED_THREADS (thread)
6008 {
6009 struct target_waitstatus *ws = &thread->pending_follow;
6010
6011 if (is_pending_fork_parent (ws, pid, thread->ptid))
6012 {
6013 threads_listing_context_remove (ws, context);
6014 }
6015 }
6016
6017 /* Check for any pending fork events (not reported or processed yet)
6018 in process PID and remove those fork child threads from the
6019 CONTEXT list as well. */
6020 remote_notif_get_pending_events (notif);
6021 param.input = context;
6022 param.output = NULL;
6023 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6024 remove_child_of_pending_fork, &param);
6025 }
6026
6027 /* Remove stop replies in the queue if its pid is equal to the given
6028 inferior's pid. */
6029
6030 static int
6031 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6032 QUEUE_ITER (stop_reply_p) *iter,
6033 stop_reply_p event,
6034 void *data)
6035 {
6036 struct queue_iter_param *param = (struct queue_iter_param *) data;
6037 struct inferior *inf = (struct inferior *) param->input;
6038
6039 if (ptid_get_pid (event->ptid) == inf->pid)
6040 {
6041 stop_reply_xfree (event);
6042 QUEUE_remove_elem (stop_reply_p, q, iter);
6043 }
6044
6045 return 1;
6046 }
6047
6048 /* Discard all pending stop replies of inferior INF. */
6049
6050 static void
6051 discard_pending_stop_replies (struct inferior *inf)
6052 {
6053 int i;
6054 struct queue_iter_param param;
6055 struct stop_reply *reply;
6056 struct remote_state *rs = get_remote_state ();
6057 struct remote_notif_state *rns = rs->notif_state;
6058
6059 /* This function can be notified when an inferior exists. When the
6060 target is not remote, the notification state is NULL. */
6061 if (rs->remote_desc == NULL)
6062 return;
6063
6064 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6065
6066 /* Discard the in-flight notification. */
6067 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6068 {
6069 stop_reply_xfree (reply);
6070 rns->pending_event[notif_client_stop.id] = NULL;
6071 }
6072
6073 param.input = inf;
6074 param.output = NULL;
6075 /* Discard the stop replies we have already pulled with
6076 vStopped. */
6077 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6078 remove_stop_reply_for_inferior, &param);
6079 }
6080
6081 /* If its remote state is equal to the given remote state,
6082 remove EVENT from the stop reply queue. */
6083
6084 static int
6085 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6086 QUEUE_ITER (stop_reply_p) *iter,
6087 stop_reply_p event,
6088 void *data)
6089 {
6090 struct queue_iter_param *param = (struct queue_iter_param *) data;
6091 struct remote_state *rs = (struct remote_state *) param->input;
6092
6093 if (event->rs == rs)
6094 {
6095 stop_reply_xfree (event);
6096 QUEUE_remove_elem (stop_reply_p, q, iter);
6097 }
6098
6099 return 1;
6100 }
6101
6102 /* Discard the stop replies for RS in stop_reply_queue. */
6103
6104 static void
6105 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6106 {
6107 struct queue_iter_param param;
6108
6109 param.input = rs;
6110 param.output = NULL;
6111 /* Discard the stop replies we have already pulled with
6112 vStopped. */
6113 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6114 remove_stop_reply_of_remote_state, &param);
6115 }
6116
6117 /* A parameter to pass data in and out. */
6118
6119 static int
6120 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6121 QUEUE_ITER (stop_reply_p) *iter,
6122 stop_reply_p event,
6123 void *data)
6124 {
6125 struct queue_iter_param *param = (struct queue_iter_param *) data;
6126 ptid_t *ptid = (ptid_t *) param->input;
6127
6128 if (ptid_match (event->ptid, *ptid))
6129 {
6130 param->output = event;
6131 QUEUE_remove_elem (stop_reply_p, q, iter);
6132 return 0;
6133 }
6134
6135 return 1;
6136 }
6137
6138 /* Remove the first reply in 'stop_reply_queue' which matches
6139 PTID. */
6140
6141 static struct stop_reply *
6142 remote_notif_remove_queued_reply (ptid_t ptid)
6143 {
6144 struct queue_iter_param param;
6145
6146 param.input = &ptid;
6147 param.output = NULL;
6148
6149 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6150 remote_notif_remove_once_on_match, &param);
6151 if (notif_debug)
6152 fprintf_unfiltered (gdb_stdlog,
6153 "notif: discard queued event: 'Stop' in %s\n",
6154 target_pid_to_str (ptid));
6155
6156 return param.output;
6157 }
6158
6159 /* Look for a queued stop reply belonging to PTID. If one is found,
6160 remove it from the queue, and return it. Returns NULL if none is
6161 found. If there are still queued events left to process, tell the
6162 event loop to get back to target_wait soon. */
6163
6164 static struct stop_reply *
6165 queued_stop_reply (ptid_t ptid)
6166 {
6167 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6168
6169 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6170 /* There's still at least an event left. */
6171 mark_async_event_handler (remote_async_inferior_event_token);
6172
6173 return r;
6174 }
6175
6176 /* Push a fully parsed stop reply in the stop reply queue. Since we
6177 know that we now have at least one queued event left to pass to the
6178 core side, tell the event loop to get back to target_wait soon. */
6179
6180 static void
6181 push_stop_reply (struct stop_reply *new_event)
6182 {
6183 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6184
6185 if (notif_debug)
6186 fprintf_unfiltered (gdb_stdlog,
6187 "notif: push 'Stop' %s to queue %d\n",
6188 target_pid_to_str (new_event->ptid),
6189 QUEUE_length (stop_reply_p,
6190 stop_reply_queue));
6191
6192 mark_async_event_handler (remote_async_inferior_event_token);
6193 }
6194
6195 static int
6196 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6197 QUEUE_ITER (stop_reply_p) *iter,
6198 struct stop_reply *event,
6199 void *data)
6200 {
6201 ptid_t *ptid = (ptid_t *) data;
6202
6203 return !(ptid_equal (*ptid, event->ptid)
6204 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6205 }
6206
6207 /* Returns true if we have a stop reply for PTID. */
6208
6209 static int
6210 peek_stop_reply (ptid_t ptid)
6211 {
6212 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6213 stop_reply_match_ptid_and_ws, &ptid);
6214 }
6215
6216 /* Skip PACKET until the next semi-colon (or end of string). */
6217
6218 static char *
6219 skip_to_semicolon (char *p)
6220 {
6221 while (*p != '\0' && *p != ';')
6222 p++;
6223 return p;
6224 }
6225
6226 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6227 starting with P and ending with PEND matches PREFIX. */
6228
6229 static int
6230 strprefix (const char *p, const char *pend, const char *prefix)
6231 {
6232 for ( ; p < pend; p++, prefix++)
6233 if (*p != *prefix)
6234 return 0;
6235 return *prefix == '\0';
6236 }
6237
6238 /* Parse the stop reply in BUF. Either the function succeeds, and the
6239 result is stored in EVENT, or throws an error. */
6240
6241 static void
6242 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6243 {
6244 struct remote_arch_state *rsa = get_remote_arch_state ();
6245 ULONGEST addr;
6246 char *p;
6247 int skipregs = 0;
6248
6249 event->ptid = null_ptid;
6250 event->rs = get_remote_state ();
6251 event->ws.kind = TARGET_WAITKIND_IGNORE;
6252 event->ws.value.integer = 0;
6253 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6254 event->regcache = NULL;
6255 event->core = -1;
6256
6257 switch (buf[0])
6258 {
6259 case 'T': /* Status with PC, SP, FP, ... */
6260 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6261 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6262 ss = signal number
6263 n... = register number
6264 r... = register contents
6265 */
6266
6267 p = &buf[3]; /* after Txx */
6268 while (*p)
6269 {
6270 char *p1;
6271 int fieldsize;
6272
6273 p1 = strchr (p, ':');
6274 if (p1 == NULL)
6275 error (_("Malformed packet(a) (missing colon): %s\n\
6276 Packet: '%s'\n"),
6277 p, buf);
6278 if (p == p1)
6279 error (_("Malformed packet(a) (missing register number): %s\n\
6280 Packet: '%s'\n"),
6281 p, buf);
6282
6283 /* Some "registers" are actually extended stop information.
6284 Note if you're adding a new entry here: GDB 7.9 and
6285 earlier assume that all register "numbers" that start
6286 with an hex digit are real register numbers. Make sure
6287 the server only sends such a packet if it knows the
6288 client understands it. */
6289
6290 if (strprefix (p, p1, "thread"))
6291 event->ptid = read_ptid (++p1, &p);
6292 else if (strprefix (p, p1, "watch")
6293 || strprefix (p, p1, "rwatch")
6294 || strprefix (p, p1, "awatch"))
6295 {
6296 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6297 p = unpack_varlen_hex (++p1, &addr);
6298 event->watch_data_address = (CORE_ADDR) addr;
6299 }
6300 else if (strprefix (p, p1, "swbreak"))
6301 {
6302 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6303
6304 /* Make sure the stub doesn't forget to indicate support
6305 with qSupported. */
6306 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6307 error (_("Unexpected swbreak stop reason"));
6308
6309 /* The value part is documented as "must be empty",
6310 though we ignore it, in case we ever decide to make
6311 use of it in a backward compatible way. */
6312 p = skip_to_semicolon (p1 + 1);
6313 }
6314 else if (strprefix (p, p1, "hwbreak"))
6315 {
6316 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6317
6318 /* Make sure the stub doesn't forget to indicate support
6319 with qSupported. */
6320 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6321 error (_("Unexpected hwbreak stop reason"));
6322
6323 /* See above. */
6324 p = skip_to_semicolon (p1 + 1);
6325 }
6326 else if (strprefix (p, p1, "library"))
6327 {
6328 event->ws.kind = TARGET_WAITKIND_LOADED;
6329 p = skip_to_semicolon (p1 + 1);
6330 }
6331 else if (strprefix (p, p1, "replaylog"))
6332 {
6333 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6334 /* p1 will indicate "begin" or "end", but it makes
6335 no difference for now, so ignore it. */
6336 p = skip_to_semicolon (p1 + 1);
6337 }
6338 else if (strprefix (p, p1, "core"))
6339 {
6340 ULONGEST c;
6341
6342 p = unpack_varlen_hex (++p1, &c);
6343 event->core = c;
6344 }
6345 else if (strprefix (p, p1, "fork"))
6346 {
6347 event->ws.value.related_pid = read_ptid (++p1, &p);
6348 event->ws.kind = TARGET_WAITKIND_FORKED;
6349 }
6350 else if (strprefix (p, p1, "vfork"))
6351 {
6352 event->ws.value.related_pid = read_ptid (++p1, &p);
6353 event->ws.kind = TARGET_WAITKIND_VFORKED;
6354 }
6355 else if (strprefix (p, p1, "vforkdone"))
6356 {
6357 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6358 p = skip_to_semicolon (p1 + 1);
6359 }
6360 else if (strprefix (p, p1, "exec"))
6361 {
6362 ULONGEST ignored;
6363 char pathname[PATH_MAX];
6364 int pathlen;
6365
6366 /* Determine the length of the execd pathname. */
6367 p = unpack_varlen_hex (++p1, &ignored);
6368 pathlen = (p - p1) / 2;
6369
6370 /* Save the pathname for event reporting and for
6371 the next run command. */
6372 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6373 pathname[pathlen] = '\0';
6374
6375 /* This is freed during event handling. */
6376 event->ws.value.execd_pathname = xstrdup (pathname);
6377 event->ws.kind = TARGET_WAITKIND_EXECD;
6378
6379 /* Skip the registers included in this packet, since
6380 they may be for an architecture different from the
6381 one used by the original program. */
6382 skipregs = 1;
6383 }
6384 else
6385 {
6386 ULONGEST pnum;
6387 char *p_temp;
6388
6389 if (skipregs)
6390 {
6391 p = skip_to_semicolon (p1 + 1);
6392 p++;
6393 continue;
6394 }
6395
6396 /* Maybe a real ``P'' register number. */
6397 p_temp = unpack_varlen_hex (p, &pnum);
6398 /* If the first invalid character is the colon, we got a
6399 register number. Otherwise, it's an unknown stop
6400 reason. */
6401 if (p_temp == p1)
6402 {
6403 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6404 cached_reg_t cached_reg;
6405
6406 if (reg == NULL)
6407 error (_("Remote sent bad register number %s: %s\n\
6408 Packet: '%s'\n"),
6409 hex_string (pnum), p, buf);
6410
6411 cached_reg.num = reg->regnum;
6412
6413 p = p1 + 1;
6414 fieldsize = hex2bin (p, cached_reg.data,
6415 register_size (target_gdbarch (),
6416 reg->regnum));
6417 p += 2 * fieldsize;
6418 if (fieldsize < register_size (target_gdbarch (),
6419 reg->regnum))
6420 warning (_("Remote reply is too short: %s"), buf);
6421
6422 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6423 }
6424 else
6425 {
6426 /* Not a number. Silently skip unknown optional
6427 info. */
6428 p = skip_to_semicolon (p1 + 1);
6429 }
6430 }
6431
6432 if (*p != ';')
6433 error (_("Remote register badly formatted: %s\nhere: %s"),
6434 buf, p);
6435 ++p;
6436 }
6437
6438 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6439 break;
6440
6441 /* fall through */
6442 case 'S': /* Old style status, just signal only. */
6443 {
6444 int sig;
6445
6446 event->ws.kind = TARGET_WAITKIND_STOPPED;
6447 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6448 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6449 event->ws.value.sig = (enum gdb_signal) sig;
6450 else
6451 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6452 }
6453 break;
6454 case 'W': /* Target exited. */
6455 case 'X':
6456 {
6457 char *p;
6458 int pid;
6459 ULONGEST value;
6460
6461 /* GDB used to accept only 2 hex chars here. Stubs should
6462 only send more if they detect GDB supports multi-process
6463 support. */
6464 p = unpack_varlen_hex (&buf[1], &value);
6465
6466 if (buf[0] == 'W')
6467 {
6468 /* The remote process exited. */
6469 event->ws.kind = TARGET_WAITKIND_EXITED;
6470 event->ws.value.integer = value;
6471 }
6472 else
6473 {
6474 /* The remote process exited with a signal. */
6475 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6476 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6477 event->ws.value.sig = (enum gdb_signal) value;
6478 else
6479 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6480 }
6481
6482 /* If no process is specified, assume inferior_ptid. */
6483 pid = ptid_get_pid (inferior_ptid);
6484 if (*p == '\0')
6485 ;
6486 else if (*p == ';')
6487 {
6488 p++;
6489
6490 if (*p == '\0')
6491 ;
6492 else if (startswith (p, "process:"))
6493 {
6494 ULONGEST upid;
6495
6496 p += sizeof ("process:") - 1;
6497 unpack_varlen_hex (p, &upid);
6498 pid = upid;
6499 }
6500 else
6501 error (_("unknown stop reply packet: %s"), buf);
6502 }
6503 else
6504 error (_("unknown stop reply packet: %s"), buf);
6505 event->ptid = pid_to_ptid (pid);
6506 }
6507 break;
6508 }
6509
6510 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6511 error (_("No process or thread specified in stop reply: %s"), buf);
6512 }
6513
6514 /* When the stub wants to tell GDB about a new notification reply, it
6515 sends a notification (%Stop, for example). Those can come it at
6516 any time, hence, we have to make sure that any pending
6517 putpkt/getpkt sequence we're making is finished, before querying
6518 the stub for more events with the corresponding ack command
6519 (vStopped, for example). E.g., if we started a vStopped sequence
6520 immediately upon receiving the notification, something like this
6521 could happen:
6522
6523 1.1) --> Hg 1
6524 1.2) <-- OK
6525 1.3) --> g
6526 1.4) <-- %Stop
6527 1.5) --> vStopped
6528 1.6) <-- (registers reply to step #1.3)
6529
6530 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6531 query.
6532
6533 To solve this, whenever we parse a %Stop notification successfully,
6534 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6535 doing whatever we were doing:
6536
6537 2.1) --> Hg 1
6538 2.2) <-- OK
6539 2.3) --> g
6540 2.4) <-- %Stop
6541 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6542 2.5) <-- (registers reply to step #2.3)
6543
6544 Eventualy after step #2.5, we return to the event loop, which
6545 notices there's an event on the
6546 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6547 associated callback --- the function below. At this point, we're
6548 always safe to start a vStopped sequence. :
6549
6550 2.6) --> vStopped
6551 2.7) <-- T05 thread:2
6552 2.8) --> vStopped
6553 2.9) --> OK
6554 */
6555
6556 void
6557 remote_notif_get_pending_events (struct notif_client *nc)
6558 {
6559 struct remote_state *rs = get_remote_state ();
6560
6561 if (rs->notif_state->pending_event[nc->id] != NULL)
6562 {
6563 if (notif_debug)
6564 fprintf_unfiltered (gdb_stdlog,
6565 "notif: process: '%s' ack pending event\n",
6566 nc->name);
6567
6568 /* acknowledge */
6569 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6570 rs->notif_state->pending_event[nc->id] = NULL;
6571
6572 while (1)
6573 {
6574 getpkt (&rs->buf, &rs->buf_size, 0);
6575 if (strcmp (rs->buf, "OK") == 0)
6576 break;
6577 else
6578 remote_notif_ack (nc, rs->buf);
6579 }
6580 }
6581 else
6582 {
6583 if (notif_debug)
6584 fprintf_unfiltered (gdb_stdlog,
6585 "notif: process: '%s' no pending reply\n",
6586 nc->name);
6587 }
6588 }
6589
6590 /* Called when it is decided that STOP_REPLY holds the info of the
6591 event that is to be returned to the core. This function always
6592 destroys STOP_REPLY. */
6593
6594 static ptid_t
6595 process_stop_reply (struct stop_reply *stop_reply,
6596 struct target_waitstatus *status)
6597 {
6598 ptid_t ptid;
6599
6600 *status = stop_reply->ws;
6601 ptid = stop_reply->ptid;
6602
6603 /* If no thread/process was reported by the stub, assume the current
6604 inferior. */
6605 if (ptid_equal (ptid, null_ptid))
6606 ptid = inferior_ptid;
6607
6608 if (status->kind != TARGET_WAITKIND_EXITED
6609 && status->kind != TARGET_WAITKIND_SIGNALLED)
6610 {
6611 struct remote_state *rs = get_remote_state ();
6612
6613 /* Expedited registers. */
6614 if (stop_reply->regcache)
6615 {
6616 struct regcache *regcache
6617 = get_thread_arch_regcache (ptid, target_gdbarch ());
6618 cached_reg_t *reg;
6619 int ix;
6620
6621 for (ix = 0;
6622 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6623 ix++)
6624 regcache_raw_supply (regcache, reg->num, reg->data);
6625 VEC_free (cached_reg_t, stop_reply->regcache);
6626 }
6627
6628 rs->stop_reason = stop_reply->stop_reason;
6629 rs->remote_watch_data_address = stop_reply->watch_data_address;
6630
6631 remote_notice_new_inferior (ptid, 0);
6632 demand_private_info (ptid)->core = stop_reply->core;
6633 }
6634
6635 stop_reply_xfree (stop_reply);
6636 return ptid;
6637 }
6638
6639 /* The non-stop mode version of target_wait. */
6640
6641 static ptid_t
6642 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6643 {
6644 struct remote_state *rs = get_remote_state ();
6645 struct stop_reply *stop_reply;
6646 int ret;
6647 int is_notif = 0;
6648
6649 /* If in non-stop mode, get out of getpkt even if a
6650 notification is received. */
6651
6652 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6653 0 /* forever */, &is_notif);
6654 while (1)
6655 {
6656 if (ret != -1 && !is_notif)
6657 switch (rs->buf[0])
6658 {
6659 case 'E': /* Error of some sort. */
6660 /* We're out of sync with the target now. Did it continue
6661 or not? We can't tell which thread it was in non-stop,
6662 so just ignore this. */
6663 warning (_("Remote failure reply: %s"), rs->buf);
6664 break;
6665 case 'O': /* Console output. */
6666 remote_console_output (rs->buf + 1);
6667 break;
6668 default:
6669 warning (_("Invalid remote reply: %s"), rs->buf);
6670 break;
6671 }
6672
6673 /* Acknowledge a pending stop reply that may have arrived in the
6674 mean time. */
6675 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6676 remote_notif_get_pending_events (&notif_client_stop);
6677
6678 /* If indeed we noticed a stop reply, we're done. */
6679 stop_reply = queued_stop_reply (ptid);
6680 if (stop_reply != NULL)
6681 return process_stop_reply (stop_reply, status);
6682
6683 /* Still no event. If we're just polling for an event, then
6684 return to the event loop. */
6685 if (options & TARGET_WNOHANG)
6686 {
6687 status->kind = TARGET_WAITKIND_IGNORE;
6688 return minus_one_ptid;
6689 }
6690
6691 /* Otherwise do a blocking wait. */
6692 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6693 1 /* forever */, &is_notif);
6694 }
6695 }
6696
6697 /* Wait until the remote machine stops, then return, storing status in
6698 STATUS just as `wait' would. */
6699
6700 static ptid_t
6701 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6702 {
6703 struct remote_state *rs = get_remote_state ();
6704 ptid_t event_ptid = null_ptid;
6705 char *buf;
6706 struct stop_reply *stop_reply;
6707
6708 again:
6709
6710 status->kind = TARGET_WAITKIND_IGNORE;
6711 status->value.integer = 0;
6712
6713 stop_reply = queued_stop_reply (ptid);
6714 if (stop_reply != NULL)
6715 return process_stop_reply (stop_reply, status);
6716
6717 if (rs->cached_wait_status)
6718 /* Use the cached wait status, but only once. */
6719 rs->cached_wait_status = 0;
6720 else
6721 {
6722 int ret;
6723 int is_notif;
6724 int forever = ((options & TARGET_WNOHANG) == 0
6725 && wait_forever_enabled_p);
6726
6727 if (!rs->waiting_for_stop_reply)
6728 {
6729 status->kind = TARGET_WAITKIND_NO_RESUMED;
6730 return minus_one_ptid;
6731 }
6732
6733 if (!target_is_async_p ())
6734 {
6735 ofunc = signal (SIGINT, sync_remote_interrupt);
6736 /* If the user hit C-c before this packet, or between packets,
6737 pretend that it was hit right here. */
6738 if (check_quit_flag ())
6739 {
6740 clear_quit_flag ();
6741 sync_remote_interrupt (SIGINT);
6742 }
6743 }
6744
6745 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6746 _never_ wait for ever -> test on target_is_async_p().
6747 However, before we do that we need to ensure that the caller
6748 knows how to take the target into/out of async mode. */
6749 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6750 forever, &is_notif);
6751
6752 if (!target_is_async_p ())
6753 signal (SIGINT, ofunc);
6754
6755 /* GDB gets a notification. Return to core as this event is
6756 not interesting. */
6757 if (ret != -1 && is_notif)
6758 return minus_one_ptid;
6759
6760 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6761 return minus_one_ptid;
6762 }
6763
6764 buf = rs->buf;
6765
6766 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6767
6768 /* Assume that the target has acknowledged Ctrl-C unless we receive
6769 an 'F' or 'O' packet. */
6770 if (buf[0] != 'F' && buf[0] != 'O')
6771 rs->ctrlc_pending_p = 0;
6772
6773 switch (buf[0])
6774 {
6775 case 'E': /* Error of some sort. */
6776 /* We're out of sync with the target now. Did it continue or
6777 not? Not is more likely, so report a stop. */
6778 rs->waiting_for_stop_reply = 0;
6779
6780 warning (_("Remote failure reply: %s"), buf);
6781 status->kind = TARGET_WAITKIND_STOPPED;
6782 status->value.sig = GDB_SIGNAL_0;
6783 break;
6784 case 'F': /* File-I/O request. */
6785 remote_fileio_request (buf, rs->ctrlc_pending_p);
6786 rs->ctrlc_pending_p = 0;
6787 break;
6788 case 'T': case 'S': case 'X': case 'W':
6789 {
6790 struct stop_reply *stop_reply;
6791
6792 /* There is a stop reply to handle. */
6793 rs->waiting_for_stop_reply = 0;
6794
6795 stop_reply
6796 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6797 rs->buf);
6798
6799 event_ptid = process_stop_reply (stop_reply, status);
6800 break;
6801 }
6802 case 'O': /* Console output. */
6803 remote_console_output (buf + 1);
6804 break;
6805 case '\0':
6806 if (rs->last_sent_signal != GDB_SIGNAL_0)
6807 {
6808 /* Zero length reply means that we tried 'S' or 'C' and the
6809 remote system doesn't support it. */
6810 target_terminal_ours_for_output ();
6811 printf_filtered
6812 ("Can't send signals to this remote system. %s not sent.\n",
6813 gdb_signal_to_name (rs->last_sent_signal));
6814 rs->last_sent_signal = GDB_SIGNAL_0;
6815 target_terminal_inferior ();
6816
6817 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6818 putpkt ((char *) buf);
6819 break;
6820 }
6821 /* else fallthrough */
6822 default:
6823 warning (_("Invalid remote reply: %s"), buf);
6824 break;
6825 }
6826
6827 if (status->kind == TARGET_WAITKIND_IGNORE)
6828 {
6829 /* Nothing interesting happened. If we're doing a non-blocking
6830 poll, we're done. Otherwise, go back to waiting. */
6831 if (options & TARGET_WNOHANG)
6832 return minus_one_ptid;
6833 else
6834 goto again;
6835 }
6836 else if (status->kind != TARGET_WAITKIND_EXITED
6837 && status->kind != TARGET_WAITKIND_SIGNALLED)
6838 {
6839 if (!ptid_equal (event_ptid, null_ptid))
6840 record_currthread (rs, event_ptid);
6841 else
6842 event_ptid = inferior_ptid;
6843 }
6844 else
6845 /* A process exit. Invalidate our notion of current thread. */
6846 record_currthread (rs, minus_one_ptid);
6847
6848 return event_ptid;
6849 }
6850
6851 /* Wait until the remote machine stops, then return, storing status in
6852 STATUS just as `wait' would. */
6853
6854 static ptid_t
6855 remote_wait (struct target_ops *ops,
6856 ptid_t ptid, struct target_waitstatus *status, int options)
6857 {
6858 ptid_t event_ptid;
6859
6860 if (target_is_non_stop_p ())
6861 event_ptid = remote_wait_ns (ptid, status, options);
6862 else
6863 event_ptid = remote_wait_as (ptid, status, options);
6864
6865 if (target_is_async_p ())
6866 {
6867 /* If there are are events left in the queue tell the event loop
6868 to return here. */
6869 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6870 mark_async_event_handler (remote_async_inferior_event_token);
6871 }
6872
6873 return event_ptid;
6874 }
6875
6876 /* Fetch a single register using a 'p' packet. */
6877
6878 static int
6879 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6880 {
6881 struct remote_state *rs = get_remote_state ();
6882 char *buf, *p;
6883 char regp[MAX_REGISTER_SIZE];
6884 int i;
6885
6886 if (packet_support (PACKET_p) == PACKET_DISABLE)
6887 return 0;
6888
6889 if (reg->pnum == -1)
6890 return 0;
6891
6892 p = rs->buf;
6893 *p++ = 'p';
6894 p += hexnumstr (p, reg->pnum);
6895 *p++ = '\0';
6896 putpkt (rs->buf);
6897 getpkt (&rs->buf, &rs->buf_size, 0);
6898
6899 buf = rs->buf;
6900
6901 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6902 {
6903 case PACKET_OK:
6904 break;
6905 case PACKET_UNKNOWN:
6906 return 0;
6907 case PACKET_ERROR:
6908 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6909 gdbarch_register_name (get_regcache_arch (regcache),
6910 reg->regnum),
6911 buf);
6912 }
6913
6914 /* If this register is unfetchable, tell the regcache. */
6915 if (buf[0] == 'x')
6916 {
6917 regcache_raw_supply (regcache, reg->regnum, NULL);
6918 return 1;
6919 }
6920
6921 /* Otherwise, parse and supply the value. */
6922 p = buf;
6923 i = 0;
6924 while (p[0] != 0)
6925 {
6926 if (p[1] == 0)
6927 error (_("fetch_register_using_p: early buf termination"));
6928
6929 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6930 p += 2;
6931 }
6932 regcache_raw_supply (regcache, reg->regnum, regp);
6933 return 1;
6934 }
6935
6936 /* Fetch the registers included in the target's 'g' packet. */
6937
6938 static int
6939 send_g_packet (void)
6940 {
6941 struct remote_state *rs = get_remote_state ();
6942 int buf_len;
6943
6944 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6945 remote_send (&rs->buf, &rs->buf_size);
6946
6947 /* We can get out of synch in various cases. If the first character
6948 in the buffer is not a hex character, assume that has happened
6949 and try to fetch another packet to read. */
6950 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6951 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6952 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6953 && rs->buf[0] != 'x') /* New: unavailable register value. */
6954 {
6955 if (remote_debug)
6956 fprintf_unfiltered (gdb_stdlog,
6957 "Bad register packet; fetching a new packet\n");
6958 getpkt (&rs->buf, &rs->buf_size, 0);
6959 }
6960
6961 buf_len = strlen (rs->buf);
6962
6963 /* Sanity check the received packet. */
6964 if (buf_len % 2 != 0)
6965 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6966
6967 return buf_len / 2;
6968 }
6969
6970 static void
6971 process_g_packet (struct regcache *regcache)
6972 {
6973 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6974 struct remote_state *rs = get_remote_state ();
6975 struct remote_arch_state *rsa = get_remote_arch_state ();
6976 int i, buf_len;
6977 char *p;
6978 char *regs;
6979
6980 buf_len = strlen (rs->buf);
6981
6982 /* Further sanity checks, with knowledge of the architecture. */
6983 if (buf_len > 2 * rsa->sizeof_g_packet)
6984 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6985
6986 /* Save the size of the packet sent to us by the target. It is used
6987 as a heuristic when determining the max size of packets that the
6988 target can safely receive. */
6989 if (rsa->actual_register_packet_size == 0)
6990 rsa->actual_register_packet_size = buf_len;
6991
6992 /* If this is smaller than we guessed the 'g' packet would be,
6993 update our records. A 'g' reply that doesn't include a register's
6994 value implies either that the register is not available, or that
6995 the 'p' packet must be used. */
6996 if (buf_len < 2 * rsa->sizeof_g_packet)
6997 {
6998 rsa->sizeof_g_packet = buf_len / 2;
6999
7000 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7001 {
7002 if (rsa->regs[i].pnum == -1)
7003 continue;
7004
7005 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7006 rsa->regs[i].in_g_packet = 0;
7007 else
7008 rsa->regs[i].in_g_packet = 1;
7009 }
7010 }
7011
7012 regs = (char *) alloca (rsa->sizeof_g_packet);
7013
7014 /* Unimplemented registers read as all bits zero. */
7015 memset (regs, 0, rsa->sizeof_g_packet);
7016
7017 /* Reply describes registers byte by byte, each byte encoded as two
7018 hex characters. Suck them all up, then supply them to the
7019 register cacheing/storage mechanism. */
7020
7021 p = rs->buf;
7022 for (i = 0; i < rsa->sizeof_g_packet; i++)
7023 {
7024 if (p[0] == 0 || p[1] == 0)
7025 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7026 internal_error (__FILE__, __LINE__,
7027 _("unexpected end of 'g' packet reply"));
7028
7029 if (p[0] == 'x' && p[1] == 'x')
7030 regs[i] = 0; /* 'x' */
7031 else
7032 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7033 p += 2;
7034 }
7035
7036 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7037 {
7038 struct packet_reg *r = &rsa->regs[i];
7039
7040 if (r->in_g_packet)
7041 {
7042 if (r->offset * 2 >= strlen (rs->buf))
7043 /* This shouldn't happen - we adjusted in_g_packet above. */
7044 internal_error (__FILE__, __LINE__,
7045 _("unexpected end of 'g' packet reply"));
7046 else if (rs->buf[r->offset * 2] == 'x')
7047 {
7048 gdb_assert (r->offset * 2 < strlen (rs->buf));
7049 /* The register isn't available, mark it as such (at
7050 the same time setting the value to zero). */
7051 regcache_raw_supply (regcache, r->regnum, NULL);
7052 }
7053 else
7054 regcache_raw_supply (regcache, r->regnum,
7055 regs + r->offset);
7056 }
7057 }
7058 }
7059
7060 static void
7061 fetch_registers_using_g (struct regcache *regcache)
7062 {
7063 send_g_packet ();
7064 process_g_packet (regcache);
7065 }
7066
7067 /* Make the remote selected traceframe match GDB's selected
7068 traceframe. */
7069
7070 static void
7071 set_remote_traceframe (void)
7072 {
7073 int newnum;
7074 struct remote_state *rs = get_remote_state ();
7075
7076 if (rs->remote_traceframe_number == get_traceframe_number ())
7077 return;
7078
7079 /* Avoid recursion, remote_trace_find calls us again. */
7080 rs->remote_traceframe_number = get_traceframe_number ();
7081
7082 newnum = target_trace_find (tfind_number,
7083 get_traceframe_number (), 0, 0, NULL);
7084
7085 /* Should not happen. If it does, all bets are off. */
7086 if (newnum != get_traceframe_number ())
7087 warning (_("could not set remote traceframe"));
7088 }
7089
7090 static void
7091 remote_fetch_registers (struct target_ops *ops,
7092 struct regcache *regcache, int regnum)
7093 {
7094 struct remote_arch_state *rsa = get_remote_arch_state ();
7095 int i;
7096
7097 set_remote_traceframe ();
7098 set_general_thread (inferior_ptid);
7099
7100 if (regnum >= 0)
7101 {
7102 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7103
7104 gdb_assert (reg != NULL);
7105
7106 /* If this register might be in the 'g' packet, try that first -
7107 we are likely to read more than one register. If this is the
7108 first 'g' packet, we might be overly optimistic about its
7109 contents, so fall back to 'p'. */
7110 if (reg->in_g_packet)
7111 {
7112 fetch_registers_using_g (regcache);
7113 if (reg->in_g_packet)
7114 return;
7115 }
7116
7117 if (fetch_register_using_p (regcache, reg))
7118 return;
7119
7120 /* This register is not available. */
7121 regcache_raw_supply (regcache, reg->regnum, NULL);
7122
7123 return;
7124 }
7125
7126 fetch_registers_using_g (regcache);
7127
7128 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7129 if (!rsa->regs[i].in_g_packet)
7130 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7131 {
7132 /* This register is not available. */
7133 regcache_raw_supply (regcache, i, NULL);
7134 }
7135 }
7136
7137 /* Prepare to store registers. Since we may send them all (using a
7138 'G' request), we have to read out the ones we don't want to change
7139 first. */
7140
7141 static void
7142 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7143 {
7144 struct remote_arch_state *rsa = get_remote_arch_state ();
7145 int i;
7146 gdb_byte buf[MAX_REGISTER_SIZE];
7147
7148 /* Make sure the entire registers array is valid. */
7149 switch (packet_support (PACKET_P))
7150 {
7151 case PACKET_DISABLE:
7152 case PACKET_SUPPORT_UNKNOWN:
7153 /* Make sure all the necessary registers are cached. */
7154 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7155 if (rsa->regs[i].in_g_packet)
7156 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7157 break;
7158 case PACKET_ENABLE:
7159 break;
7160 }
7161 }
7162
7163 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7164 packet was not recognized. */
7165
7166 static int
7167 store_register_using_P (const struct regcache *regcache,
7168 struct packet_reg *reg)
7169 {
7170 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7171 struct remote_state *rs = get_remote_state ();
7172 /* Try storing a single register. */
7173 char *buf = rs->buf;
7174 gdb_byte regp[MAX_REGISTER_SIZE];
7175 char *p;
7176
7177 if (packet_support (PACKET_P) == PACKET_DISABLE)
7178 return 0;
7179
7180 if (reg->pnum == -1)
7181 return 0;
7182
7183 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7184 p = buf + strlen (buf);
7185 regcache_raw_collect (regcache, reg->regnum, regp);
7186 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7187 putpkt (rs->buf);
7188 getpkt (&rs->buf, &rs->buf_size, 0);
7189
7190 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7191 {
7192 case PACKET_OK:
7193 return 1;
7194 case PACKET_ERROR:
7195 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7196 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7197 case PACKET_UNKNOWN:
7198 return 0;
7199 default:
7200 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7201 }
7202 }
7203
7204 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7205 contents of the register cache buffer. FIXME: ignores errors. */
7206
7207 static void
7208 store_registers_using_G (const struct regcache *regcache)
7209 {
7210 struct remote_state *rs = get_remote_state ();
7211 struct remote_arch_state *rsa = get_remote_arch_state ();
7212 gdb_byte *regs;
7213 char *p;
7214
7215 /* Extract all the registers in the regcache copying them into a
7216 local buffer. */
7217 {
7218 int i;
7219
7220 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7221 memset (regs, 0, rsa->sizeof_g_packet);
7222 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7223 {
7224 struct packet_reg *r = &rsa->regs[i];
7225
7226 if (r->in_g_packet)
7227 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7228 }
7229 }
7230
7231 /* Command describes registers byte by byte,
7232 each byte encoded as two hex characters. */
7233 p = rs->buf;
7234 *p++ = 'G';
7235 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7236 updated. */
7237 bin2hex (regs, p, rsa->sizeof_g_packet);
7238 putpkt (rs->buf);
7239 getpkt (&rs->buf, &rs->buf_size, 0);
7240 if (packet_check_result (rs->buf) == PACKET_ERROR)
7241 error (_("Could not write registers; remote failure reply '%s'"),
7242 rs->buf);
7243 }
7244
7245 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7246 of the register cache buffer. FIXME: ignores errors. */
7247
7248 static void
7249 remote_store_registers (struct target_ops *ops,
7250 struct regcache *regcache, int regnum)
7251 {
7252 struct remote_arch_state *rsa = get_remote_arch_state ();
7253 int i;
7254
7255 set_remote_traceframe ();
7256 set_general_thread (inferior_ptid);
7257
7258 if (regnum >= 0)
7259 {
7260 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7261
7262 gdb_assert (reg != NULL);
7263
7264 /* Always prefer to store registers using the 'P' packet if
7265 possible; we often change only a small number of registers.
7266 Sometimes we change a larger number; we'd need help from a
7267 higher layer to know to use 'G'. */
7268 if (store_register_using_P (regcache, reg))
7269 return;
7270
7271 /* For now, don't complain if we have no way to write the
7272 register. GDB loses track of unavailable registers too
7273 easily. Some day, this may be an error. We don't have
7274 any way to read the register, either... */
7275 if (!reg->in_g_packet)
7276 return;
7277
7278 store_registers_using_G (regcache);
7279 return;
7280 }
7281
7282 store_registers_using_G (regcache);
7283
7284 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7285 if (!rsa->regs[i].in_g_packet)
7286 if (!store_register_using_P (regcache, &rsa->regs[i]))
7287 /* See above for why we do not issue an error here. */
7288 continue;
7289 }
7290 \f
7291
7292 /* Return the number of hex digits in num. */
7293
7294 static int
7295 hexnumlen (ULONGEST num)
7296 {
7297 int i;
7298
7299 for (i = 0; num != 0; i++)
7300 num >>= 4;
7301
7302 return max (i, 1);
7303 }
7304
7305 /* Set BUF to the minimum number of hex digits representing NUM. */
7306
7307 static int
7308 hexnumstr (char *buf, ULONGEST num)
7309 {
7310 int len = hexnumlen (num);
7311
7312 return hexnumnstr (buf, num, len);
7313 }
7314
7315
7316 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7317
7318 static int
7319 hexnumnstr (char *buf, ULONGEST num, int width)
7320 {
7321 int i;
7322
7323 buf[width] = '\0';
7324
7325 for (i = width - 1; i >= 0; i--)
7326 {
7327 buf[i] = "0123456789abcdef"[(num & 0xf)];
7328 num >>= 4;
7329 }
7330
7331 return width;
7332 }
7333
7334 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7335
7336 static CORE_ADDR
7337 remote_address_masked (CORE_ADDR addr)
7338 {
7339 unsigned int address_size = remote_address_size;
7340
7341 /* If "remoteaddresssize" was not set, default to target address size. */
7342 if (!address_size)
7343 address_size = gdbarch_addr_bit (target_gdbarch ());
7344
7345 if (address_size > 0
7346 && address_size < (sizeof (ULONGEST) * 8))
7347 {
7348 /* Only create a mask when that mask can safely be constructed
7349 in a ULONGEST variable. */
7350 ULONGEST mask = 1;
7351
7352 mask = (mask << address_size) - 1;
7353 addr &= mask;
7354 }
7355 return addr;
7356 }
7357
7358 /* Determine whether the remote target supports binary downloading.
7359 This is accomplished by sending a no-op memory write of zero length
7360 to the target at the specified address. It does not suffice to send
7361 the whole packet, since many stubs strip the eighth bit and
7362 subsequently compute a wrong checksum, which causes real havoc with
7363 remote_write_bytes.
7364
7365 NOTE: This can still lose if the serial line is not eight-bit
7366 clean. In cases like this, the user should clear "remote
7367 X-packet". */
7368
7369 static void
7370 check_binary_download (CORE_ADDR addr)
7371 {
7372 struct remote_state *rs = get_remote_state ();
7373
7374 switch (packet_support (PACKET_X))
7375 {
7376 case PACKET_DISABLE:
7377 break;
7378 case PACKET_ENABLE:
7379 break;
7380 case PACKET_SUPPORT_UNKNOWN:
7381 {
7382 char *p;
7383
7384 p = rs->buf;
7385 *p++ = 'X';
7386 p += hexnumstr (p, (ULONGEST) addr);
7387 *p++ = ',';
7388 p += hexnumstr (p, (ULONGEST) 0);
7389 *p++ = ':';
7390 *p = '\0';
7391
7392 putpkt_binary (rs->buf, (int) (p - rs->buf));
7393 getpkt (&rs->buf, &rs->buf_size, 0);
7394
7395 if (rs->buf[0] == '\0')
7396 {
7397 if (remote_debug)
7398 fprintf_unfiltered (gdb_stdlog,
7399 "binary downloading NOT "
7400 "supported by target\n");
7401 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7402 }
7403 else
7404 {
7405 if (remote_debug)
7406 fprintf_unfiltered (gdb_stdlog,
7407 "binary downloading supported by target\n");
7408 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7409 }
7410 break;
7411 }
7412 }
7413 }
7414
7415 /* Helper function to resize the payload in order to try to get a good
7416 alignment. We try to write an amount of data such that the next write will
7417 start on an address aligned on REMOTE_ALIGN_WRITES. */
7418
7419 static int
7420 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7421 {
7422 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7423 }
7424
7425 /* Write memory data directly to the remote machine.
7426 This does not inform the data cache; the data cache uses this.
7427 HEADER is the starting part of the packet.
7428 MEMADDR is the address in the remote memory space.
7429 MYADDR is the address of the buffer in our space.
7430 LEN_UNITS is the number of addressable units to write.
7431 UNIT_SIZE is the length in bytes of an addressable unit.
7432 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7433 should send data as binary ('X'), or hex-encoded ('M').
7434
7435 The function creates packet of the form
7436 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7437
7438 where encoding of <DATA> is terminated by PACKET_FORMAT.
7439
7440 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7441 are omitted.
7442
7443 Return the transferred status, error or OK (an
7444 'enum target_xfer_status' value). Save the number of addressable units
7445 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7446
7447 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7448 exchange between gdb and the stub could look like (?? in place of the
7449 checksum):
7450
7451 -> $m1000,4#??
7452 <- aaaabbbbccccdddd
7453
7454 -> $M1000,3:eeeeffffeeee#??
7455 <- OK
7456
7457 -> $m1000,4#??
7458 <- eeeeffffeeeedddd */
7459
7460 static enum target_xfer_status
7461 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7462 const gdb_byte *myaddr, ULONGEST len_units,
7463 int unit_size, ULONGEST *xfered_len_units,
7464 char packet_format, int use_length)
7465 {
7466 struct remote_state *rs = get_remote_state ();
7467 char *p;
7468 char *plen = NULL;
7469 int plenlen = 0;
7470 int todo_units;
7471 int units_written;
7472 int payload_capacity_bytes;
7473 int payload_length_bytes;
7474
7475 if (packet_format != 'X' && packet_format != 'M')
7476 internal_error (__FILE__, __LINE__,
7477 _("remote_write_bytes_aux: bad packet format"));
7478
7479 if (len_units == 0)
7480 return TARGET_XFER_EOF;
7481
7482 payload_capacity_bytes = get_memory_write_packet_size ();
7483
7484 /* The packet buffer will be large enough for the payload;
7485 get_memory_packet_size ensures this. */
7486 rs->buf[0] = '\0';
7487
7488 /* Compute the size of the actual payload by subtracting out the
7489 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7490
7491 payload_capacity_bytes -= strlen ("$,:#NN");
7492 if (!use_length)
7493 /* The comma won't be used. */
7494 payload_capacity_bytes += 1;
7495 payload_capacity_bytes -= strlen (header);
7496 payload_capacity_bytes -= hexnumlen (memaddr);
7497
7498 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7499
7500 strcat (rs->buf, header);
7501 p = rs->buf + strlen (header);
7502
7503 /* Compute a best guess of the number of bytes actually transfered. */
7504 if (packet_format == 'X')
7505 {
7506 /* Best guess at number of bytes that will fit. */
7507 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7508 if (use_length)
7509 payload_capacity_bytes -= hexnumlen (todo_units);
7510 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7511 }
7512 else
7513 {
7514 /* Number of bytes that will fit. */
7515 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7516 if (use_length)
7517 payload_capacity_bytes -= hexnumlen (todo_units);
7518 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7519 }
7520
7521 if (todo_units <= 0)
7522 internal_error (__FILE__, __LINE__,
7523 _("minimum packet size too small to write data"));
7524
7525 /* If we already need another packet, then try to align the end
7526 of this packet to a useful boundary. */
7527 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7528 todo_units = align_for_efficient_write (todo_units, memaddr);
7529
7530 /* Append "<memaddr>". */
7531 memaddr = remote_address_masked (memaddr);
7532 p += hexnumstr (p, (ULONGEST) memaddr);
7533
7534 if (use_length)
7535 {
7536 /* Append ",". */
7537 *p++ = ',';
7538
7539 /* Append the length and retain its location and size. It may need to be
7540 adjusted once the packet body has been created. */
7541 plen = p;
7542 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7543 p += plenlen;
7544 }
7545
7546 /* Append ":". */
7547 *p++ = ':';
7548 *p = '\0';
7549
7550 /* Append the packet body. */
7551 if (packet_format == 'X')
7552 {
7553 /* Binary mode. Send target system values byte by byte, in
7554 increasing byte addresses. Only escape certain critical
7555 characters. */
7556 payload_length_bytes =
7557 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7558 &units_written, payload_capacity_bytes);
7559
7560 /* If not all TODO units fit, then we'll need another packet. Make
7561 a second try to keep the end of the packet aligned. Don't do
7562 this if the packet is tiny. */
7563 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7564 {
7565 int new_todo_units;
7566
7567 new_todo_units = align_for_efficient_write (units_written, memaddr);
7568
7569 if (new_todo_units != units_written)
7570 payload_length_bytes =
7571 remote_escape_output (myaddr, new_todo_units, unit_size,
7572 (gdb_byte *) p, &units_written,
7573 payload_capacity_bytes);
7574 }
7575
7576 p += payload_length_bytes;
7577 if (use_length && units_written < todo_units)
7578 {
7579 /* Escape chars have filled up the buffer prematurely,
7580 and we have actually sent fewer units than planned.
7581 Fix-up the length field of the packet. Use the same
7582 number of characters as before. */
7583 plen += hexnumnstr (plen, (ULONGEST) units_written,
7584 plenlen);
7585 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7586 }
7587 }
7588 else
7589 {
7590 /* Normal mode: Send target system values byte by byte, in
7591 increasing byte addresses. Each byte is encoded as a two hex
7592 value. */
7593 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7594 units_written = todo_units;
7595 }
7596
7597 putpkt_binary (rs->buf, (int) (p - rs->buf));
7598 getpkt (&rs->buf, &rs->buf_size, 0);
7599
7600 if (rs->buf[0] == 'E')
7601 return TARGET_XFER_E_IO;
7602
7603 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7604 send fewer units than we'd planned. */
7605 *xfered_len_units = (ULONGEST) units_written;
7606 return TARGET_XFER_OK;
7607 }
7608
7609 /* Write memory data directly to the remote machine.
7610 This does not inform the data cache; the data cache uses this.
7611 MEMADDR is the address in the remote memory space.
7612 MYADDR is the address of the buffer in our space.
7613 LEN is the number of bytes.
7614
7615 Return the transferred status, error or OK (an
7616 'enum target_xfer_status' value). Save the number of bytes
7617 transferred in *XFERED_LEN. Only transfer a single packet. */
7618
7619 static enum target_xfer_status
7620 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7621 int unit_size, ULONGEST *xfered_len)
7622 {
7623 char *packet_format = 0;
7624
7625 /* Check whether the target supports binary download. */
7626 check_binary_download (memaddr);
7627
7628 switch (packet_support (PACKET_X))
7629 {
7630 case PACKET_ENABLE:
7631 packet_format = "X";
7632 break;
7633 case PACKET_DISABLE:
7634 packet_format = "M";
7635 break;
7636 case PACKET_SUPPORT_UNKNOWN:
7637 internal_error (__FILE__, __LINE__,
7638 _("remote_write_bytes: bad internal state"));
7639 default:
7640 internal_error (__FILE__, __LINE__, _("bad switch"));
7641 }
7642
7643 return remote_write_bytes_aux (packet_format,
7644 memaddr, myaddr, len, unit_size, xfered_len,
7645 packet_format[0], 1);
7646 }
7647
7648 /* Read memory data directly from the remote machine.
7649 This does not use the data cache; the data cache uses this.
7650 MEMADDR is the address in the remote memory space.
7651 MYADDR is the address of the buffer in our space.
7652 LEN_UNITS is the number of addressable memory units to read..
7653 UNIT_SIZE is the length in bytes of an addressable unit.
7654
7655 Return the transferred status, error or OK (an
7656 'enum target_xfer_status' value). Save the number of bytes
7657 transferred in *XFERED_LEN_UNITS.
7658
7659 See the comment of remote_write_bytes_aux for an example of
7660 memory read/write exchange between gdb and the stub. */
7661
7662 static enum target_xfer_status
7663 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7664 int unit_size, ULONGEST *xfered_len_units)
7665 {
7666 struct remote_state *rs = get_remote_state ();
7667 int buf_size_bytes; /* Max size of packet output buffer. */
7668 char *p;
7669 int todo_units;
7670 int decoded_bytes;
7671
7672 buf_size_bytes = get_memory_read_packet_size ();
7673 /* The packet buffer will be large enough for the payload;
7674 get_memory_packet_size ensures this. */
7675
7676 /* Number of units that will fit. */
7677 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7678
7679 /* Construct "m"<memaddr>","<len>". */
7680 memaddr = remote_address_masked (memaddr);
7681 p = rs->buf;
7682 *p++ = 'm';
7683 p += hexnumstr (p, (ULONGEST) memaddr);
7684 *p++ = ',';
7685 p += hexnumstr (p, (ULONGEST) todo_units);
7686 *p = '\0';
7687 putpkt (rs->buf);
7688 getpkt (&rs->buf, &rs->buf_size, 0);
7689 if (rs->buf[0] == 'E'
7690 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7691 && rs->buf[3] == '\0')
7692 return TARGET_XFER_E_IO;
7693 /* Reply describes memory byte by byte, each byte encoded as two hex
7694 characters. */
7695 p = rs->buf;
7696 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7697 /* Return what we have. Let higher layers handle partial reads. */
7698 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7699 return TARGET_XFER_OK;
7700 }
7701
7702 /* Using the set of read-only target sections of remote, read live
7703 read-only memory.
7704
7705 For interface/parameters/return description see target.h,
7706 to_xfer_partial. */
7707
7708 static enum target_xfer_status
7709 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7710 ULONGEST memaddr, ULONGEST len,
7711 int unit_size, ULONGEST *xfered_len)
7712 {
7713 struct target_section *secp;
7714 struct target_section_table *table;
7715
7716 secp = target_section_by_addr (ops, memaddr);
7717 if (secp != NULL
7718 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7719 secp->the_bfd_section)
7720 & SEC_READONLY))
7721 {
7722 struct target_section *p;
7723 ULONGEST memend = memaddr + len;
7724
7725 table = target_get_section_table (ops);
7726
7727 for (p = table->sections; p < table->sections_end; p++)
7728 {
7729 if (memaddr >= p->addr)
7730 {
7731 if (memend <= p->endaddr)
7732 {
7733 /* Entire transfer is within this section. */
7734 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7735 xfered_len);
7736 }
7737 else if (memaddr >= p->endaddr)
7738 {
7739 /* This section ends before the transfer starts. */
7740 continue;
7741 }
7742 else
7743 {
7744 /* This section overlaps the transfer. Just do half. */
7745 len = p->endaddr - memaddr;
7746 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7747 xfered_len);
7748 }
7749 }
7750 }
7751 }
7752
7753 return TARGET_XFER_EOF;
7754 }
7755
7756 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7757 first if the requested memory is unavailable in traceframe.
7758 Otherwise, fall back to remote_read_bytes_1. */
7759
7760 static enum target_xfer_status
7761 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7762 gdb_byte *myaddr, ULONGEST len, int unit_size,
7763 ULONGEST *xfered_len)
7764 {
7765 if (len == 0)
7766 return TARGET_XFER_EOF;
7767
7768 if (get_traceframe_number () != -1)
7769 {
7770 VEC(mem_range_s) *available;
7771
7772 /* If we fail to get the set of available memory, then the
7773 target does not support querying traceframe info, and so we
7774 attempt reading from the traceframe anyway (assuming the
7775 target implements the old QTro packet then). */
7776 if (traceframe_available_memory (&available, memaddr, len))
7777 {
7778 struct cleanup *old_chain;
7779
7780 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7781
7782 if (VEC_empty (mem_range_s, available)
7783 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7784 {
7785 enum target_xfer_status res;
7786
7787 /* Don't read into the traceframe's available
7788 memory. */
7789 if (!VEC_empty (mem_range_s, available))
7790 {
7791 LONGEST oldlen = len;
7792
7793 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7794 gdb_assert (len <= oldlen);
7795 }
7796
7797 do_cleanups (old_chain);
7798
7799 /* This goes through the topmost target again. */
7800 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7801 len, unit_size, xfered_len);
7802 if (res == TARGET_XFER_OK)
7803 return TARGET_XFER_OK;
7804 else
7805 {
7806 /* No use trying further, we know some memory starting
7807 at MEMADDR isn't available. */
7808 *xfered_len = len;
7809 return TARGET_XFER_UNAVAILABLE;
7810 }
7811 }
7812
7813 /* Don't try to read more than how much is available, in
7814 case the target implements the deprecated QTro packet to
7815 cater for older GDBs (the target's knowledge of read-only
7816 sections may be outdated by now). */
7817 len = VEC_index (mem_range_s, available, 0)->length;
7818
7819 do_cleanups (old_chain);
7820 }
7821 }
7822
7823 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7824 }
7825
7826 \f
7827
7828 /* Sends a packet with content determined by the printf format string
7829 FORMAT and the remaining arguments, then gets the reply. Returns
7830 whether the packet was a success, a failure, or unknown. */
7831
7832 static enum packet_result remote_send_printf (const char *format, ...)
7833 ATTRIBUTE_PRINTF (1, 2);
7834
7835 static enum packet_result
7836 remote_send_printf (const char *format, ...)
7837 {
7838 struct remote_state *rs = get_remote_state ();
7839 int max_size = get_remote_packet_size ();
7840 va_list ap;
7841
7842 va_start (ap, format);
7843
7844 rs->buf[0] = '\0';
7845 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7846 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7847
7848 if (putpkt (rs->buf) < 0)
7849 error (_("Communication problem with target."));
7850
7851 rs->buf[0] = '\0';
7852 getpkt (&rs->buf, &rs->buf_size, 0);
7853
7854 return packet_check_result (rs->buf);
7855 }
7856
7857 static void
7858 restore_remote_timeout (void *p)
7859 {
7860 int value = *(int *)p;
7861
7862 remote_timeout = value;
7863 }
7864
7865 /* Flash writing can take quite some time. We'll set
7866 effectively infinite timeout for flash operations.
7867 In future, we'll need to decide on a better approach. */
7868 static const int remote_flash_timeout = 1000;
7869
7870 static void
7871 remote_flash_erase (struct target_ops *ops,
7872 ULONGEST address, LONGEST length)
7873 {
7874 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7875 int saved_remote_timeout = remote_timeout;
7876 enum packet_result ret;
7877 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7878 &saved_remote_timeout);
7879
7880 remote_timeout = remote_flash_timeout;
7881
7882 ret = remote_send_printf ("vFlashErase:%s,%s",
7883 phex (address, addr_size),
7884 phex (length, 4));
7885 switch (ret)
7886 {
7887 case PACKET_UNKNOWN:
7888 error (_("Remote target does not support flash erase"));
7889 case PACKET_ERROR:
7890 error (_("Error erasing flash with vFlashErase packet"));
7891 default:
7892 break;
7893 }
7894
7895 do_cleanups (back_to);
7896 }
7897
7898 static enum target_xfer_status
7899 remote_flash_write (struct target_ops *ops, ULONGEST address,
7900 ULONGEST length, ULONGEST *xfered_len,
7901 const gdb_byte *data)
7902 {
7903 int saved_remote_timeout = remote_timeout;
7904 enum target_xfer_status ret;
7905 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7906 &saved_remote_timeout);
7907
7908 remote_timeout = remote_flash_timeout;
7909 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7910 xfered_len,'X', 0);
7911 do_cleanups (back_to);
7912
7913 return ret;
7914 }
7915
7916 static void
7917 remote_flash_done (struct target_ops *ops)
7918 {
7919 int saved_remote_timeout = remote_timeout;
7920 int ret;
7921 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7922 &saved_remote_timeout);
7923
7924 remote_timeout = remote_flash_timeout;
7925 ret = remote_send_printf ("vFlashDone");
7926 do_cleanups (back_to);
7927
7928 switch (ret)
7929 {
7930 case PACKET_UNKNOWN:
7931 error (_("Remote target does not support vFlashDone"));
7932 case PACKET_ERROR:
7933 error (_("Error finishing flash operation"));
7934 default:
7935 break;
7936 }
7937 }
7938
7939 static void
7940 remote_files_info (struct target_ops *ignore)
7941 {
7942 puts_filtered ("Debugging a target over a serial line.\n");
7943 }
7944 \f
7945 /* Stuff for dealing with the packets which are part of this protocol.
7946 See comment at top of file for details. */
7947
7948 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7949 error to higher layers. Called when a serial error is detected.
7950 The exception message is STRING, followed by a colon and a blank,
7951 the system error message for errno at function entry and final dot
7952 for output compatibility with throw_perror_with_name. */
7953
7954 static void
7955 unpush_and_perror (const char *string)
7956 {
7957 int saved_errno = errno;
7958
7959 remote_unpush_target ();
7960 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7961 safe_strerror (saved_errno));
7962 }
7963
7964 /* Read a single character from the remote end. */
7965
7966 static int
7967 readchar (int timeout)
7968 {
7969 int ch;
7970 struct remote_state *rs = get_remote_state ();
7971
7972 ch = serial_readchar (rs->remote_desc, timeout);
7973
7974 if (ch >= 0)
7975 return ch;
7976
7977 switch ((enum serial_rc) ch)
7978 {
7979 case SERIAL_EOF:
7980 remote_unpush_target ();
7981 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7982 /* no return */
7983 case SERIAL_ERROR:
7984 unpush_and_perror (_("Remote communication error. "
7985 "Target disconnected."));
7986 /* no return */
7987 case SERIAL_TIMEOUT:
7988 break;
7989 }
7990 return ch;
7991 }
7992
7993 /* Wrapper for serial_write that closes the target and throws if
7994 writing fails. */
7995
7996 static void
7997 remote_serial_write (const char *str, int len)
7998 {
7999 struct remote_state *rs = get_remote_state ();
8000
8001 if (serial_write (rs->remote_desc, str, len))
8002 {
8003 unpush_and_perror (_("Remote communication error. "
8004 "Target disconnected."));
8005 }
8006 }
8007
8008 /* Send the command in *BUF to the remote machine, and read the reply
8009 into *BUF. Report an error if we get an error reply. Resize
8010 *BUF using xrealloc if necessary to hold the result, and update
8011 *SIZEOF_BUF. */
8012
8013 static void
8014 remote_send (char **buf,
8015 long *sizeof_buf)
8016 {
8017 putpkt (*buf);
8018 getpkt (buf, sizeof_buf, 0);
8019
8020 if ((*buf)[0] == 'E')
8021 error (_("Remote failure reply: %s"), *buf);
8022 }
8023
8024 /* Return a pointer to an xmalloc'ed string representing an escaped
8025 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8026 etc. The caller is responsible for releasing the returned
8027 memory. */
8028
8029 static char *
8030 escape_buffer (const char *buf, int n)
8031 {
8032 struct cleanup *old_chain;
8033 struct ui_file *stb;
8034 char *str;
8035
8036 stb = mem_fileopen ();
8037 old_chain = make_cleanup_ui_file_delete (stb);
8038
8039 fputstrn_unfiltered (buf, n, '\\', stb);
8040 str = ui_file_xstrdup (stb, NULL);
8041 do_cleanups (old_chain);
8042 return str;
8043 }
8044
8045 /* Display a null-terminated packet on stdout, for debugging, using C
8046 string notation. */
8047
8048 static void
8049 print_packet (const char *buf)
8050 {
8051 puts_filtered ("\"");
8052 fputstr_filtered (buf, '"', gdb_stdout);
8053 puts_filtered ("\"");
8054 }
8055
8056 int
8057 putpkt (const char *buf)
8058 {
8059 return putpkt_binary (buf, strlen (buf));
8060 }
8061
8062 /* Send a packet to the remote machine, with error checking. The data
8063 of the packet is in BUF. The string in BUF can be at most
8064 get_remote_packet_size () - 5 to account for the $, # and checksum,
8065 and for a possible /0 if we are debugging (remote_debug) and want
8066 to print the sent packet as a string. */
8067
8068 static int
8069 putpkt_binary (const char *buf, int cnt)
8070 {
8071 struct remote_state *rs = get_remote_state ();
8072 int i;
8073 unsigned char csum = 0;
8074 char *buf2 = (char *) xmalloc (cnt + 6);
8075 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8076
8077 int ch;
8078 int tcount = 0;
8079 char *p;
8080 char *message;
8081
8082 /* Catch cases like trying to read memory or listing threads while
8083 we're waiting for a stop reply. The remote server wouldn't be
8084 ready to handle this request, so we'd hang and timeout. We don't
8085 have to worry about this in synchronous mode, because in that
8086 case it's not possible to issue a command while the target is
8087 running. This is not a problem in non-stop mode, because in that
8088 case, the stub is always ready to process serial input. */
8089 if (!target_is_non_stop_p ()
8090 && target_is_async_p ()
8091 && rs->waiting_for_stop_reply)
8092 {
8093 error (_("Cannot execute this command while the target is running.\n"
8094 "Use the \"interrupt\" command to stop the target\n"
8095 "and then try again."));
8096 }
8097
8098 /* We're sending out a new packet. Make sure we don't look at a
8099 stale cached response. */
8100 rs->cached_wait_status = 0;
8101
8102 /* Copy the packet into buffer BUF2, encapsulating it
8103 and giving it a checksum. */
8104
8105 p = buf2;
8106 *p++ = '$';
8107
8108 for (i = 0; i < cnt; i++)
8109 {
8110 csum += buf[i];
8111 *p++ = buf[i];
8112 }
8113 *p++ = '#';
8114 *p++ = tohex ((csum >> 4) & 0xf);
8115 *p++ = tohex (csum & 0xf);
8116
8117 /* Send it over and over until we get a positive ack. */
8118
8119 while (1)
8120 {
8121 int started_error_output = 0;
8122
8123 if (remote_debug)
8124 {
8125 struct cleanup *old_chain;
8126 char *str;
8127
8128 *p = '\0';
8129 str = escape_buffer (buf2, p - buf2);
8130 old_chain = make_cleanup (xfree, str);
8131 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8132 gdb_flush (gdb_stdlog);
8133 do_cleanups (old_chain);
8134 }
8135 remote_serial_write (buf2, p - buf2);
8136
8137 /* If this is a no acks version of the remote protocol, send the
8138 packet and move on. */
8139 if (rs->noack_mode)
8140 break;
8141
8142 /* Read until either a timeout occurs (-2) or '+' is read.
8143 Handle any notification that arrives in the mean time. */
8144 while (1)
8145 {
8146 ch = readchar (remote_timeout);
8147
8148 if (remote_debug)
8149 {
8150 switch (ch)
8151 {
8152 case '+':
8153 case '-':
8154 case SERIAL_TIMEOUT:
8155 case '$':
8156 case '%':
8157 if (started_error_output)
8158 {
8159 putchar_unfiltered ('\n');
8160 started_error_output = 0;
8161 }
8162 }
8163 }
8164
8165 switch (ch)
8166 {
8167 case '+':
8168 if (remote_debug)
8169 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8170 do_cleanups (old_chain);
8171 return 1;
8172 case '-':
8173 if (remote_debug)
8174 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8175 /* FALLTHROUGH */
8176 case SERIAL_TIMEOUT:
8177 tcount++;
8178 if (tcount > 3)
8179 {
8180 do_cleanups (old_chain);
8181 return 0;
8182 }
8183 break; /* Retransmit buffer. */
8184 case '$':
8185 {
8186 if (remote_debug)
8187 fprintf_unfiltered (gdb_stdlog,
8188 "Packet instead of Ack, ignoring it\n");
8189 /* It's probably an old response sent because an ACK
8190 was lost. Gobble up the packet and ack it so it
8191 doesn't get retransmitted when we resend this
8192 packet. */
8193 skip_frame ();
8194 remote_serial_write ("+", 1);
8195 continue; /* Now, go look for +. */
8196 }
8197
8198 case '%':
8199 {
8200 int val;
8201
8202 /* If we got a notification, handle it, and go back to looking
8203 for an ack. */
8204 /* We've found the start of a notification. Now
8205 collect the data. */
8206 val = read_frame (&rs->buf, &rs->buf_size);
8207 if (val >= 0)
8208 {
8209 if (remote_debug)
8210 {
8211 struct cleanup *old_chain;
8212 char *str;
8213
8214 str = escape_buffer (rs->buf, val);
8215 old_chain = make_cleanup (xfree, str);
8216 fprintf_unfiltered (gdb_stdlog,
8217 " Notification received: %s\n",
8218 str);
8219 do_cleanups (old_chain);
8220 }
8221 handle_notification (rs->notif_state, rs->buf);
8222 /* We're in sync now, rewait for the ack. */
8223 tcount = 0;
8224 }
8225 else
8226 {
8227 if (remote_debug)
8228 {
8229 if (!started_error_output)
8230 {
8231 started_error_output = 1;
8232 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8233 }
8234 fputc_unfiltered (ch & 0177, gdb_stdlog);
8235 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8236 }
8237 }
8238 continue;
8239 }
8240 /* fall-through */
8241 default:
8242 if (remote_debug)
8243 {
8244 if (!started_error_output)
8245 {
8246 started_error_output = 1;
8247 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8248 }
8249 fputc_unfiltered (ch & 0177, gdb_stdlog);
8250 }
8251 continue;
8252 }
8253 break; /* Here to retransmit. */
8254 }
8255
8256 #if 0
8257 /* This is wrong. If doing a long backtrace, the user should be
8258 able to get out next time we call QUIT, without anything as
8259 violent as interrupt_query. If we want to provide a way out of
8260 here without getting to the next QUIT, it should be based on
8261 hitting ^C twice as in remote_wait. */
8262 if (quit_flag)
8263 {
8264 quit_flag = 0;
8265 interrupt_query ();
8266 }
8267 #endif
8268 }
8269
8270 do_cleanups (old_chain);
8271 return 0;
8272 }
8273
8274 /* Come here after finding the start of a frame when we expected an
8275 ack. Do our best to discard the rest of this packet. */
8276
8277 static void
8278 skip_frame (void)
8279 {
8280 int c;
8281
8282 while (1)
8283 {
8284 c = readchar (remote_timeout);
8285 switch (c)
8286 {
8287 case SERIAL_TIMEOUT:
8288 /* Nothing we can do. */
8289 return;
8290 case '#':
8291 /* Discard the two bytes of checksum and stop. */
8292 c = readchar (remote_timeout);
8293 if (c >= 0)
8294 c = readchar (remote_timeout);
8295
8296 return;
8297 case '*': /* Run length encoding. */
8298 /* Discard the repeat count. */
8299 c = readchar (remote_timeout);
8300 if (c < 0)
8301 return;
8302 break;
8303 default:
8304 /* A regular character. */
8305 break;
8306 }
8307 }
8308 }
8309
8310 /* Come here after finding the start of the frame. Collect the rest
8311 into *BUF, verifying the checksum, length, and handling run-length
8312 compression. NUL terminate the buffer. If there is not enough room,
8313 expand *BUF using xrealloc.
8314
8315 Returns -1 on error, number of characters in buffer (ignoring the
8316 trailing NULL) on success. (could be extended to return one of the
8317 SERIAL status indications). */
8318
8319 static long
8320 read_frame (char **buf_p,
8321 long *sizeof_buf)
8322 {
8323 unsigned char csum;
8324 long bc;
8325 int c;
8326 char *buf = *buf_p;
8327 struct remote_state *rs = get_remote_state ();
8328
8329 csum = 0;
8330 bc = 0;
8331
8332 while (1)
8333 {
8334 c = readchar (remote_timeout);
8335 switch (c)
8336 {
8337 case SERIAL_TIMEOUT:
8338 if (remote_debug)
8339 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8340 return -1;
8341 case '$':
8342 if (remote_debug)
8343 fputs_filtered ("Saw new packet start in middle of old one\n",
8344 gdb_stdlog);
8345 return -1; /* Start a new packet, count retries. */
8346 case '#':
8347 {
8348 unsigned char pktcsum;
8349 int check_0 = 0;
8350 int check_1 = 0;
8351
8352 buf[bc] = '\0';
8353
8354 check_0 = readchar (remote_timeout);
8355 if (check_0 >= 0)
8356 check_1 = readchar (remote_timeout);
8357
8358 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8359 {
8360 if (remote_debug)
8361 fputs_filtered ("Timeout in checksum, retrying\n",
8362 gdb_stdlog);
8363 return -1;
8364 }
8365 else if (check_0 < 0 || check_1 < 0)
8366 {
8367 if (remote_debug)
8368 fputs_filtered ("Communication error in checksum\n",
8369 gdb_stdlog);
8370 return -1;
8371 }
8372
8373 /* Don't recompute the checksum; with no ack packets we
8374 don't have any way to indicate a packet retransmission
8375 is necessary. */
8376 if (rs->noack_mode)
8377 return bc;
8378
8379 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8380 if (csum == pktcsum)
8381 return bc;
8382
8383 if (remote_debug)
8384 {
8385 struct cleanup *old_chain;
8386 char *str;
8387
8388 str = escape_buffer (buf, bc);
8389 old_chain = make_cleanup (xfree, str);
8390 fprintf_unfiltered (gdb_stdlog,
8391 "Bad checksum, sentsum=0x%x, "
8392 "csum=0x%x, buf=%s\n",
8393 pktcsum, csum, str);
8394 do_cleanups (old_chain);
8395 }
8396 /* Number of characters in buffer ignoring trailing
8397 NULL. */
8398 return -1;
8399 }
8400 case '*': /* Run length encoding. */
8401 {
8402 int repeat;
8403
8404 csum += c;
8405 c = readchar (remote_timeout);
8406 csum += c;
8407 repeat = c - ' ' + 3; /* Compute repeat count. */
8408
8409 /* The character before ``*'' is repeated. */
8410
8411 if (repeat > 0 && repeat <= 255 && bc > 0)
8412 {
8413 if (bc + repeat - 1 >= *sizeof_buf - 1)
8414 {
8415 /* Make some more room in the buffer. */
8416 *sizeof_buf += repeat;
8417 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8418 buf = *buf_p;
8419 }
8420
8421 memset (&buf[bc], buf[bc - 1], repeat);
8422 bc += repeat;
8423 continue;
8424 }
8425
8426 buf[bc] = '\0';
8427 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8428 return -1;
8429 }
8430 default:
8431 if (bc >= *sizeof_buf - 1)
8432 {
8433 /* Make some more room in the buffer. */
8434 *sizeof_buf *= 2;
8435 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8436 buf = *buf_p;
8437 }
8438
8439 buf[bc++] = c;
8440 csum += c;
8441 continue;
8442 }
8443 }
8444 }
8445
8446 /* Read a packet from the remote machine, with error checking, and
8447 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8448 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8449 rather than timing out; this is used (in synchronous mode) to wait
8450 for a target that is is executing user code to stop. */
8451 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8452 don't have to change all the calls to getpkt to deal with the
8453 return value, because at the moment I don't know what the right
8454 thing to do it for those. */
8455 void
8456 getpkt (char **buf,
8457 long *sizeof_buf,
8458 int forever)
8459 {
8460 int timed_out;
8461
8462 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8463 }
8464
8465
8466 /* Read a packet from the remote machine, with error checking, and
8467 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8468 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8469 rather than timing out; this is used (in synchronous mode) to wait
8470 for a target that is is executing user code to stop. If FOREVER ==
8471 0, this function is allowed to time out gracefully and return an
8472 indication of this to the caller. Otherwise return the number of
8473 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8474 enough reason to return to the caller. *IS_NOTIF is an output
8475 boolean that indicates whether *BUF holds a notification or not
8476 (a regular packet). */
8477
8478 static int
8479 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8480 int expecting_notif, int *is_notif)
8481 {
8482 struct remote_state *rs = get_remote_state ();
8483 int c;
8484 int tries;
8485 int timeout;
8486 int val = -1;
8487
8488 /* We're reading a new response. Make sure we don't look at a
8489 previously cached response. */
8490 rs->cached_wait_status = 0;
8491
8492 strcpy (*buf, "timeout");
8493
8494 if (forever)
8495 timeout = watchdog > 0 ? watchdog : -1;
8496 else if (expecting_notif)
8497 timeout = 0; /* There should already be a char in the buffer. If
8498 not, bail out. */
8499 else
8500 timeout = remote_timeout;
8501
8502 #define MAX_TRIES 3
8503
8504 /* Process any number of notifications, and then return when
8505 we get a packet. */
8506 for (;;)
8507 {
8508 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8509 times. */
8510 for (tries = 1; tries <= MAX_TRIES; tries++)
8511 {
8512 /* This can loop forever if the remote side sends us
8513 characters continuously, but if it pauses, we'll get
8514 SERIAL_TIMEOUT from readchar because of timeout. Then
8515 we'll count that as a retry.
8516
8517 Note that even when forever is set, we will only wait
8518 forever prior to the start of a packet. After that, we
8519 expect characters to arrive at a brisk pace. They should
8520 show up within remote_timeout intervals. */
8521 do
8522 c = readchar (timeout);
8523 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8524
8525 if (c == SERIAL_TIMEOUT)
8526 {
8527 if (expecting_notif)
8528 return -1; /* Don't complain, it's normal to not get
8529 anything in this case. */
8530
8531 if (forever) /* Watchdog went off? Kill the target. */
8532 {
8533 QUIT;
8534 remote_unpush_target ();
8535 throw_error (TARGET_CLOSE_ERROR,
8536 _("Watchdog timeout has expired. "
8537 "Target detached."));
8538 }
8539 if (remote_debug)
8540 fputs_filtered ("Timed out.\n", gdb_stdlog);
8541 }
8542 else
8543 {
8544 /* We've found the start of a packet or notification.
8545 Now collect the data. */
8546 val = read_frame (buf, sizeof_buf);
8547 if (val >= 0)
8548 break;
8549 }
8550
8551 remote_serial_write ("-", 1);
8552 }
8553
8554 if (tries > MAX_TRIES)
8555 {
8556 /* We have tried hard enough, and just can't receive the
8557 packet/notification. Give up. */
8558 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8559
8560 /* Skip the ack char if we're in no-ack mode. */
8561 if (!rs->noack_mode)
8562 remote_serial_write ("+", 1);
8563 return -1;
8564 }
8565
8566 /* If we got an ordinary packet, return that to our caller. */
8567 if (c == '$')
8568 {
8569 if (remote_debug)
8570 {
8571 struct cleanup *old_chain;
8572 char *str;
8573
8574 str = escape_buffer (*buf, val);
8575 old_chain = make_cleanup (xfree, str);
8576 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8577 do_cleanups (old_chain);
8578 }
8579
8580 /* Skip the ack char if we're in no-ack mode. */
8581 if (!rs->noack_mode)
8582 remote_serial_write ("+", 1);
8583 if (is_notif != NULL)
8584 *is_notif = 0;
8585 return val;
8586 }
8587
8588 /* If we got a notification, handle it, and go back to looking
8589 for a packet. */
8590 else
8591 {
8592 gdb_assert (c == '%');
8593
8594 if (remote_debug)
8595 {
8596 struct cleanup *old_chain;
8597 char *str;
8598
8599 str = escape_buffer (*buf, val);
8600 old_chain = make_cleanup (xfree, str);
8601 fprintf_unfiltered (gdb_stdlog,
8602 " Notification received: %s\n",
8603 str);
8604 do_cleanups (old_chain);
8605 }
8606 if (is_notif != NULL)
8607 *is_notif = 1;
8608
8609 handle_notification (rs->notif_state, *buf);
8610
8611 /* Notifications require no acknowledgement. */
8612
8613 if (expecting_notif)
8614 return val;
8615 }
8616 }
8617 }
8618
8619 static int
8620 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8621 {
8622 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8623 }
8624
8625 static int
8626 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8627 int *is_notif)
8628 {
8629 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8630 is_notif);
8631 }
8632
8633 /* Check whether EVENT is a fork event for the process specified
8634 by the pid passed in DATA, and if it is, kill the fork child. */
8635
8636 static int
8637 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8638 QUEUE_ITER (stop_reply_p) *iter,
8639 stop_reply_p event,
8640 void *data)
8641 {
8642 struct queue_iter_param *param = (struct queue_iter_param *) data;
8643 int parent_pid = *(int *) param->input;
8644
8645 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8646 {
8647 struct remote_state *rs = get_remote_state ();
8648 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8649 int res;
8650
8651 res = remote_vkill (child_pid, rs);
8652 if (res != 0)
8653 error (_("Can't kill fork child process %d"), child_pid);
8654 }
8655
8656 return 1;
8657 }
8658
8659 /* Kill any new fork children of process PID that haven't been
8660 processed by follow_fork. */
8661
8662 static void
8663 kill_new_fork_children (int pid, struct remote_state *rs)
8664 {
8665 struct thread_info *thread;
8666 struct notif_client *notif = &notif_client_stop;
8667 struct queue_iter_param param;
8668
8669 /* Kill the fork child threads of any threads in process PID
8670 that are stopped at a fork event. */
8671 ALL_NON_EXITED_THREADS (thread)
8672 {
8673 struct target_waitstatus *ws = &thread->pending_follow;
8674
8675 if (is_pending_fork_parent (ws, pid, thread->ptid))
8676 {
8677 struct remote_state *rs = get_remote_state ();
8678 int child_pid = ptid_get_pid (ws->value.related_pid);
8679 int res;
8680
8681 res = remote_vkill (child_pid, rs);
8682 if (res != 0)
8683 error (_("Can't kill fork child process %d"), child_pid);
8684 }
8685 }
8686
8687 /* Check for any pending fork events (not reported or processed yet)
8688 in process PID and kill those fork child threads as well. */
8689 remote_notif_get_pending_events (notif);
8690 param.input = &pid;
8691 param.output = NULL;
8692 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8693 kill_child_of_pending_fork, &param);
8694 }
8695
8696 \f
8697 static void
8698 remote_kill (struct target_ops *ops)
8699 {
8700
8701 /* Catch errors so the user can quit from gdb even when we
8702 aren't on speaking terms with the remote system. */
8703 TRY
8704 {
8705 putpkt ("k");
8706 }
8707 CATCH (ex, RETURN_MASK_ERROR)
8708 {
8709 if (ex.error == TARGET_CLOSE_ERROR)
8710 {
8711 /* If we got an (EOF) error that caused the target
8712 to go away, then we're done, that's what we wanted.
8713 "k" is susceptible to cause a premature EOF, given
8714 that the remote server isn't actually required to
8715 reply to "k", and it can happen that it doesn't
8716 even get to reply ACK to the "k". */
8717 return;
8718 }
8719
8720 /* Otherwise, something went wrong. We didn't actually kill
8721 the target. Just propagate the exception, and let the
8722 user or higher layers decide what to do. */
8723 throw_exception (ex);
8724 }
8725 END_CATCH
8726
8727 /* We've killed the remote end, we get to mourn it. Since this is
8728 target remote, single-process, mourning the inferior also
8729 unpushes remote_ops. */
8730 target_mourn_inferior ();
8731 }
8732
8733 static int
8734 remote_vkill (int pid, struct remote_state *rs)
8735 {
8736 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8737 return -1;
8738
8739 /* Tell the remote target to detach. */
8740 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8741 putpkt (rs->buf);
8742 getpkt (&rs->buf, &rs->buf_size, 0);
8743
8744 switch (packet_ok (rs->buf,
8745 &remote_protocol_packets[PACKET_vKill]))
8746 {
8747 case PACKET_OK:
8748 return 0;
8749 case PACKET_ERROR:
8750 return 1;
8751 case PACKET_UNKNOWN:
8752 return -1;
8753 default:
8754 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8755 }
8756 }
8757
8758 static void
8759 extended_remote_kill (struct target_ops *ops)
8760 {
8761 int res;
8762 int pid = ptid_get_pid (inferior_ptid);
8763 struct remote_state *rs = get_remote_state ();
8764
8765 /* If we're stopped while forking and we haven't followed yet, kill the
8766 child task. We need to do this before killing the parent task
8767 because if this is a vfork then the parent will be sleeping. */
8768 kill_new_fork_children (pid, rs);
8769
8770 res = remote_vkill (pid, rs);
8771 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8772 {
8773 /* Don't try 'k' on a multi-process aware stub -- it has no way
8774 to specify the pid. */
8775
8776 putpkt ("k");
8777 #if 0
8778 getpkt (&rs->buf, &rs->buf_size, 0);
8779 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8780 res = 1;
8781 #else
8782 /* Don't wait for it to die. I'm not really sure it matters whether
8783 we do or not. For the existing stubs, kill is a noop. */
8784 res = 0;
8785 #endif
8786 }
8787
8788 if (res != 0)
8789 error (_("Can't kill process"));
8790
8791 target_mourn_inferior ();
8792 }
8793
8794 static void
8795 remote_mourn (struct target_ops *target)
8796 {
8797 unpush_target (target);
8798
8799 /* remote_close takes care of doing most of the clean up. */
8800 generic_mourn_inferior ();
8801 }
8802
8803 static void
8804 extended_remote_mourn (struct target_ops *target)
8805 {
8806 struct remote_state *rs = get_remote_state ();
8807
8808 /* In case we got here due to an error, but we're going to stay
8809 connected. */
8810 rs->waiting_for_stop_reply = 0;
8811
8812 /* If the current general thread belonged to the process we just
8813 detached from or has exited, the remote side current general
8814 thread becomes undefined. Considering a case like this:
8815
8816 - We just got here due to a detach.
8817 - The process that we're detaching from happens to immediately
8818 report a global breakpoint being hit in non-stop mode, in the
8819 same thread we had selected before.
8820 - GDB attaches to this process again.
8821 - This event happens to be the next event we handle.
8822
8823 GDB would consider that the current general thread didn't need to
8824 be set on the stub side (with Hg), since for all it knew,
8825 GENERAL_THREAD hadn't changed.
8826
8827 Notice that although in all-stop mode, the remote server always
8828 sets the current thread to the thread reporting the stop event,
8829 that doesn't happen in non-stop mode; in non-stop, the stub *must
8830 not* change the current thread when reporting a breakpoint hit,
8831 due to the decoupling of event reporting and event handling.
8832
8833 To keep things simple, we always invalidate our notion of the
8834 current thread. */
8835 record_currthread (rs, minus_one_ptid);
8836
8837 /* Unlike "target remote", we do not want to unpush the target; then
8838 the next time the user says "run", we won't be connected. */
8839
8840 /* Call common code to mark the inferior as not running. */
8841 generic_mourn_inferior ();
8842
8843 if (!have_inferiors ())
8844 {
8845 if (!remote_multi_process_p (rs))
8846 {
8847 /* Check whether the target is running now - some remote stubs
8848 automatically restart after kill. */
8849 putpkt ("?");
8850 getpkt (&rs->buf, &rs->buf_size, 0);
8851
8852 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8853 {
8854 /* Assume that the target has been restarted. Set
8855 inferior_ptid so that bits of core GDB realizes
8856 there's something here, e.g., so that the user can
8857 say "kill" again. */
8858 inferior_ptid = magic_null_ptid;
8859 }
8860 }
8861 }
8862 }
8863
8864 static int
8865 extended_remote_supports_disable_randomization (struct target_ops *self)
8866 {
8867 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8868 }
8869
8870 static void
8871 extended_remote_disable_randomization (int val)
8872 {
8873 struct remote_state *rs = get_remote_state ();
8874 char *reply;
8875
8876 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8877 val);
8878 putpkt (rs->buf);
8879 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8880 if (*reply == '\0')
8881 error (_("Target does not support QDisableRandomization."));
8882 if (strcmp (reply, "OK") != 0)
8883 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8884 }
8885
8886 static int
8887 extended_remote_run (char *args)
8888 {
8889 struct remote_state *rs = get_remote_state ();
8890 int len;
8891 const char *remote_exec_file = get_remote_exec_file ();
8892
8893 /* If the user has disabled vRun support, or we have detected that
8894 support is not available, do not try it. */
8895 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8896 return -1;
8897
8898 strcpy (rs->buf, "vRun;");
8899 len = strlen (rs->buf);
8900
8901 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8902 error (_("Remote file name too long for run packet"));
8903 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8904 strlen (remote_exec_file));
8905
8906 gdb_assert (args != NULL);
8907 if (*args)
8908 {
8909 struct cleanup *back_to;
8910 int i;
8911 char **argv;
8912
8913 argv = gdb_buildargv (args);
8914 back_to = make_cleanup_freeargv (argv);
8915 for (i = 0; argv[i] != NULL; i++)
8916 {
8917 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8918 error (_("Argument list too long for run packet"));
8919 rs->buf[len++] = ';';
8920 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8921 strlen (argv[i]));
8922 }
8923 do_cleanups (back_to);
8924 }
8925
8926 rs->buf[len++] = '\0';
8927
8928 putpkt (rs->buf);
8929 getpkt (&rs->buf, &rs->buf_size, 0);
8930
8931 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8932 {
8933 case PACKET_OK:
8934 /* We have a wait response. All is well. */
8935 return 0;
8936 case PACKET_UNKNOWN:
8937 return -1;
8938 case PACKET_ERROR:
8939 if (remote_exec_file[0] == '\0')
8940 error (_("Running the default executable on the remote target failed; "
8941 "try \"set remote exec-file\"?"));
8942 else
8943 error (_("Running \"%s\" on the remote target failed"),
8944 remote_exec_file);
8945 default:
8946 gdb_assert_not_reached (_("bad switch"));
8947 }
8948 }
8949
8950 /* In the extended protocol we want to be able to do things like
8951 "run" and have them basically work as expected. So we need
8952 a special create_inferior function. We support changing the
8953 executable file and the command line arguments, but not the
8954 environment. */
8955
8956 static void
8957 extended_remote_create_inferior (struct target_ops *ops,
8958 char *exec_file, char *args,
8959 char **env, int from_tty)
8960 {
8961 int run_worked;
8962 char *stop_reply;
8963 struct remote_state *rs = get_remote_state ();
8964 const char *remote_exec_file = get_remote_exec_file ();
8965
8966 /* If running asynchronously, register the target file descriptor
8967 with the event loop. */
8968 if (target_can_async_p ())
8969 target_async (1);
8970
8971 /* Disable address space randomization if requested (and supported). */
8972 if (extended_remote_supports_disable_randomization (ops))
8973 extended_remote_disable_randomization (disable_randomization);
8974
8975 /* Now restart the remote server. */
8976 run_worked = extended_remote_run (args) != -1;
8977 if (!run_worked)
8978 {
8979 /* vRun was not supported. Fail if we need it to do what the
8980 user requested. */
8981 if (remote_exec_file[0])
8982 error (_("Remote target does not support \"set remote exec-file\""));
8983 if (args[0])
8984 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8985
8986 /* Fall back to "R". */
8987 extended_remote_restart ();
8988 }
8989
8990 if (!have_inferiors ())
8991 {
8992 /* Clean up from the last time we ran, before we mark the target
8993 running again. This will mark breakpoints uninserted, and
8994 get_offsets may insert breakpoints. */
8995 init_thread_list ();
8996 init_wait_for_inferior ();
8997 }
8998
8999 /* vRun's success return is a stop reply. */
9000 stop_reply = run_worked ? rs->buf : NULL;
9001 add_current_inferior_and_thread (stop_reply);
9002
9003 /* Get updated offsets, if the stub uses qOffsets. */
9004 get_offsets ();
9005 }
9006 \f
9007
9008 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9009 the list of conditions (in agent expression bytecode format), if any, the
9010 target needs to evaluate. The output is placed into the packet buffer
9011 started from BUF and ended at BUF_END. */
9012
9013 static int
9014 remote_add_target_side_condition (struct gdbarch *gdbarch,
9015 struct bp_target_info *bp_tgt, char *buf,
9016 char *buf_end)
9017 {
9018 struct agent_expr *aexpr = NULL;
9019 int i, ix;
9020 char *pkt;
9021 char *buf_start = buf;
9022
9023 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9024 return 0;
9025
9026 buf += strlen (buf);
9027 xsnprintf (buf, buf_end - buf, "%s", ";");
9028 buf++;
9029
9030 /* Send conditions to the target and free the vector. */
9031 for (ix = 0;
9032 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9033 ix++)
9034 {
9035 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9036 buf += strlen (buf);
9037 for (i = 0; i < aexpr->len; ++i)
9038 buf = pack_hex_byte (buf, aexpr->buf[i]);
9039 *buf = '\0';
9040 }
9041 return 0;
9042 }
9043
9044 static void
9045 remote_add_target_side_commands (struct gdbarch *gdbarch,
9046 struct bp_target_info *bp_tgt, char *buf)
9047 {
9048 struct agent_expr *aexpr = NULL;
9049 int i, ix;
9050
9051 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9052 return;
9053
9054 buf += strlen (buf);
9055
9056 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9057 buf += strlen (buf);
9058
9059 /* Concatenate all the agent expressions that are commands into the
9060 cmds parameter. */
9061 for (ix = 0;
9062 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9063 ix++)
9064 {
9065 sprintf (buf, "X%x,", aexpr->len);
9066 buf += strlen (buf);
9067 for (i = 0; i < aexpr->len; ++i)
9068 buf = pack_hex_byte (buf, aexpr->buf[i]);
9069 *buf = '\0';
9070 }
9071 }
9072
9073 /* Insert a breakpoint. On targets that have software breakpoint
9074 support, we ask the remote target to do the work; on targets
9075 which don't, we insert a traditional memory breakpoint. */
9076
9077 static int
9078 remote_insert_breakpoint (struct target_ops *ops,
9079 struct gdbarch *gdbarch,
9080 struct bp_target_info *bp_tgt)
9081 {
9082 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9083 If it succeeds, then set the support to PACKET_ENABLE. If it
9084 fails, and the user has explicitly requested the Z support then
9085 report an error, otherwise, mark it disabled and go on. */
9086
9087 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9088 {
9089 CORE_ADDR addr = bp_tgt->reqstd_address;
9090 struct remote_state *rs;
9091 char *p, *endbuf;
9092 int bpsize;
9093 struct condition_list *cond = NULL;
9094
9095 /* Make sure the remote is pointing at the right process, if
9096 necessary. */
9097 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9098 set_general_process ();
9099
9100 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9101
9102 rs = get_remote_state ();
9103 p = rs->buf;
9104 endbuf = rs->buf + get_remote_packet_size ();
9105
9106 *(p++) = 'Z';
9107 *(p++) = '0';
9108 *(p++) = ',';
9109 addr = (ULONGEST) remote_address_masked (addr);
9110 p += hexnumstr (p, addr);
9111 xsnprintf (p, endbuf - p, ",%d", bpsize);
9112
9113 if (remote_supports_cond_breakpoints (ops))
9114 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9115
9116 if (remote_can_run_breakpoint_commands (ops))
9117 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9118
9119 putpkt (rs->buf);
9120 getpkt (&rs->buf, &rs->buf_size, 0);
9121
9122 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9123 {
9124 case PACKET_ERROR:
9125 return -1;
9126 case PACKET_OK:
9127 bp_tgt->placed_address = addr;
9128 bp_tgt->placed_size = bpsize;
9129 return 0;
9130 case PACKET_UNKNOWN:
9131 break;
9132 }
9133 }
9134
9135 /* If this breakpoint has target-side commands but this stub doesn't
9136 support Z0 packets, throw error. */
9137 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9138 throw_error (NOT_SUPPORTED_ERROR, _("\
9139 Target doesn't support breakpoints that have target side commands."));
9140
9141 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9142 }
9143
9144 static int
9145 remote_remove_breakpoint (struct target_ops *ops,
9146 struct gdbarch *gdbarch,
9147 struct bp_target_info *bp_tgt)
9148 {
9149 CORE_ADDR addr = bp_tgt->placed_address;
9150 struct remote_state *rs = get_remote_state ();
9151
9152 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9153 {
9154 char *p = rs->buf;
9155 char *endbuf = rs->buf + get_remote_packet_size ();
9156
9157 /* Make sure the remote is pointing at the right process, if
9158 necessary. */
9159 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9160 set_general_process ();
9161
9162 *(p++) = 'z';
9163 *(p++) = '0';
9164 *(p++) = ',';
9165
9166 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9167 p += hexnumstr (p, addr);
9168 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9169
9170 putpkt (rs->buf);
9171 getpkt (&rs->buf, &rs->buf_size, 0);
9172
9173 return (rs->buf[0] == 'E');
9174 }
9175
9176 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9177 }
9178
9179 static enum Z_packet_type
9180 watchpoint_to_Z_packet (int type)
9181 {
9182 switch (type)
9183 {
9184 case hw_write:
9185 return Z_PACKET_WRITE_WP;
9186 break;
9187 case hw_read:
9188 return Z_PACKET_READ_WP;
9189 break;
9190 case hw_access:
9191 return Z_PACKET_ACCESS_WP;
9192 break;
9193 default:
9194 internal_error (__FILE__, __LINE__,
9195 _("hw_bp_to_z: bad watchpoint type %d"), type);
9196 }
9197 }
9198
9199 static int
9200 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9201 enum target_hw_bp_type type, struct expression *cond)
9202 {
9203 struct remote_state *rs = get_remote_state ();
9204 char *endbuf = rs->buf + get_remote_packet_size ();
9205 char *p;
9206 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9207
9208 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9209 return 1;
9210
9211 /* Make sure the remote is pointing at the right process, if
9212 necessary. */
9213 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9214 set_general_process ();
9215
9216 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9217 p = strchr (rs->buf, '\0');
9218 addr = remote_address_masked (addr);
9219 p += hexnumstr (p, (ULONGEST) addr);
9220 xsnprintf (p, endbuf - p, ",%x", len);
9221
9222 putpkt (rs->buf);
9223 getpkt (&rs->buf, &rs->buf_size, 0);
9224
9225 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9226 {
9227 case PACKET_ERROR:
9228 return -1;
9229 case PACKET_UNKNOWN:
9230 return 1;
9231 case PACKET_OK:
9232 return 0;
9233 }
9234 internal_error (__FILE__, __LINE__,
9235 _("remote_insert_watchpoint: reached end of function"));
9236 }
9237
9238 static int
9239 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9240 CORE_ADDR start, int length)
9241 {
9242 CORE_ADDR diff = remote_address_masked (addr - start);
9243
9244 return diff < length;
9245 }
9246
9247
9248 static int
9249 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9250 enum target_hw_bp_type type, struct expression *cond)
9251 {
9252 struct remote_state *rs = get_remote_state ();
9253 char *endbuf = rs->buf + get_remote_packet_size ();
9254 char *p;
9255 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9256
9257 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9258 return -1;
9259
9260 /* Make sure the remote is pointing at the right process, if
9261 necessary. */
9262 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9263 set_general_process ();
9264
9265 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9266 p = strchr (rs->buf, '\0');
9267 addr = remote_address_masked (addr);
9268 p += hexnumstr (p, (ULONGEST) addr);
9269 xsnprintf (p, endbuf - p, ",%x", len);
9270 putpkt (rs->buf);
9271 getpkt (&rs->buf, &rs->buf_size, 0);
9272
9273 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9274 {
9275 case PACKET_ERROR:
9276 case PACKET_UNKNOWN:
9277 return -1;
9278 case PACKET_OK:
9279 return 0;
9280 }
9281 internal_error (__FILE__, __LINE__,
9282 _("remote_remove_watchpoint: reached end of function"));
9283 }
9284
9285
9286 int remote_hw_watchpoint_limit = -1;
9287 int remote_hw_watchpoint_length_limit = -1;
9288 int remote_hw_breakpoint_limit = -1;
9289
9290 static int
9291 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9292 CORE_ADDR addr, int len)
9293 {
9294 if (remote_hw_watchpoint_length_limit == 0)
9295 return 0;
9296 else if (remote_hw_watchpoint_length_limit < 0)
9297 return 1;
9298 else if (len <= remote_hw_watchpoint_length_limit)
9299 return 1;
9300 else
9301 return 0;
9302 }
9303
9304 static int
9305 remote_check_watch_resources (struct target_ops *self,
9306 enum bptype type, int cnt, int ot)
9307 {
9308 if (type == bp_hardware_breakpoint)
9309 {
9310 if (remote_hw_breakpoint_limit == 0)
9311 return 0;
9312 else if (remote_hw_breakpoint_limit < 0)
9313 return 1;
9314 else if (cnt <= remote_hw_breakpoint_limit)
9315 return 1;
9316 }
9317 else
9318 {
9319 if (remote_hw_watchpoint_limit == 0)
9320 return 0;
9321 else if (remote_hw_watchpoint_limit < 0)
9322 return 1;
9323 else if (ot)
9324 return -1;
9325 else if (cnt <= remote_hw_watchpoint_limit)
9326 return 1;
9327 }
9328 return -1;
9329 }
9330
9331 /* The to_stopped_by_sw_breakpoint method of target remote. */
9332
9333 static int
9334 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9335 {
9336 struct remote_state *rs = get_remote_state ();
9337
9338 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9339 }
9340
9341 /* The to_supports_stopped_by_sw_breakpoint method of target
9342 remote. */
9343
9344 static int
9345 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9346 {
9347 struct remote_state *rs = get_remote_state ();
9348
9349 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9350 }
9351
9352 /* The to_stopped_by_hw_breakpoint method of target remote. */
9353
9354 static int
9355 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9356 {
9357 struct remote_state *rs = get_remote_state ();
9358
9359 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9360 }
9361
9362 /* The to_supports_stopped_by_hw_breakpoint method of target
9363 remote. */
9364
9365 static int
9366 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9367 {
9368 struct remote_state *rs = get_remote_state ();
9369
9370 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9371 }
9372
9373 static int
9374 remote_stopped_by_watchpoint (struct target_ops *ops)
9375 {
9376 struct remote_state *rs = get_remote_state ();
9377
9378 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
9379 }
9380
9381 static int
9382 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9383 {
9384 struct remote_state *rs = get_remote_state ();
9385 int rc = 0;
9386
9387 if (remote_stopped_by_watchpoint (target))
9388 {
9389 *addr_p = rs->remote_watch_data_address;
9390 rc = 1;
9391 }
9392
9393 return rc;
9394 }
9395
9396
9397 static int
9398 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9399 struct bp_target_info *bp_tgt)
9400 {
9401 CORE_ADDR addr = bp_tgt->reqstd_address;
9402 struct remote_state *rs;
9403 char *p, *endbuf;
9404 char *message;
9405 int bpsize;
9406
9407 /* The length field should be set to the size of a breakpoint
9408 instruction, even though we aren't inserting one ourselves. */
9409
9410 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9411
9412 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9413 return -1;
9414
9415 /* Make sure the remote is pointing at the right process, if
9416 necessary. */
9417 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9418 set_general_process ();
9419
9420 rs = get_remote_state ();
9421 p = rs->buf;
9422 endbuf = rs->buf + get_remote_packet_size ();
9423
9424 *(p++) = 'Z';
9425 *(p++) = '1';
9426 *(p++) = ',';
9427
9428 addr = remote_address_masked (addr);
9429 p += hexnumstr (p, (ULONGEST) addr);
9430 xsnprintf (p, endbuf - p, ",%x", bpsize);
9431
9432 if (remote_supports_cond_breakpoints (self))
9433 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9434
9435 if (remote_can_run_breakpoint_commands (self))
9436 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9437
9438 putpkt (rs->buf);
9439 getpkt (&rs->buf, &rs->buf_size, 0);
9440
9441 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9442 {
9443 case PACKET_ERROR:
9444 if (rs->buf[1] == '.')
9445 {
9446 message = strchr (rs->buf + 2, '.');
9447 if (message)
9448 error (_("Remote failure reply: %s"), message + 1);
9449 }
9450 return -1;
9451 case PACKET_UNKNOWN:
9452 return -1;
9453 case PACKET_OK:
9454 bp_tgt->placed_address = addr;
9455 bp_tgt->placed_size = bpsize;
9456 return 0;
9457 }
9458 internal_error (__FILE__, __LINE__,
9459 _("remote_insert_hw_breakpoint: reached end of function"));
9460 }
9461
9462
9463 static int
9464 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9465 struct bp_target_info *bp_tgt)
9466 {
9467 CORE_ADDR addr;
9468 struct remote_state *rs = get_remote_state ();
9469 char *p = rs->buf;
9470 char *endbuf = rs->buf + get_remote_packet_size ();
9471
9472 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9473 return -1;
9474
9475 /* Make sure the remote is pointing at the right process, if
9476 necessary. */
9477 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9478 set_general_process ();
9479
9480 *(p++) = 'z';
9481 *(p++) = '1';
9482 *(p++) = ',';
9483
9484 addr = remote_address_masked (bp_tgt->placed_address);
9485 p += hexnumstr (p, (ULONGEST) addr);
9486 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9487
9488 putpkt (rs->buf);
9489 getpkt (&rs->buf, &rs->buf_size, 0);
9490
9491 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9492 {
9493 case PACKET_ERROR:
9494 case PACKET_UNKNOWN:
9495 return -1;
9496 case PACKET_OK:
9497 return 0;
9498 }
9499 internal_error (__FILE__, __LINE__,
9500 _("remote_remove_hw_breakpoint: reached end of function"));
9501 }
9502
9503 /* Verify memory using the "qCRC:" request. */
9504
9505 static int
9506 remote_verify_memory (struct target_ops *ops,
9507 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9508 {
9509 struct remote_state *rs = get_remote_state ();
9510 unsigned long host_crc, target_crc;
9511 char *tmp;
9512
9513 /* It doesn't make sense to use qCRC if the remote target is
9514 connected but not running. */
9515 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9516 {
9517 enum packet_result result;
9518
9519 /* Make sure the remote is pointing at the right process. */
9520 set_general_process ();
9521
9522 /* FIXME: assumes lma can fit into long. */
9523 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9524 (long) lma, (long) size);
9525 putpkt (rs->buf);
9526
9527 /* Be clever; compute the host_crc before waiting for target
9528 reply. */
9529 host_crc = xcrc32 (data, size, 0xffffffff);
9530
9531 getpkt (&rs->buf, &rs->buf_size, 0);
9532
9533 result = packet_ok (rs->buf,
9534 &remote_protocol_packets[PACKET_qCRC]);
9535 if (result == PACKET_ERROR)
9536 return -1;
9537 else if (result == PACKET_OK)
9538 {
9539 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9540 target_crc = target_crc * 16 + fromhex (*tmp);
9541
9542 return (host_crc == target_crc);
9543 }
9544 }
9545
9546 return simple_verify_memory (ops, data, lma, size);
9547 }
9548
9549 /* compare-sections command
9550
9551 With no arguments, compares each loadable section in the exec bfd
9552 with the same memory range on the target, and reports mismatches.
9553 Useful for verifying the image on the target against the exec file. */
9554
9555 static void
9556 compare_sections_command (char *args, int from_tty)
9557 {
9558 asection *s;
9559 struct cleanup *old_chain;
9560 gdb_byte *sectdata;
9561 const char *sectname;
9562 bfd_size_type size;
9563 bfd_vma lma;
9564 int matched = 0;
9565 int mismatched = 0;
9566 int res;
9567 int read_only = 0;
9568
9569 if (!exec_bfd)
9570 error (_("command cannot be used without an exec file"));
9571
9572 /* Make sure the remote is pointing at the right process. */
9573 set_general_process ();
9574
9575 if (args != NULL && strcmp (args, "-r") == 0)
9576 {
9577 read_only = 1;
9578 args = NULL;
9579 }
9580
9581 for (s = exec_bfd->sections; s; s = s->next)
9582 {
9583 if (!(s->flags & SEC_LOAD))
9584 continue; /* Skip non-loadable section. */
9585
9586 if (read_only && (s->flags & SEC_READONLY) == 0)
9587 continue; /* Skip writeable sections */
9588
9589 size = bfd_get_section_size (s);
9590 if (size == 0)
9591 continue; /* Skip zero-length section. */
9592
9593 sectname = bfd_get_section_name (exec_bfd, s);
9594 if (args && strcmp (args, sectname) != 0)
9595 continue; /* Not the section selected by user. */
9596
9597 matched = 1; /* Do this section. */
9598 lma = s->lma;
9599
9600 sectdata = (gdb_byte *) xmalloc (size);
9601 old_chain = make_cleanup (xfree, sectdata);
9602 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9603
9604 res = target_verify_memory (sectdata, lma, size);
9605
9606 if (res == -1)
9607 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9608 paddress (target_gdbarch (), lma),
9609 paddress (target_gdbarch (), lma + size));
9610
9611 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9612 paddress (target_gdbarch (), lma),
9613 paddress (target_gdbarch (), lma + size));
9614 if (res)
9615 printf_filtered ("matched.\n");
9616 else
9617 {
9618 printf_filtered ("MIS-MATCHED!\n");
9619 mismatched++;
9620 }
9621
9622 do_cleanups (old_chain);
9623 }
9624 if (mismatched > 0)
9625 warning (_("One or more sections of the target image does not match\n\
9626 the loaded file\n"));
9627 if (args && !matched)
9628 printf_filtered (_("No loaded section named '%s'.\n"), args);
9629 }
9630
9631 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9632 into remote target. The number of bytes written to the remote
9633 target is returned, or -1 for error. */
9634
9635 static enum target_xfer_status
9636 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9637 const char *annex, const gdb_byte *writebuf,
9638 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9639 struct packet_config *packet)
9640 {
9641 int i, buf_len;
9642 ULONGEST n;
9643 struct remote_state *rs = get_remote_state ();
9644 int max_size = get_memory_write_packet_size ();
9645
9646 if (packet->support == PACKET_DISABLE)
9647 return TARGET_XFER_E_IO;
9648
9649 /* Insert header. */
9650 i = snprintf (rs->buf, max_size,
9651 "qXfer:%s:write:%s:%s:",
9652 object_name, annex ? annex : "",
9653 phex_nz (offset, sizeof offset));
9654 max_size -= (i + 1);
9655
9656 /* Escape as much data as fits into rs->buf. */
9657 buf_len = remote_escape_output
9658 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9659
9660 if (putpkt_binary (rs->buf, i + buf_len) < 0
9661 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9662 || packet_ok (rs->buf, packet) != PACKET_OK)
9663 return TARGET_XFER_E_IO;
9664
9665 unpack_varlen_hex (rs->buf, &n);
9666
9667 *xfered_len = n;
9668 return TARGET_XFER_OK;
9669 }
9670
9671 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9672 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9673 number of bytes read is returned, or 0 for EOF, or -1 for error.
9674 The number of bytes read may be less than LEN without indicating an
9675 EOF. PACKET is checked and updated to indicate whether the remote
9676 target supports this object. */
9677
9678 static enum target_xfer_status
9679 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9680 const char *annex,
9681 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9682 ULONGEST *xfered_len,
9683 struct packet_config *packet)
9684 {
9685 struct remote_state *rs = get_remote_state ();
9686 LONGEST i, n, packet_len;
9687
9688 if (packet->support == PACKET_DISABLE)
9689 return TARGET_XFER_E_IO;
9690
9691 /* Check whether we've cached an end-of-object packet that matches
9692 this request. */
9693 if (rs->finished_object)
9694 {
9695 if (strcmp (object_name, rs->finished_object) == 0
9696 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9697 && offset == rs->finished_offset)
9698 return TARGET_XFER_EOF;
9699
9700
9701 /* Otherwise, we're now reading something different. Discard
9702 the cache. */
9703 xfree (rs->finished_object);
9704 xfree (rs->finished_annex);
9705 rs->finished_object = NULL;
9706 rs->finished_annex = NULL;
9707 }
9708
9709 /* Request only enough to fit in a single packet. The actual data
9710 may not, since we don't know how much of it will need to be escaped;
9711 the target is free to respond with slightly less data. We subtract
9712 five to account for the response type and the protocol frame. */
9713 n = min (get_remote_packet_size () - 5, len);
9714 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9715 object_name, annex ? annex : "",
9716 phex_nz (offset, sizeof offset),
9717 phex_nz (n, sizeof n));
9718 i = putpkt (rs->buf);
9719 if (i < 0)
9720 return TARGET_XFER_E_IO;
9721
9722 rs->buf[0] = '\0';
9723 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9724 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9725 return TARGET_XFER_E_IO;
9726
9727 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9728 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9729
9730 /* 'm' means there is (or at least might be) more data after this
9731 batch. That does not make sense unless there's at least one byte
9732 of data in this reply. */
9733 if (rs->buf[0] == 'm' && packet_len == 1)
9734 error (_("Remote qXfer reply contained no data."));
9735
9736 /* Got some data. */
9737 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9738 packet_len - 1, readbuf, n);
9739
9740 /* 'l' is an EOF marker, possibly including a final block of data,
9741 or possibly empty. If we have the final block of a non-empty
9742 object, record this fact to bypass a subsequent partial read. */
9743 if (rs->buf[0] == 'l' && offset + i > 0)
9744 {
9745 rs->finished_object = xstrdup (object_name);
9746 rs->finished_annex = xstrdup (annex ? annex : "");
9747 rs->finished_offset = offset + i;
9748 }
9749
9750 if (i == 0)
9751 return TARGET_XFER_EOF;
9752 else
9753 {
9754 *xfered_len = i;
9755 return TARGET_XFER_OK;
9756 }
9757 }
9758
9759 static enum target_xfer_status
9760 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9761 const char *annex, gdb_byte *readbuf,
9762 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9763 ULONGEST *xfered_len)
9764 {
9765 struct remote_state *rs;
9766 int i;
9767 char *p2;
9768 char query_type;
9769 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9770
9771 set_remote_traceframe ();
9772 set_general_thread (inferior_ptid);
9773
9774 rs = get_remote_state ();
9775
9776 /* Handle memory using the standard memory routines. */
9777 if (object == TARGET_OBJECT_MEMORY)
9778 {
9779 /* If the remote target is connected but not running, we should
9780 pass this request down to a lower stratum (e.g. the executable
9781 file). */
9782 if (!target_has_execution)
9783 return TARGET_XFER_EOF;
9784
9785 if (writebuf != NULL)
9786 return remote_write_bytes (offset, writebuf, len, unit_size,
9787 xfered_len);
9788 else
9789 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9790 xfered_len);
9791 }
9792
9793 /* Handle SPU memory using qxfer packets. */
9794 if (object == TARGET_OBJECT_SPU)
9795 {
9796 if (readbuf)
9797 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9798 xfered_len, &remote_protocol_packets
9799 [PACKET_qXfer_spu_read]);
9800 else
9801 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9802 xfered_len, &remote_protocol_packets
9803 [PACKET_qXfer_spu_write]);
9804 }
9805
9806 /* Handle extra signal info using qxfer packets. */
9807 if (object == TARGET_OBJECT_SIGNAL_INFO)
9808 {
9809 if (readbuf)
9810 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9811 xfered_len, &remote_protocol_packets
9812 [PACKET_qXfer_siginfo_read]);
9813 else
9814 return remote_write_qxfer (ops, "siginfo", annex,
9815 writebuf, offset, len, xfered_len,
9816 &remote_protocol_packets
9817 [PACKET_qXfer_siginfo_write]);
9818 }
9819
9820 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9821 {
9822 if (readbuf)
9823 return remote_read_qxfer (ops, "statictrace", annex,
9824 readbuf, offset, len, xfered_len,
9825 &remote_protocol_packets
9826 [PACKET_qXfer_statictrace_read]);
9827 else
9828 return TARGET_XFER_E_IO;
9829 }
9830
9831 /* Only handle flash writes. */
9832 if (writebuf != NULL)
9833 {
9834 LONGEST xfered;
9835
9836 switch (object)
9837 {
9838 case TARGET_OBJECT_FLASH:
9839 return remote_flash_write (ops, offset, len, xfered_len,
9840 writebuf);
9841
9842 default:
9843 return TARGET_XFER_E_IO;
9844 }
9845 }
9846
9847 /* Map pre-existing objects onto letters. DO NOT do this for new
9848 objects!!! Instead specify new query packets. */
9849 switch (object)
9850 {
9851 case TARGET_OBJECT_AVR:
9852 query_type = 'R';
9853 break;
9854
9855 case TARGET_OBJECT_AUXV:
9856 gdb_assert (annex == NULL);
9857 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9858 xfered_len,
9859 &remote_protocol_packets[PACKET_qXfer_auxv]);
9860
9861 case TARGET_OBJECT_AVAILABLE_FEATURES:
9862 return remote_read_qxfer
9863 (ops, "features", annex, readbuf, offset, len, xfered_len,
9864 &remote_protocol_packets[PACKET_qXfer_features]);
9865
9866 case TARGET_OBJECT_LIBRARIES:
9867 return remote_read_qxfer
9868 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9869 &remote_protocol_packets[PACKET_qXfer_libraries]);
9870
9871 case TARGET_OBJECT_LIBRARIES_SVR4:
9872 return remote_read_qxfer
9873 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9874 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9875
9876 case TARGET_OBJECT_MEMORY_MAP:
9877 gdb_assert (annex == NULL);
9878 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9879 xfered_len,
9880 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9881
9882 case TARGET_OBJECT_OSDATA:
9883 /* Should only get here if we're connected. */
9884 gdb_assert (rs->remote_desc);
9885 return remote_read_qxfer
9886 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9887 &remote_protocol_packets[PACKET_qXfer_osdata]);
9888
9889 case TARGET_OBJECT_THREADS:
9890 gdb_assert (annex == NULL);
9891 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9892 xfered_len,
9893 &remote_protocol_packets[PACKET_qXfer_threads]);
9894
9895 case TARGET_OBJECT_TRACEFRAME_INFO:
9896 gdb_assert (annex == NULL);
9897 return remote_read_qxfer
9898 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9899 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9900
9901 case TARGET_OBJECT_FDPIC:
9902 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9903 xfered_len,
9904 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9905
9906 case TARGET_OBJECT_OPENVMS_UIB:
9907 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9908 xfered_len,
9909 &remote_protocol_packets[PACKET_qXfer_uib]);
9910
9911 case TARGET_OBJECT_BTRACE:
9912 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9913 xfered_len,
9914 &remote_protocol_packets[PACKET_qXfer_btrace]);
9915
9916 case TARGET_OBJECT_BTRACE_CONF:
9917 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9918 len, xfered_len,
9919 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9920
9921 case TARGET_OBJECT_EXEC_FILE:
9922 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9923 len, xfered_len,
9924 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9925
9926 default:
9927 return TARGET_XFER_E_IO;
9928 }
9929
9930 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9931 large enough let the caller deal with it. */
9932 if (len < get_remote_packet_size ())
9933 return TARGET_XFER_E_IO;
9934 len = get_remote_packet_size ();
9935
9936 /* Except for querying the minimum buffer size, target must be open. */
9937 if (!rs->remote_desc)
9938 error (_("remote query is only available after target open"));
9939
9940 gdb_assert (annex != NULL);
9941 gdb_assert (readbuf != NULL);
9942
9943 p2 = rs->buf;
9944 *p2++ = 'q';
9945 *p2++ = query_type;
9946
9947 /* We used one buffer char for the remote protocol q command and
9948 another for the query type. As the remote protocol encapsulation
9949 uses 4 chars plus one extra in case we are debugging
9950 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9951 string. */
9952 i = 0;
9953 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9954 {
9955 /* Bad caller may have sent forbidden characters. */
9956 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9957 *p2++ = annex[i];
9958 i++;
9959 }
9960 *p2 = '\0';
9961 gdb_assert (annex[i] == '\0');
9962
9963 i = putpkt (rs->buf);
9964 if (i < 0)
9965 return TARGET_XFER_E_IO;
9966
9967 getpkt (&rs->buf, &rs->buf_size, 0);
9968 strcpy ((char *) readbuf, rs->buf);
9969
9970 *xfered_len = strlen ((char *) readbuf);
9971 return TARGET_XFER_OK;
9972 }
9973
9974 static int
9975 remote_search_memory (struct target_ops* ops,
9976 CORE_ADDR start_addr, ULONGEST search_space_len,
9977 const gdb_byte *pattern, ULONGEST pattern_len,
9978 CORE_ADDR *found_addrp)
9979 {
9980 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9981 struct remote_state *rs = get_remote_state ();
9982 int max_size = get_memory_write_packet_size ();
9983 struct packet_config *packet =
9984 &remote_protocol_packets[PACKET_qSearch_memory];
9985 /* Number of packet bytes used to encode the pattern;
9986 this could be more than PATTERN_LEN due to escape characters. */
9987 int escaped_pattern_len;
9988 /* Amount of pattern that was encodable in the packet. */
9989 int used_pattern_len;
9990 int i;
9991 int found;
9992 ULONGEST found_addr;
9993
9994 /* Don't go to the target if we don't have to.
9995 This is done before checking packet->support to avoid the possibility that
9996 a success for this edge case means the facility works in general. */
9997 if (pattern_len > search_space_len)
9998 return 0;
9999 if (pattern_len == 0)
10000 {
10001 *found_addrp = start_addr;
10002 return 1;
10003 }
10004
10005 /* If we already know the packet isn't supported, fall back to the simple
10006 way of searching memory. */
10007
10008 if (packet_config_support (packet) == PACKET_DISABLE)
10009 {
10010 /* Target doesn't provided special support, fall back and use the
10011 standard support (copy memory and do the search here). */
10012 return simple_search_memory (ops, start_addr, search_space_len,
10013 pattern, pattern_len, found_addrp);
10014 }
10015
10016 /* Make sure the remote is pointing at the right process. */
10017 set_general_process ();
10018
10019 /* Insert header. */
10020 i = snprintf (rs->buf, max_size,
10021 "qSearch:memory:%s;%s;",
10022 phex_nz (start_addr, addr_size),
10023 phex_nz (search_space_len, sizeof (search_space_len)));
10024 max_size -= (i + 1);
10025
10026 /* Escape as much data as fits into rs->buf. */
10027 escaped_pattern_len =
10028 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10029 &used_pattern_len, max_size);
10030
10031 /* Bail if the pattern is too large. */
10032 if (used_pattern_len != pattern_len)
10033 error (_("Pattern is too large to transmit to remote target."));
10034
10035 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10036 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10037 || packet_ok (rs->buf, packet) != PACKET_OK)
10038 {
10039 /* The request may not have worked because the command is not
10040 supported. If so, fall back to the simple way. */
10041 if (packet->support == PACKET_DISABLE)
10042 {
10043 return simple_search_memory (ops, start_addr, search_space_len,
10044 pattern, pattern_len, found_addrp);
10045 }
10046 return -1;
10047 }
10048
10049 if (rs->buf[0] == '0')
10050 found = 0;
10051 else if (rs->buf[0] == '1')
10052 {
10053 found = 1;
10054 if (rs->buf[1] != ',')
10055 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10056 unpack_varlen_hex (rs->buf + 2, &found_addr);
10057 *found_addrp = found_addr;
10058 }
10059 else
10060 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10061
10062 return found;
10063 }
10064
10065 static void
10066 remote_rcmd (struct target_ops *self, const char *command,
10067 struct ui_file *outbuf)
10068 {
10069 struct remote_state *rs = get_remote_state ();
10070 char *p = rs->buf;
10071
10072 if (!rs->remote_desc)
10073 error (_("remote rcmd is only available after target open"));
10074
10075 /* Send a NULL command across as an empty command. */
10076 if (command == NULL)
10077 command = "";
10078
10079 /* The query prefix. */
10080 strcpy (rs->buf, "qRcmd,");
10081 p = strchr (rs->buf, '\0');
10082
10083 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10084 > get_remote_packet_size ())
10085 error (_("\"monitor\" command ``%s'' is too long."), command);
10086
10087 /* Encode the actual command. */
10088 bin2hex ((const gdb_byte *) command, p, strlen (command));
10089
10090 if (putpkt (rs->buf) < 0)
10091 error (_("Communication problem with target."));
10092
10093 /* get/display the response */
10094 while (1)
10095 {
10096 char *buf;
10097
10098 /* XXX - see also remote_get_noisy_reply(). */
10099 QUIT; /* Allow user to bail out with ^C. */
10100 rs->buf[0] = '\0';
10101 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10102 {
10103 /* Timeout. Continue to (try to) read responses.
10104 This is better than stopping with an error, assuming the stub
10105 is still executing the (long) monitor command.
10106 If needed, the user can interrupt gdb using C-c, obtaining
10107 an effect similar to stop on timeout. */
10108 continue;
10109 }
10110 buf = rs->buf;
10111 if (buf[0] == '\0')
10112 error (_("Target does not support this command."));
10113 if (buf[0] == 'O' && buf[1] != 'K')
10114 {
10115 remote_console_output (buf + 1); /* 'O' message from stub. */
10116 continue;
10117 }
10118 if (strcmp (buf, "OK") == 0)
10119 break;
10120 if (strlen (buf) == 3 && buf[0] == 'E'
10121 && isdigit (buf[1]) && isdigit (buf[2]))
10122 {
10123 error (_("Protocol error with Rcmd"));
10124 }
10125 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10126 {
10127 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10128
10129 fputc_unfiltered (c, outbuf);
10130 }
10131 break;
10132 }
10133 }
10134
10135 static VEC(mem_region_s) *
10136 remote_memory_map (struct target_ops *ops)
10137 {
10138 VEC(mem_region_s) *result = NULL;
10139 char *text = target_read_stralloc (&current_target,
10140 TARGET_OBJECT_MEMORY_MAP, NULL);
10141
10142 if (text)
10143 {
10144 struct cleanup *back_to = make_cleanup (xfree, text);
10145
10146 result = parse_memory_map (text);
10147 do_cleanups (back_to);
10148 }
10149
10150 return result;
10151 }
10152
10153 static void
10154 packet_command (char *args, int from_tty)
10155 {
10156 struct remote_state *rs = get_remote_state ();
10157
10158 if (!rs->remote_desc)
10159 error (_("command can only be used with remote target"));
10160
10161 if (!args)
10162 error (_("remote-packet command requires packet text as argument"));
10163
10164 puts_filtered ("sending: ");
10165 print_packet (args);
10166 puts_filtered ("\n");
10167 putpkt (args);
10168
10169 getpkt (&rs->buf, &rs->buf_size, 0);
10170 puts_filtered ("received: ");
10171 print_packet (rs->buf);
10172 puts_filtered ("\n");
10173 }
10174
10175 #if 0
10176 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10177
10178 static void display_thread_info (struct gdb_ext_thread_info *info);
10179
10180 static void threadset_test_cmd (char *cmd, int tty);
10181
10182 static void threadalive_test (char *cmd, int tty);
10183
10184 static void threadlist_test_cmd (char *cmd, int tty);
10185
10186 int get_and_display_threadinfo (threadref *ref);
10187
10188 static void threadinfo_test_cmd (char *cmd, int tty);
10189
10190 static int thread_display_step (threadref *ref, void *context);
10191
10192 static void threadlist_update_test_cmd (char *cmd, int tty);
10193
10194 static void init_remote_threadtests (void);
10195
10196 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10197
10198 static void
10199 threadset_test_cmd (char *cmd, int tty)
10200 {
10201 int sample_thread = SAMPLE_THREAD;
10202
10203 printf_filtered (_("Remote threadset test\n"));
10204 set_general_thread (sample_thread);
10205 }
10206
10207
10208 static void
10209 threadalive_test (char *cmd, int tty)
10210 {
10211 int sample_thread = SAMPLE_THREAD;
10212 int pid = ptid_get_pid (inferior_ptid);
10213 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10214
10215 if (remote_thread_alive (ptid))
10216 printf_filtered ("PASS: Thread alive test\n");
10217 else
10218 printf_filtered ("FAIL: Thread alive test\n");
10219 }
10220
10221 void output_threadid (char *title, threadref *ref);
10222
10223 void
10224 output_threadid (char *title, threadref *ref)
10225 {
10226 char hexid[20];
10227
10228 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10229 hexid[16] = 0;
10230 printf_filtered ("%s %s\n", title, (&hexid[0]));
10231 }
10232
10233 static void
10234 threadlist_test_cmd (char *cmd, int tty)
10235 {
10236 int startflag = 1;
10237 threadref nextthread;
10238 int done, result_count;
10239 threadref threadlist[3];
10240
10241 printf_filtered ("Remote Threadlist test\n");
10242 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10243 &result_count, &threadlist[0]))
10244 printf_filtered ("FAIL: threadlist test\n");
10245 else
10246 {
10247 threadref *scan = threadlist;
10248 threadref *limit = scan + result_count;
10249
10250 while (scan < limit)
10251 output_threadid (" thread ", scan++);
10252 }
10253 }
10254
10255 void
10256 display_thread_info (struct gdb_ext_thread_info *info)
10257 {
10258 output_threadid ("Threadid: ", &info->threadid);
10259 printf_filtered ("Name: %s\n ", info->shortname);
10260 printf_filtered ("State: %s\n", info->display);
10261 printf_filtered ("other: %s\n\n", info->more_display);
10262 }
10263
10264 int
10265 get_and_display_threadinfo (threadref *ref)
10266 {
10267 int result;
10268 int set;
10269 struct gdb_ext_thread_info threadinfo;
10270
10271 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10272 | TAG_MOREDISPLAY | TAG_DISPLAY;
10273 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10274 display_thread_info (&threadinfo);
10275 return result;
10276 }
10277
10278 static void
10279 threadinfo_test_cmd (char *cmd, int tty)
10280 {
10281 int athread = SAMPLE_THREAD;
10282 threadref thread;
10283 int set;
10284
10285 int_to_threadref (&thread, athread);
10286 printf_filtered ("Remote Threadinfo test\n");
10287 if (!get_and_display_threadinfo (&thread))
10288 printf_filtered ("FAIL cannot get thread info\n");
10289 }
10290
10291 static int
10292 thread_display_step (threadref *ref, void *context)
10293 {
10294 /* output_threadid(" threadstep ",ref); *//* simple test */
10295 return get_and_display_threadinfo (ref);
10296 }
10297
10298 static void
10299 threadlist_update_test_cmd (char *cmd, int tty)
10300 {
10301 printf_filtered ("Remote Threadlist update test\n");
10302 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10303 }
10304
10305 static void
10306 init_remote_threadtests (void)
10307 {
10308 add_com ("tlist", class_obscure, threadlist_test_cmd,
10309 _("Fetch and print the remote list of "
10310 "thread identifiers, one pkt only"));
10311 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10312 _("Fetch and display info about one thread"));
10313 add_com ("tset", class_obscure, threadset_test_cmd,
10314 _("Test setting to a different thread"));
10315 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10316 _("Iterate through updating all remote thread info"));
10317 add_com ("talive", class_obscure, threadalive_test,
10318 _(" Remote thread alive test "));
10319 }
10320
10321 #endif /* 0 */
10322
10323 /* Convert a thread ID to a string. Returns the string in a static
10324 buffer. */
10325
10326 static char *
10327 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10328 {
10329 static char buf[64];
10330 struct remote_state *rs = get_remote_state ();
10331
10332 if (ptid_equal (ptid, null_ptid))
10333 return normal_pid_to_str (ptid);
10334 else if (ptid_is_pid (ptid))
10335 {
10336 /* Printing an inferior target id. */
10337
10338 /* When multi-process extensions are off, there's no way in the
10339 remote protocol to know the remote process id, if there's any
10340 at all. There's one exception --- when we're connected with
10341 target extended-remote, and we manually attached to a process
10342 with "attach PID". We don't record anywhere a flag that
10343 allows us to distinguish that case from the case of
10344 connecting with extended-remote and the stub already being
10345 attached to a process, and reporting yes to qAttached, hence
10346 no smart special casing here. */
10347 if (!remote_multi_process_p (rs))
10348 {
10349 xsnprintf (buf, sizeof buf, "Remote target");
10350 return buf;
10351 }
10352
10353 return normal_pid_to_str (ptid);
10354 }
10355 else
10356 {
10357 if (ptid_equal (magic_null_ptid, ptid))
10358 xsnprintf (buf, sizeof buf, "Thread <main>");
10359 else if (rs->extended && remote_multi_process_p (rs))
10360 if (ptid_get_lwp (ptid) == 0)
10361 return normal_pid_to_str (ptid);
10362 else
10363 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10364 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10365 else
10366 xsnprintf (buf, sizeof buf, "Thread %ld",
10367 ptid_get_lwp (ptid));
10368 return buf;
10369 }
10370 }
10371
10372 /* Get the address of the thread local variable in OBJFILE which is
10373 stored at OFFSET within the thread local storage for thread PTID. */
10374
10375 static CORE_ADDR
10376 remote_get_thread_local_address (struct target_ops *ops,
10377 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10378 {
10379 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10380 {
10381 struct remote_state *rs = get_remote_state ();
10382 char *p = rs->buf;
10383 char *endp = rs->buf + get_remote_packet_size ();
10384 enum packet_result result;
10385
10386 strcpy (p, "qGetTLSAddr:");
10387 p += strlen (p);
10388 p = write_ptid (p, endp, ptid);
10389 *p++ = ',';
10390 p += hexnumstr (p, offset);
10391 *p++ = ',';
10392 p += hexnumstr (p, lm);
10393 *p++ = '\0';
10394
10395 putpkt (rs->buf);
10396 getpkt (&rs->buf, &rs->buf_size, 0);
10397 result = packet_ok (rs->buf,
10398 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10399 if (result == PACKET_OK)
10400 {
10401 ULONGEST result;
10402
10403 unpack_varlen_hex (rs->buf, &result);
10404 return result;
10405 }
10406 else if (result == PACKET_UNKNOWN)
10407 throw_error (TLS_GENERIC_ERROR,
10408 _("Remote target doesn't support qGetTLSAddr packet"));
10409 else
10410 throw_error (TLS_GENERIC_ERROR,
10411 _("Remote target failed to process qGetTLSAddr request"));
10412 }
10413 else
10414 throw_error (TLS_GENERIC_ERROR,
10415 _("TLS not supported or disabled on this target"));
10416 /* Not reached. */
10417 return 0;
10418 }
10419
10420 /* Provide thread local base, i.e. Thread Information Block address.
10421 Returns 1 if ptid is found and thread_local_base is non zero. */
10422
10423 static int
10424 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10425 {
10426 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10427 {
10428 struct remote_state *rs = get_remote_state ();
10429 char *p = rs->buf;
10430 char *endp = rs->buf + get_remote_packet_size ();
10431 enum packet_result result;
10432
10433 strcpy (p, "qGetTIBAddr:");
10434 p += strlen (p);
10435 p = write_ptid (p, endp, ptid);
10436 *p++ = '\0';
10437
10438 putpkt (rs->buf);
10439 getpkt (&rs->buf, &rs->buf_size, 0);
10440 result = packet_ok (rs->buf,
10441 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10442 if (result == PACKET_OK)
10443 {
10444 ULONGEST result;
10445
10446 unpack_varlen_hex (rs->buf, &result);
10447 if (addr)
10448 *addr = (CORE_ADDR) result;
10449 return 1;
10450 }
10451 else if (result == PACKET_UNKNOWN)
10452 error (_("Remote target doesn't support qGetTIBAddr packet"));
10453 else
10454 error (_("Remote target failed to process qGetTIBAddr request"));
10455 }
10456 else
10457 error (_("qGetTIBAddr not supported or disabled on this target"));
10458 /* Not reached. */
10459 return 0;
10460 }
10461
10462 /* Support for inferring a target description based on the current
10463 architecture and the size of a 'g' packet. While the 'g' packet
10464 can have any size (since optional registers can be left off the
10465 end), some sizes are easily recognizable given knowledge of the
10466 approximate architecture. */
10467
10468 struct remote_g_packet_guess
10469 {
10470 int bytes;
10471 const struct target_desc *tdesc;
10472 };
10473 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10474 DEF_VEC_O(remote_g_packet_guess_s);
10475
10476 struct remote_g_packet_data
10477 {
10478 VEC(remote_g_packet_guess_s) *guesses;
10479 };
10480
10481 static struct gdbarch_data *remote_g_packet_data_handle;
10482
10483 static void *
10484 remote_g_packet_data_init (struct obstack *obstack)
10485 {
10486 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10487 }
10488
10489 void
10490 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10491 const struct target_desc *tdesc)
10492 {
10493 struct remote_g_packet_data *data
10494 = ((struct remote_g_packet_data *)
10495 gdbarch_data (gdbarch, remote_g_packet_data_handle));
10496 struct remote_g_packet_guess new_guess, *guess;
10497 int ix;
10498
10499 gdb_assert (tdesc != NULL);
10500
10501 for (ix = 0;
10502 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10503 ix++)
10504 if (guess->bytes == bytes)
10505 internal_error (__FILE__, __LINE__,
10506 _("Duplicate g packet description added for size %d"),
10507 bytes);
10508
10509 new_guess.bytes = bytes;
10510 new_guess.tdesc = tdesc;
10511 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10512 }
10513
10514 /* Return 1 if remote_read_description would do anything on this target
10515 and architecture, 0 otherwise. */
10516
10517 static int
10518 remote_read_description_p (struct target_ops *target)
10519 {
10520 struct remote_g_packet_data *data
10521 = ((struct remote_g_packet_data *)
10522 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10523
10524 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10525 return 1;
10526
10527 return 0;
10528 }
10529
10530 static const struct target_desc *
10531 remote_read_description (struct target_ops *target)
10532 {
10533 struct remote_g_packet_data *data
10534 = ((struct remote_g_packet_data *)
10535 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10536
10537 /* Do not try this during initial connection, when we do not know
10538 whether there is a running but stopped thread. */
10539 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10540 return target->beneath->to_read_description (target->beneath);
10541
10542 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10543 {
10544 struct remote_g_packet_guess *guess;
10545 int ix;
10546 int bytes = send_g_packet ();
10547
10548 for (ix = 0;
10549 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10550 ix++)
10551 if (guess->bytes == bytes)
10552 return guess->tdesc;
10553
10554 /* We discard the g packet. A minor optimization would be to
10555 hold on to it, and fill the register cache once we have selected
10556 an architecture, but it's too tricky to do safely. */
10557 }
10558
10559 return target->beneath->to_read_description (target->beneath);
10560 }
10561
10562 /* Remote file transfer support. This is host-initiated I/O, not
10563 target-initiated; for target-initiated, see remote-fileio.c. */
10564
10565 /* If *LEFT is at least the length of STRING, copy STRING to
10566 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10567 decrease *LEFT. Otherwise raise an error. */
10568
10569 static void
10570 remote_buffer_add_string (char **buffer, int *left, char *string)
10571 {
10572 int len = strlen (string);
10573
10574 if (len > *left)
10575 error (_("Packet too long for target."));
10576
10577 memcpy (*buffer, string, len);
10578 *buffer += len;
10579 *left -= len;
10580
10581 /* NUL-terminate the buffer as a convenience, if there is
10582 room. */
10583 if (*left)
10584 **buffer = '\0';
10585 }
10586
10587 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10588 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10589 decrease *LEFT. Otherwise raise an error. */
10590
10591 static void
10592 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10593 int len)
10594 {
10595 if (2 * len > *left)
10596 error (_("Packet too long for target."));
10597
10598 bin2hex (bytes, *buffer, len);
10599 *buffer += 2 * len;
10600 *left -= 2 * len;
10601
10602 /* NUL-terminate the buffer as a convenience, if there is
10603 room. */
10604 if (*left)
10605 **buffer = '\0';
10606 }
10607
10608 /* If *LEFT is large enough, convert VALUE to hex and add it to
10609 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10610 decrease *LEFT. Otherwise raise an error. */
10611
10612 static void
10613 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10614 {
10615 int len = hexnumlen (value);
10616
10617 if (len > *left)
10618 error (_("Packet too long for target."));
10619
10620 hexnumstr (*buffer, value);
10621 *buffer += len;
10622 *left -= len;
10623
10624 /* NUL-terminate the buffer as a convenience, if there is
10625 room. */
10626 if (*left)
10627 **buffer = '\0';
10628 }
10629
10630 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10631 value, *REMOTE_ERRNO to the remote error number or zero if none
10632 was included, and *ATTACHMENT to point to the start of the annex
10633 if any. The length of the packet isn't needed here; there may
10634 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10635
10636 Return 0 if the packet could be parsed, -1 if it could not. If
10637 -1 is returned, the other variables may not be initialized. */
10638
10639 static int
10640 remote_hostio_parse_result (char *buffer, int *retcode,
10641 int *remote_errno, char **attachment)
10642 {
10643 char *p, *p2;
10644
10645 *remote_errno = 0;
10646 *attachment = NULL;
10647
10648 if (buffer[0] != 'F')
10649 return -1;
10650
10651 errno = 0;
10652 *retcode = strtol (&buffer[1], &p, 16);
10653 if (errno != 0 || p == &buffer[1])
10654 return -1;
10655
10656 /* Check for ",errno". */
10657 if (*p == ',')
10658 {
10659 errno = 0;
10660 *remote_errno = strtol (p + 1, &p2, 16);
10661 if (errno != 0 || p + 1 == p2)
10662 return -1;
10663 p = p2;
10664 }
10665
10666 /* Check for ";attachment". If there is no attachment, the
10667 packet should end here. */
10668 if (*p == ';')
10669 {
10670 *attachment = p + 1;
10671 return 0;
10672 }
10673 else if (*p == '\0')
10674 return 0;
10675 else
10676 return -1;
10677 }
10678
10679 /* Send a prepared I/O packet to the target and read its response.
10680 The prepared packet is in the global RS->BUF before this function
10681 is called, and the answer is there when we return.
10682
10683 COMMAND_BYTES is the length of the request to send, which may include
10684 binary data. WHICH_PACKET is the packet configuration to check
10685 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10686 is set to the error number and -1 is returned. Otherwise the value
10687 returned by the function is returned.
10688
10689 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10690 attachment is expected; an error will be reported if there's a
10691 mismatch. If one is found, *ATTACHMENT will be set to point into
10692 the packet buffer and *ATTACHMENT_LEN will be set to the
10693 attachment's length. */
10694
10695 static int
10696 remote_hostio_send_command (int command_bytes, int which_packet,
10697 int *remote_errno, char **attachment,
10698 int *attachment_len)
10699 {
10700 struct remote_state *rs = get_remote_state ();
10701 int ret, bytes_read;
10702 char *attachment_tmp;
10703
10704 if (!rs->remote_desc
10705 || packet_support (which_packet) == PACKET_DISABLE)
10706 {
10707 *remote_errno = FILEIO_ENOSYS;
10708 return -1;
10709 }
10710
10711 putpkt_binary (rs->buf, command_bytes);
10712 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10713
10714 /* If it timed out, something is wrong. Don't try to parse the
10715 buffer. */
10716 if (bytes_read < 0)
10717 {
10718 *remote_errno = FILEIO_EINVAL;
10719 return -1;
10720 }
10721
10722 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10723 {
10724 case PACKET_ERROR:
10725 *remote_errno = FILEIO_EINVAL;
10726 return -1;
10727 case PACKET_UNKNOWN:
10728 *remote_errno = FILEIO_ENOSYS;
10729 return -1;
10730 case PACKET_OK:
10731 break;
10732 }
10733
10734 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10735 &attachment_tmp))
10736 {
10737 *remote_errno = FILEIO_EINVAL;
10738 return -1;
10739 }
10740
10741 /* Make sure we saw an attachment if and only if we expected one. */
10742 if ((attachment_tmp == NULL && attachment != NULL)
10743 || (attachment_tmp != NULL && attachment == NULL))
10744 {
10745 *remote_errno = FILEIO_EINVAL;
10746 return -1;
10747 }
10748
10749 /* If an attachment was found, it must point into the packet buffer;
10750 work out how many bytes there were. */
10751 if (attachment_tmp != NULL)
10752 {
10753 *attachment = attachment_tmp;
10754 *attachment_len = bytes_read - (*attachment - rs->buf);
10755 }
10756
10757 return ret;
10758 }
10759
10760 /* Invalidate the readahead cache. */
10761
10762 static void
10763 readahead_cache_invalidate (void)
10764 {
10765 struct remote_state *rs = get_remote_state ();
10766
10767 rs->readahead_cache.fd = -1;
10768 }
10769
10770 /* Invalidate the readahead cache if it is holding data for FD. */
10771
10772 static void
10773 readahead_cache_invalidate_fd (int fd)
10774 {
10775 struct remote_state *rs = get_remote_state ();
10776
10777 if (rs->readahead_cache.fd == fd)
10778 rs->readahead_cache.fd = -1;
10779 }
10780
10781 /* Set the filesystem remote_hostio functions that take FILENAME
10782 arguments will use. Return 0 on success, or -1 if an error
10783 occurs (and set *REMOTE_ERRNO). */
10784
10785 static int
10786 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10787 {
10788 struct remote_state *rs = get_remote_state ();
10789 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10790 char *p = rs->buf;
10791 int left = get_remote_packet_size () - 1;
10792 char arg[9];
10793 int ret;
10794
10795 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10796 return 0;
10797
10798 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10799 return 0;
10800
10801 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10802
10803 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10804 remote_buffer_add_string (&p, &left, arg);
10805
10806 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10807 remote_errno, NULL, NULL);
10808
10809 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10810 return 0;
10811
10812 if (ret == 0)
10813 rs->fs_pid = required_pid;
10814
10815 return ret;
10816 }
10817
10818 /* Implementation of to_fileio_open. */
10819
10820 static int
10821 remote_hostio_open (struct target_ops *self,
10822 struct inferior *inf, const char *filename,
10823 int flags, int mode, int warn_if_slow,
10824 int *remote_errno)
10825 {
10826 struct remote_state *rs = get_remote_state ();
10827 char *p = rs->buf;
10828 int left = get_remote_packet_size () - 1;
10829
10830 if (warn_if_slow)
10831 {
10832 static int warning_issued = 0;
10833
10834 printf_unfiltered (_("Reading %s from remote target...\n"),
10835 filename);
10836
10837 if (!warning_issued)
10838 {
10839 warning (_("File transfers from remote targets can be slow."
10840 " Use \"set sysroot\" to access files locally"
10841 " instead."));
10842 warning_issued = 1;
10843 }
10844 }
10845
10846 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10847 return -1;
10848
10849 remote_buffer_add_string (&p, &left, "vFile:open:");
10850
10851 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10852 strlen (filename));
10853 remote_buffer_add_string (&p, &left, ",");
10854
10855 remote_buffer_add_int (&p, &left, flags);
10856 remote_buffer_add_string (&p, &left, ",");
10857
10858 remote_buffer_add_int (&p, &left, mode);
10859
10860 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10861 remote_errno, NULL, NULL);
10862 }
10863
10864 /* Implementation of to_fileio_pwrite. */
10865
10866 static int
10867 remote_hostio_pwrite (struct target_ops *self,
10868 int fd, const gdb_byte *write_buf, int len,
10869 ULONGEST offset, int *remote_errno)
10870 {
10871 struct remote_state *rs = get_remote_state ();
10872 char *p = rs->buf;
10873 int left = get_remote_packet_size ();
10874 int out_len;
10875
10876 readahead_cache_invalidate_fd (fd);
10877
10878 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10879
10880 remote_buffer_add_int (&p, &left, fd);
10881 remote_buffer_add_string (&p, &left, ",");
10882
10883 remote_buffer_add_int (&p, &left, offset);
10884 remote_buffer_add_string (&p, &left, ",");
10885
10886 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10887 get_remote_packet_size () - (p - rs->buf));
10888
10889 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10890 remote_errno, NULL, NULL);
10891 }
10892
10893 /* Helper for the implementation of to_fileio_pread. Read the file
10894 from the remote side with vFile:pread. */
10895
10896 static int
10897 remote_hostio_pread_vFile (struct target_ops *self,
10898 int fd, gdb_byte *read_buf, int len,
10899 ULONGEST offset, int *remote_errno)
10900 {
10901 struct remote_state *rs = get_remote_state ();
10902 char *p = rs->buf;
10903 char *attachment;
10904 int left = get_remote_packet_size ();
10905 int ret, attachment_len;
10906 int read_len;
10907
10908 remote_buffer_add_string (&p, &left, "vFile:pread:");
10909
10910 remote_buffer_add_int (&p, &left, fd);
10911 remote_buffer_add_string (&p, &left, ",");
10912
10913 remote_buffer_add_int (&p, &left, len);
10914 remote_buffer_add_string (&p, &left, ",");
10915
10916 remote_buffer_add_int (&p, &left, offset);
10917
10918 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10919 remote_errno, &attachment,
10920 &attachment_len);
10921
10922 if (ret < 0)
10923 return ret;
10924
10925 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10926 read_buf, len);
10927 if (read_len != ret)
10928 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10929
10930 return ret;
10931 }
10932
10933 /* Serve pread from the readahead cache. Returns number of bytes
10934 read, or 0 if the request can't be served from the cache. */
10935
10936 static int
10937 remote_hostio_pread_from_cache (struct remote_state *rs,
10938 int fd, gdb_byte *read_buf, size_t len,
10939 ULONGEST offset)
10940 {
10941 struct readahead_cache *cache = &rs->readahead_cache;
10942
10943 if (cache->fd == fd
10944 && cache->offset <= offset
10945 && offset < cache->offset + cache->bufsize)
10946 {
10947 ULONGEST max = cache->offset + cache->bufsize;
10948
10949 if (offset + len > max)
10950 len = max - offset;
10951
10952 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10953 return len;
10954 }
10955
10956 return 0;
10957 }
10958
10959 /* Implementation of to_fileio_pread. */
10960
10961 static int
10962 remote_hostio_pread (struct target_ops *self,
10963 int fd, gdb_byte *read_buf, int len,
10964 ULONGEST offset, int *remote_errno)
10965 {
10966 int ret;
10967 struct remote_state *rs = get_remote_state ();
10968 struct readahead_cache *cache = &rs->readahead_cache;
10969
10970 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10971 if (ret > 0)
10972 {
10973 cache->hit_count++;
10974
10975 if (remote_debug)
10976 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10977 pulongest (cache->hit_count));
10978 return ret;
10979 }
10980
10981 cache->miss_count++;
10982 if (remote_debug)
10983 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10984 pulongest (cache->miss_count));
10985
10986 cache->fd = fd;
10987 cache->offset = offset;
10988 cache->bufsize = get_remote_packet_size ();
10989 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
10990
10991 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10992 cache->offset, remote_errno);
10993 if (ret <= 0)
10994 {
10995 readahead_cache_invalidate_fd (fd);
10996 return ret;
10997 }
10998
10999 cache->bufsize = ret;
11000 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11001 }
11002
11003 /* Implementation of to_fileio_close. */
11004
11005 static int
11006 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11007 {
11008 struct remote_state *rs = get_remote_state ();
11009 char *p = rs->buf;
11010 int left = get_remote_packet_size () - 1;
11011
11012 readahead_cache_invalidate_fd (fd);
11013
11014 remote_buffer_add_string (&p, &left, "vFile:close:");
11015
11016 remote_buffer_add_int (&p, &left, fd);
11017
11018 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11019 remote_errno, NULL, NULL);
11020 }
11021
11022 /* Implementation of to_fileio_unlink. */
11023
11024 static int
11025 remote_hostio_unlink (struct target_ops *self,
11026 struct inferior *inf, const char *filename,
11027 int *remote_errno)
11028 {
11029 struct remote_state *rs = get_remote_state ();
11030 char *p = rs->buf;
11031 int left = get_remote_packet_size () - 1;
11032
11033 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11034 return -1;
11035
11036 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11037
11038 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11039 strlen (filename));
11040
11041 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11042 remote_errno, NULL, NULL);
11043 }
11044
11045 /* Implementation of to_fileio_readlink. */
11046
11047 static char *
11048 remote_hostio_readlink (struct target_ops *self,
11049 struct inferior *inf, const char *filename,
11050 int *remote_errno)
11051 {
11052 struct remote_state *rs = get_remote_state ();
11053 char *p = rs->buf;
11054 char *attachment;
11055 int left = get_remote_packet_size ();
11056 int len, attachment_len;
11057 int read_len;
11058 char *ret;
11059
11060 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11061 return NULL;
11062
11063 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11064
11065 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11066 strlen (filename));
11067
11068 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11069 remote_errno, &attachment,
11070 &attachment_len);
11071
11072 if (len < 0)
11073 return NULL;
11074
11075 ret = (char *) xmalloc (len + 1);
11076
11077 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11078 (gdb_byte *) ret, len);
11079 if (read_len != len)
11080 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11081
11082 ret[len] = '\0';
11083 return ret;
11084 }
11085
11086 /* Implementation of to_fileio_fstat. */
11087
11088 static int
11089 remote_hostio_fstat (struct target_ops *self,
11090 int fd, struct stat *st,
11091 int *remote_errno)
11092 {
11093 struct remote_state *rs = get_remote_state ();
11094 char *p = rs->buf;
11095 int left = get_remote_packet_size ();
11096 int attachment_len, ret;
11097 char *attachment;
11098 struct fio_stat fst;
11099 int read_len;
11100
11101 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11102
11103 remote_buffer_add_int (&p, &left, fd);
11104
11105 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11106 remote_errno, &attachment,
11107 &attachment_len);
11108 if (ret < 0)
11109 {
11110 if (*remote_errno != FILEIO_ENOSYS)
11111 return ret;
11112
11113 /* Strictly we should return -1, ENOSYS here, but when
11114 "set sysroot remote:" was implemented in August 2008
11115 BFD's need for a stat function was sidestepped with
11116 this hack. This was not remedied until March 2015
11117 so we retain the previous behavior to avoid breaking
11118 compatibility.
11119
11120 Note that the memset is a March 2015 addition; older
11121 GDBs set st_size *and nothing else* so the structure
11122 would have garbage in all other fields. This might
11123 break something but retaining the previous behavior
11124 here would be just too wrong. */
11125
11126 memset (st, 0, sizeof (struct stat));
11127 st->st_size = INT_MAX;
11128 return 0;
11129 }
11130
11131 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11132 (gdb_byte *) &fst, sizeof (fst));
11133
11134 if (read_len != ret)
11135 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11136
11137 if (read_len != sizeof (fst))
11138 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11139 read_len, (int) sizeof (fst));
11140
11141 remote_fileio_to_host_stat (&fst, st);
11142
11143 return 0;
11144 }
11145
11146 /* Implementation of to_filesystem_is_local. */
11147
11148 static int
11149 remote_filesystem_is_local (struct target_ops *self)
11150 {
11151 /* Valgrind GDB presents itself as a remote target but works
11152 on the local filesystem: it does not implement remote get
11153 and users are not expected to set a sysroot. To handle
11154 this case we treat the remote filesystem as local if the
11155 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11156 does not support vFile:open. */
11157 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11158 {
11159 enum packet_support ps = packet_support (PACKET_vFile_open);
11160
11161 if (ps == PACKET_SUPPORT_UNKNOWN)
11162 {
11163 int fd, remote_errno;
11164
11165 /* Try opening a file to probe support. The supplied
11166 filename is irrelevant, we only care about whether
11167 the stub recognizes the packet or not. */
11168 fd = remote_hostio_open (self, NULL, "just probing",
11169 FILEIO_O_RDONLY, 0700, 0,
11170 &remote_errno);
11171
11172 if (fd >= 0)
11173 remote_hostio_close (self, fd, &remote_errno);
11174
11175 ps = packet_support (PACKET_vFile_open);
11176 }
11177
11178 if (ps == PACKET_DISABLE)
11179 {
11180 static int warning_issued = 0;
11181
11182 if (!warning_issued)
11183 {
11184 warning (_("remote target does not support file"
11185 " transfer, attempting to access files"
11186 " from local filesystem."));
11187 warning_issued = 1;
11188 }
11189
11190 return 1;
11191 }
11192 }
11193
11194 return 0;
11195 }
11196
11197 static int
11198 remote_fileio_errno_to_host (int errnum)
11199 {
11200 switch (errnum)
11201 {
11202 case FILEIO_EPERM:
11203 return EPERM;
11204 case FILEIO_ENOENT:
11205 return ENOENT;
11206 case FILEIO_EINTR:
11207 return EINTR;
11208 case FILEIO_EIO:
11209 return EIO;
11210 case FILEIO_EBADF:
11211 return EBADF;
11212 case FILEIO_EACCES:
11213 return EACCES;
11214 case FILEIO_EFAULT:
11215 return EFAULT;
11216 case FILEIO_EBUSY:
11217 return EBUSY;
11218 case FILEIO_EEXIST:
11219 return EEXIST;
11220 case FILEIO_ENODEV:
11221 return ENODEV;
11222 case FILEIO_ENOTDIR:
11223 return ENOTDIR;
11224 case FILEIO_EISDIR:
11225 return EISDIR;
11226 case FILEIO_EINVAL:
11227 return EINVAL;
11228 case FILEIO_ENFILE:
11229 return ENFILE;
11230 case FILEIO_EMFILE:
11231 return EMFILE;
11232 case FILEIO_EFBIG:
11233 return EFBIG;
11234 case FILEIO_ENOSPC:
11235 return ENOSPC;
11236 case FILEIO_ESPIPE:
11237 return ESPIPE;
11238 case FILEIO_EROFS:
11239 return EROFS;
11240 case FILEIO_ENOSYS:
11241 return ENOSYS;
11242 case FILEIO_ENAMETOOLONG:
11243 return ENAMETOOLONG;
11244 }
11245 return -1;
11246 }
11247
11248 static char *
11249 remote_hostio_error (int errnum)
11250 {
11251 int host_error = remote_fileio_errno_to_host (errnum);
11252
11253 if (host_error == -1)
11254 error (_("Unknown remote I/O error %d"), errnum);
11255 else
11256 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11257 }
11258
11259 static void
11260 remote_hostio_close_cleanup (void *opaque)
11261 {
11262 int fd = *(int *) opaque;
11263 int remote_errno;
11264
11265 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11266 }
11267
11268 void
11269 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11270 {
11271 struct cleanup *back_to, *close_cleanup;
11272 int retcode, fd, remote_errno, bytes, io_size;
11273 FILE *file;
11274 gdb_byte *buffer;
11275 int bytes_in_buffer;
11276 int saw_eof;
11277 ULONGEST offset;
11278 struct remote_state *rs = get_remote_state ();
11279
11280 if (!rs->remote_desc)
11281 error (_("command can only be used with remote target"));
11282
11283 file = gdb_fopen_cloexec (local_file, "rb");
11284 if (file == NULL)
11285 perror_with_name (local_file);
11286 back_to = make_cleanup_fclose (file);
11287
11288 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11289 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11290 | FILEIO_O_TRUNC),
11291 0700, 0, &remote_errno);
11292 if (fd == -1)
11293 remote_hostio_error (remote_errno);
11294
11295 /* Send up to this many bytes at once. They won't all fit in the
11296 remote packet limit, so we'll transfer slightly fewer. */
11297 io_size = get_remote_packet_size ();
11298 buffer = (gdb_byte *) xmalloc (io_size);
11299 make_cleanup (xfree, buffer);
11300
11301 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11302
11303 bytes_in_buffer = 0;
11304 saw_eof = 0;
11305 offset = 0;
11306 while (bytes_in_buffer || !saw_eof)
11307 {
11308 if (!saw_eof)
11309 {
11310 bytes = fread (buffer + bytes_in_buffer, 1,
11311 io_size - bytes_in_buffer,
11312 file);
11313 if (bytes == 0)
11314 {
11315 if (ferror (file))
11316 error (_("Error reading %s."), local_file);
11317 else
11318 {
11319 /* EOF. Unless there is something still in the
11320 buffer from the last iteration, we are done. */
11321 saw_eof = 1;
11322 if (bytes_in_buffer == 0)
11323 break;
11324 }
11325 }
11326 }
11327 else
11328 bytes = 0;
11329
11330 bytes += bytes_in_buffer;
11331 bytes_in_buffer = 0;
11332
11333 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11334 fd, buffer, bytes,
11335 offset, &remote_errno);
11336
11337 if (retcode < 0)
11338 remote_hostio_error (remote_errno);
11339 else if (retcode == 0)
11340 error (_("Remote write of %d bytes returned 0!"), bytes);
11341 else if (retcode < bytes)
11342 {
11343 /* Short write. Save the rest of the read data for the next
11344 write. */
11345 bytes_in_buffer = bytes - retcode;
11346 memmove (buffer, buffer + retcode, bytes_in_buffer);
11347 }
11348
11349 offset += retcode;
11350 }
11351
11352 discard_cleanups (close_cleanup);
11353 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11354 remote_hostio_error (remote_errno);
11355
11356 if (from_tty)
11357 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11358 do_cleanups (back_to);
11359 }
11360
11361 void
11362 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11363 {
11364 struct cleanup *back_to, *close_cleanup;
11365 int fd, remote_errno, bytes, io_size;
11366 FILE *file;
11367 gdb_byte *buffer;
11368 ULONGEST offset;
11369 struct remote_state *rs = get_remote_state ();
11370
11371 if (!rs->remote_desc)
11372 error (_("command can only be used with remote target"));
11373
11374 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11375 remote_file, FILEIO_O_RDONLY, 0, 0,
11376 &remote_errno);
11377 if (fd == -1)
11378 remote_hostio_error (remote_errno);
11379
11380 file = gdb_fopen_cloexec (local_file, "wb");
11381 if (file == NULL)
11382 perror_with_name (local_file);
11383 back_to = make_cleanup_fclose (file);
11384
11385 /* Send up to this many bytes at once. They won't all fit in the
11386 remote packet limit, so we'll transfer slightly fewer. */
11387 io_size = get_remote_packet_size ();
11388 buffer = (gdb_byte *) xmalloc (io_size);
11389 make_cleanup (xfree, buffer);
11390
11391 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11392
11393 offset = 0;
11394 while (1)
11395 {
11396 bytes = remote_hostio_pread (find_target_at (process_stratum),
11397 fd, buffer, io_size, offset, &remote_errno);
11398 if (bytes == 0)
11399 /* Success, but no bytes, means end-of-file. */
11400 break;
11401 if (bytes == -1)
11402 remote_hostio_error (remote_errno);
11403
11404 offset += bytes;
11405
11406 bytes = fwrite (buffer, 1, bytes, file);
11407 if (bytes == 0)
11408 perror_with_name (local_file);
11409 }
11410
11411 discard_cleanups (close_cleanup);
11412 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11413 remote_hostio_error (remote_errno);
11414
11415 if (from_tty)
11416 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11417 do_cleanups (back_to);
11418 }
11419
11420 void
11421 remote_file_delete (const char *remote_file, int from_tty)
11422 {
11423 int retcode, remote_errno;
11424 struct remote_state *rs = get_remote_state ();
11425
11426 if (!rs->remote_desc)
11427 error (_("command can only be used with remote target"));
11428
11429 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11430 NULL, remote_file, &remote_errno);
11431 if (retcode == -1)
11432 remote_hostio_error (remote_errno);
11433
11434 if (from_tty)
11435 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11436 }
11437
11438 static void
11439 remote_put_command (char *args, int from_tty)
11440 {
11441 struct cleanup *back_to;
11442 char **argv;
11443
11444 if (args == NULL)
11445 error_no_arg (_("file to put"));
11446
11447 argv = gdb_buildargv (args);
11448 back_to = make_cleanup_freeargv (argv);
11449 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11450 error (_("Invalid parameters to remote put"));
11451
11452 remote_file_put (argv[0], argv[1], from_tty);
11453
11454 do_cleanups (back_to);
11455 }
11456
11457 static void
11458 remote_get_command (char *args, int from_tty)
11459 {
11460 struct cleanup *back_to;
11461 char **argv;
11462
11463 if (args == NULL)
11464 error_no_arg (_("file to get"));
11465
11466 argv = gdb_buildargv (args);
11467 back_to = make_cleanup_freeargv (argv);
11468 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11469 error (_("Invalid parameters to remote get"));
11470
11471 remote_file_get (argv[0], argv[1], from_tty);
11472
11473 do_cleanups (back_to);
11474 }
11475
11476 static void
11477 remote_delete_command (char *args, int from_tty)
11478 {
11479 struct cleanup *back_to;
11480 char **argv;
11481
11482 if (args == NULL)
11483 error_no_arg (_("file to delete"));
11484
11485 argv = gdb_buildargv (args);
11486 back_to = make_cleanup_freeargv (argv);
11487 if (argv[0] == NULL || argv[1] != NULL)
11488 error (_("Invalid parameters to remote delete"));
11489
11490 remote_file_delete (argv[0], from_tty);
11491
11492 do_cleanups (back_to);
11493 }
11494
11495 static void
11496 remote_command (char *args, int from_tty)
11497 {
11498 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11499 }
11500
11501 static int
11502 remote_can_execute_reverse (struct target_ops *self)
11503 {
11504 if (packet_support (PACKET_bs) == PACKET_ENABLE
11505 || packet_support (PACKET_bc) == PACKET_ENABLE)
11506 return 1;
11507 else
11508 return 0;
11509 }
11510
11511 static int
11512 remote_supports_non_stop (struct target_ops *self)
11513 {
11514 return 1;
11515 }
11516
11517 static int
11518 remote_supports_disable_randomization (struct target_ops *self)
11519 {
11520 /* Only supported in extended mode. */
11521 return 0;
11522 }
11523
11524 static int
11525 remote_supports_multi_process (struct target_ops *self)
11526 {
11527 struct remote_state *rs = get_remote_state ();
11528
11529 /* Only extended-remote handles being attached to multiple
11530 processes, even though plain remote can use the multi-process
11531 thread id extensions, so that GDB knows the target process's
11532 PID. */
11533 return rs->extended && remote_multi_process_p (rs);
11534 }
11535
11536 static int
11537 remote_supports_cond_tracepoints (void)
11538 {
11539 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11540 }
11541
11542 static int
11543 remote_supports_cond_breakpoints (struct target_ops *self)
11544 {
11545 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11546 }
11547
11548 static int
11549 remote_supports_fast_tracepoints (void)
11550 {
11551 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11552 }
11553
11554 static int
11555 remote_supports_static_tracepoints (void)
11556 {
11557 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11558 }
11559
11560 static int
11561 remote_supports_install_in_trace (void)
11562 {
11563 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11564 }
11565
11566 static int
11567 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11568 {
11569 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11570 == PACKET_ENABLE);
11571 }
11572
11573 static int
11574 remote_supports_string_tracing (struct target_ops *self)
11575 {
11576 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11577 }
11578
11579 static int
11580 remote_can_run_breakpoint_commands (struct target_ops *self)
11581 {
11582 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11583 }
11584
11585 static void
11586 remote_trace_init (struct target_ops *self)
11587 {
11588 putpkt ("QTinit");
11589 remote_get_noisy_reply (&target_buf, &target_buf_size);
11590 if (strcmp (target_buf, "OK") != 0)
11591 error (_("Target does not support this command."));
11592 }
11593
11594 static void free_actions_list (char **actions_list);
11595 static void free_actions_list_cleanup_wrapper (void *);
11596 static void
11597 free_actions_list_cleanup_wrapper (void *al)
11598 {
11599 free_actions_list ((char **) al);
11600 }
11601
11602 static void
11603 free_actions_list (char **actions_list)
11604 {
11605 int ndx;
11606
11607 if (actions_list == 0)
11608 return;
11609
11610 for (ndx = 0; actions_list[ndx]; ndx++)
11611 xfree (actions_list[ndx]);
11612
11613 xfree (actions_list);
11614 }
11615
11616 /* Recursive routine to walk through command list including loops, and
11617 download packets for each command. */
11618
11619 static void
11620 remote_download_command_source (int num, ULONGEST addr,
11621 struct command_line *cmds)
11622 {
11623 struct remote_state *rs = get_remote_state ();
11624 struct command_line *cmd;
11625
11626 for (cmd = cmds; cmd; cmd = cmd->next)
11627 {
11628 QUIT; /* Allow user to bail out with ^C. */
11629 strcpy (rs->buf, "QTDPsrc:");
11630 encode_source_string (num, addr, "cmd", cmd->line,
11631 rs->buf + strlen (rs->buf),
11632 rs->buf_size - strlen (rs->buf));
11633 putpkt (rs->buf);
11634 remote_get_noisy_reply (&target_buf, &target_buf_size);
11635 if (strcmp (target_buf, "OK"))
11636 warning (_("Target does not support source download."));
11637
11638 if (cmd->control_type == while_control
11639 || cmd->control_type == while_stepping_control)
11640 {
11641 remote_download_command_source (num, addr, *cmd->body_list);
11642
11643 QUIT; /* Allow user to bail out with ^C. */
11644 strcpy (rs->buf, "QTDPsrc:");
11645 encode_source_string (num, addr, "cmd", "end",
11646 rs->buf + strlen (rs->buf),
11647 rs->buf_size - strlen (rs->buf));
11648 putpkt (rs->buf);
11649 remote_get_noisy_reply (&target_buf, &target_buf_size);
11650 if (strcmp (target_buf, "OK"))
11651 warning (_("Target does not support source download."));
11652 }
11653 }
11654 }
11655
11656 static void
11657 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11658 {
11659 #define BUF_SIZE 2048
11660
11661 CORE_ADDR tpaddr;
11662 char addrbuf[40];
11663 char buf[BUF_SIZE];
11664 char **tdp_actions;
11665 char **stepping_actions;
11666 int ndx;
11667 struct cleanup *old_chain = NULL;
11668 struct agent_expr *aexpr;
11669 struct cleanup *aexpr_chain = NULL;
11670 char *pkt;
11671 struct breakpoint *b = loc->owner;
11672 struct tracepoint *t = (struct tracepoint *) b;
11673
11674 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11675 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11676 tdp_actions);
11677 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11678 stepping_actions);
11679
11680 tpaddr = loc->address;
11681 sprintf_vma (addrbuf, tpaddr);
11682 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11683 addrbuf, /* address */
11684 (b->enable_state == bp_enabled ? 'E' : 'D'),
11685 t->step_count, t->pass_count);
11686 /* Fast tracepoints are mostly handled by the target, but we can
11687 tell the target how big of an instruction block should be moved
11688 around. */
11689 if (b->type == bp_fast_tracepoint)
11690 {
11691 /* Only test for support at download time; we may not know
11692 target capabilities at definition time. */
11693 if (remote_supports_fast_tracepoints ())
11694 {
11695 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11696 NULL))
11697 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11698 gdb_insn_length (loc->gdbarch, tpaddr));
11699 else
11700 /* If it passed validation at definition but fails now,
11701 something is very wrong. */
11702 internal_error (__FILE__, __LINE__,
11703 _("Fast tracepoint not "
11704 "valid during download"));
11705 }
11706 else
11707 /* Fast tracepoints are functionally identical to regular
11708 tracepoints, so don't take lack of support as a reason to
11709 give up on the trace run. */
11710 warning (_("Target does not support fast tracepoints, "
11711 "downloading %d as regular tracepoint"), b->number);
11712 }
11713 else if (b->type == bp_static_tracepoint)
11714 {
11715 /* Only test for support at download time; we may not know
11716 target capabilities at definition time. */
11717 if (remote_supports_static_tracepoints ())
11718 {
11719 struct static_tracepoint_marker marker;
11720
11721 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11722 strcat (buf, ":S");
11723 else
11724 error (_("Static tracepoint not valid during download"));
11725 }
11726 else
11727 /* Fast tracepoints are functionally identical to regular
11728 tracepoints, so don't take lack of support as a reason
11729 to give up on the trace run. */
11730 error (_("Target does not support static tracepoints"));
11731 }
11732 /* If the tracepoint has a conditional, make it into an agent
11733 expression and append to the definition. */
11734 if (loc->cond)
11735 {
11736 /* Only test support at download time, we may not know target
11737 capabilities at definition time. */
11738 if (remote_supports_cond_tracepoints ())
11739 {
11740 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11741 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11742 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11743 aexpr->len);
11744 pkt = buf + strlen (buf);
11745 for (ndx = 0; ndx < aexpr->len; ++ndx)
11746 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11747 *pkt = '\0';
11748 do_cleanups (aexpr_chain);
11749 }
11750 else
11751 warning (_("Target does not support conditional tracepoints, "
11752 "ignoring tp %d cond"), b->number);
11753 }
11754
11755 if (b->commands || *default_collect)
11756 strcat (buf, "-");
11757 putpkt (buf);
11758 remote_get_noisy_reply (&target_buf, &target_buf_size);
11759 if (strcmp (target_buf, "OK"))
11760 error (_("Target does not support tracepoints."));
11761
11762 /* do_single_steps (t); */
11763 if (tdp_actions)
11764 {
11765 for (ndx = 0; tdp_actions[ndx]; ndx++)
11766 {
11767 QUIT; /* Allow user to bail out with ^C. */
11768 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11769 b->number, addrbuf, /* address */
11770 tdp_actions[ndx],
11771 ((tdp_actions[ndx + 1] || stepping_actions)
11772 ? '-' : 0));
11773 putpkt (buf);
11774 remote_get_noisy_reply (&target_buf,
11775 &target_buf_size);
11776 if (strcmp (target_buf, "OK"))
11777 error (_("Error on target while setting tracepoints."));
11778 }
11779 }
11780 if (stepping_actions)
11781 {
11782 for (ndx = 0; stepping_actions[ndx]; ndx++)
11783 {
11784 QUIT; /* Allow user to bail out with ^C. */
11785 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11786 b->number, addrbuf, /* address */
11787 ((ndx == 0) ? "S" : ""),
11788 stepping_actions[ndx],
11789 (stepping_actions[ndx + 1] ? "-" : ""));
11790 putpkt (buf);
11791 remote_get_noisy_reply (&target_buf,
11792 &target_buf_size);
11793 if (strcmp (target_buf, "OK"))
11794 error (_("Error on target while setting tracepoints."));
11795 }
11796 }
11797
11798 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11799 {
11800 if (b->location != NULL)
11801 {
11802 strcpy (buf, "QTDPsrc:");
11803 encode_source_string (b->number, loc->address, "at",
11804 event_location_to_string (b->location),
11805 buf + strlen (buf), 2048 - strlen (buf));
11806 putpkt (buf);
11807 remote_get_noisy_reply (&target_buf, &target_buf_size);
11808 if (strcmp (target_buf, "OK"))
11809 warning (_("Target does not support source download."));
11810 }
11811 if (b->cond_string)
11812 {
11813 strcpy (buf, "QTDPsrc:");
11814 encode_source_string (b->number, loc->address,
11815 "cond", b->cond_string, buf + strlen (buf),
11816 2048 - strlen (buf));
11817 putpkt (buf);
11818 remote_get_noisy_reply (&target_buf, &target_buf_size);
11819 if (strcmp (target_buf, "OK"))
11820 warning (_("Target does not support source download."));
11821 }
11822 remote_download_command_source (b->number, loc->address,
11823 breakpoint_commands (b));
11824 }
11825
11826 do_cleanups (old_chain);
11827 }
11828
11829 static int
11830 remote_can_download_tracepoint (struct target_ops *self)
11831 {
11832 struct remote_state *rs = get_remote_state ();
11833 struct trace_status *ts;
11834 int status;
11835
11836 /* Don't try to install tracepoints until we've relocated our
11837 symbols, and fetched and merged the target's tracepoint list with
11838 ours. */
11839 if (rs->starting_up)
11840 return 0;
11841
11842 ts = current_trace_status ();
11843 status = remote_get_trace_status (self, ts);
11844
11845 if (status == -1 || !ts->running_known || !ts->running)
11846 return 0;
11847
11848 /* If we are in a tracing experiment, but remote stub doesn't support
11849 installing tracepoint in trace, we have to return. */
11850 if (!remote_supports_install_in_trace ())
11851 return 0;
11852
11853 return 1;
11854 }
11855
11856
11857 static void
11858 remote_download_trace_state_variable (struct target_ops *self,
11859 struct trace_state_variable *tsv)
11860 {
11861 struct remote_state *rs = get_remote_state ();
11862 char *p;
11863
11864 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11865 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11866 tsv->builtin);
11867 p = rs->buf + strlen (rs->buf);
11868 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11869 error (_("Trace state variable name too long for tsv definition packet"));
11870 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11871 *p++ = '\0';
11872 putpkt (rs->buf);
11873 remote_get_noisy_reply (&target_buf, &target_buf_size);
11874 if (*target_buf == '\0')
11875 error (_("Target does not support this command."));
11876 if (strcmp (target_buf, "OK") != 0)
11877 error (_("Error on target while downloading trace state variable."));
11878 }
11879
11880 static void
11881 remote_enable_tracepoint (struct target_ops *self,
11882 struct bp_location *location)
11883 {
11884 struct remote_state *rs = get_remote_state ();
11885 char addr_buf[40];
11886
11887 sprintf_vma (addr_buf, location->address);
11888 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11889 location->owner->number, addr_buf);
11890 putpkt (rs->buf);
11891 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11892 if (*rs->buf == '\0')
11893 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11894 if (strcmp (rs->buf, "OK") != 0)
11895 error (_("Error on target while enabling tracepoint."));
11896 }
11897
11898 static void
11899 remote_disable_tracepoint (struct target_ops *self,
11900 struct bp_location *location)
11901 {
11902 struct remote_state *rs = get_remote_state ();
11903 char addr_buf[40];
11904
11905 sprintf_vma (addr_buf, location->address);
11906 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11907 location->owner->number, addr_buf);
11908 putpkt (rs->buf);
11909 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11910 if (*rs->buf == '\0')
11911 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11912 if (strcmp (rs->buf, "OK") != 0)
11913 error (_("Error on target while disabling tracepoint."));
11914 }
11915
11916 static void
11917 remote_trace_set_readonly_regions (struct target_ops *self)
11918 {
11919 asection *s;
11920 bfd *abfd = NULL;
11921 bfd_size_type size;
11922 bfd_vma vma;
11923 int anysecs = 0;
11924 int offset = 0;
11925
11926 if (!exec_bfd)
11927 return; /* No information to give. */
11928
11929 strcpy (target_buf, "QTro");
11930 offset = strlen (target_buf);
11931 for (s = exec_bfd->sections; s; s = s->next)
11932 {
11933 char tmp1[40], tmp2[40];
11934 int sec_length;
11935
11936 if ((s->flags & SEC_LOAD) == 0 ||
11937 /* (s->flags & SEC_CODE) == 0 || */
11938 (s->flags & SEC_READONLY) == 0)
11939 continue;
11940
11941 anysecs = 1;
11942 vma = bfd_get_section_vma (abfd, s);
11943 size = bfd_get_section_size (s);
11944 sprintf_vma (tmp1, vma);
11945 sprintf_vma (tmp2, vma + size);
11946 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11947 if (offset + sec_length + 1 > target_buf_size)
11948 {
11949 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
11950 warning (_("\
11951 Too many sections for read-only sections definition packet."));
11952 break;
11953 }
11954 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11955 tmp1, tmp2);
11956 offset += sec_length;
11957 }
11958 if (anysecs)
11959 {
11960 putpkt (target_buf);
11961 getpkt (&target_buf, &target_buf_size, 0);
11962 }
11963 }
11964
11965 static void
11966 remote_trace_start (struct target_ops *self)
11967 {
11968 putpkt ("QTStart");
11969 remote_get_noisy_reply (&target_buf, &target_buf_size);
11970 if (*target_buf == '\0')
11971 error (_("Target does not support this command."));
11972 if (strcmp (target_buf, "OK") != 0)
11973 error (_("Bogus reply from target: %s"), target_buf);
11974 }
11975
11976 static int
11977 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11978 {
11979 /* Initialize it just to avoid a GCC false warning. */
11980 char *p = NULL;
11981 /* FIXME we need to get register block size some other way. */
11982 extern int trace_regblock_size;
11983 enum packet_result result;
11984
11985 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11986 return -1;
11987
11988 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11989
11990 putpkt ("qTStatus");
11991
11992 TRY
11993 {
11994 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11995 }
11996 CATCH (ex, RETURN_MASK_ERROR)
11997 {
11998 if (ex.error != TARGET_CLOSE_ERROR)
11999 {
12000 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12001 return -1;
12002 }
12003 throw_exception (ex);
12004 }
12005 END_CATCH
12006
12007 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12008
12009 /* If the remote target doesn't do tracing, flag it. */
12010 if (result == PACKET_UNKNOWN)
12011 return -1;
12012
12013 /* We're working with a live target. */
12014 ts->filename = NULL;
12015
12016 if (*p++ != 'T')
12017 error (_("Bogus trace status reply from target: %s"), target_buf);
12018
12019 /* Function 'parse_trace_status' sets default value of each field of
12020 'ts' at first, so we don't have to do it here. */
12021 parse_trace_status (p, ts);
12022
12023 return ts->running;
12024 }
12025
12026 static void
12027 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12028 struct uploaded_tp *utp)
12029 {
12030 struct remote_state *rs = get_remote_state ();
12031 char *reply;
12032 struct bp_location *loc;
12033 struct tracepoint *tp = (struct tracepoint *) bp;
12034 size_t size = get_remote_packet_size ();
12035
12036 if (tp)
12037 {
12038 tp->base.hit_count = 0;
12039 tp->traceframe_usage = 0;
12040 for (loc = tp->base.loc; loc; loc = loc->next)
12041 {
12042 /* If the tracepoint was never downloaded, don't go asking for
12043 any status. */
12044 if (tp->number_on_target == 0)
12045 continue;
12046 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12047 phex_nz (loc->address, 0));
12048 putpkt (rs->buf);
12049 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12050 if (reply && *reply)
12051 {
12052 if (*reply == 'V')
12053 parse_tracepoint_status (reply + 1, bp, utp);
12054 }
12055 }
12056 }
12057 else if (utp)
12058 {
12059 utp->hit_count = 0;
12060 utp->traceframe_usage = 0;
12061 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12062 phex_nz (utp->addr, 0));
12063 putpkt (rs->buf);
12064 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12065 if (reply && *reply)
12066 {
12067 if (*reply == 'V')
12068 parse_tracepoint_status (reply + 1, bp, utp);
12069 }
12070 }
12071 }
12072
12073 static void
12074 remote_trace_stop (struct target_ops *self)
12075 {
12076 putpkt ("QTStop");
12077 remote_get_noisy_reply (&target_buf, &target_buf_size);
12078 if (*target_buf == '\0')
12079 error (_("Target does not support this command."));
12080 if (strcmp (target_buf, "OK") != 0)
12081 error (_("Bogus reply from target: %s"), target_buf);
12082 }
12083
12084 static int
12085 remote_trace_find (struct target_ops *self,
12086 enum trace_find_type type, int num,
12087 CORE_ADDR addr1, CORE_ADDR addr2,
12088 int *tpp)
12089 {
12090 struct remote_state *rs = get_remote_state ();
12091 char *endbuf = rs->buf + get_remote_packet_size ();
12092 char *p, *reply;
12093 int target_frameno = -1, target_tracept = -1;
12094
12095 /* Lookups other than by absolute frame number depend on the current
12096 trace selected, so make sure it is correct on the remote end
12097 first. */
12098 if (type != tfind_number)
12099 set_remote_traceframe ();
12100
12101 p = rs->buf;
12102 strcpy (p, "QTFrame:");
12103 p = strchr (p, '\0');
12104 switch (type)
12105 {
12106 case tfind_number:
12107 xsnprintf (p, endbuf - p, "%x", num);
12108 break;
12109 case tfind_pc:
12110 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12111 break;
12112 case tfind_tp:
12113 xsnprintf (p, endbuf - p, "tdp:%x", num);
12114 break;
12115 case tfind_range:
12116 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12117 phex_nz (addr2, 0));
12118 break;
12119 case tfind_outside:
12120 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12121 phex_nz (addr2, 0));
12122 break;
12123 default:
12124 error (_("Unknown trace find type %d"), type);
12125 }
12126
12127 putpkt (rs->buf);
12128 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12129 if (*reply == '\0')
12130 error (_("Target does not support this command."));
12131
12132 while (reply && *reply)
12133 switch (*reply)
12134 {
12135 case 'F':
12136 p = ++reply;
12137 target_frameno = (int) strtol (p, &reply, 16);
12138 if (reply == p)
12139 error (_("Unable to parse trace frame number"));
12140 /* Don't update our remote traceframe number cache on failure
12141 to select a remote traceframe. */
12142 if (target_frameno == -1)
12143 return -1;
12144 break;
12145 case 'T':
12146 p = ++reply;
12147 target_tracept = (int) strtol (p, &reply, 16);
12148 if (reply == p)
12149 error (_("Unable to parse tracepoint number"));
12150 break;
12151 case 'O': /* "OK"? */
12152 if (reply[1] == 'K' && reply[2] == '\0')
12153 reply += 2;
12154 else
12155 error (_("Bogus reply from target: %s"), reply);
12156 break;
12157 default:
12158 error (_("Bogus reply from target: %s"), reply);
12159 }
12160 if (tpp)
12161 *tpp = target_tracept;
12162
12163 rs->remote_traceframe_number = target_frameno;
12164 return target_frameno;
12165 }
12166
12167 static int
12168 remote_get_trace_state_variable_value (struct target_ops *self,
12169 int tsvnum, LONGEST *val)
12170 {
12171 struct remote_state *rs = get_remote_state ();
12172 char *reply;
12173 ULONGEST uval;
12174
12175 set_remote_traceframe ();
12176
12177 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12178 putpkt (rs->buf);
12179 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12180 if (reply && *reply)
12181 {
12182 if (*reply == 'V')
12183 {
12184 unpack_varlen_hex (reply + 1, &uval);
12185 *val = (LONGEST) uval;
12186 return 1;
12187 }
12188 }
12189 return 0;
12190 }
12191
12192 static int
12193 remote_save_trace_data (struct target_ops *self, const char *filename)
12194 {
12195 struct remote_state *rs = get_remote_state ();
12196 char *p, *reply;
12197
12198 p = rs->buf;
12199 strcpy (p, "QTSave:");
12200 p += strlen (p);
12201 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12202 error (_("Remote file name too long for trace save packet"));
12203 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12204 *p++ = '\0';
12205 putpkt (rs->buf);
12206 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12207 if (*reply == '\0')
12208 error (_("Target does not support this command."));
12209 if (strcmp (reply, "OK") != 0)
12210 error (_("Bogus reply from target: %s"), reply);
12211 return 0;
12212 }
12213
12214 /* This is basically a memory transfer, but needs to be its own packet
12215 because we don't know how the target actually organizes its trace
12216 memory, plus we want to be able to ask for as much as possible, but
12217 not be unhappy if we don't get as much as we ask for. */
12218
12219 static LONGEST
12220 remote_get_raw_trace_data (struct target_ops *self,
12221 gdb_byte *buf, ULONGEST offset, LONGEST len)
12222 {
12223 struct remote_state *rs = get_remote_state ();
12224 char *reply;
12225 char *p;
12226 int rslt;
12227
12228 p = rs->buf;
12229 strcpy (p, "qTBuffer:");
12230 p += strlen (p);
12231 p += hexnumstr (p, offset);
12232 *p++ = ',';
12233 p += hexnumstr (p, len);
12234 *p++ = '\0';
12235
12236 putpkt (rs->buf);
12237 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12238 if (reply && *reply)
12239 {
12240 /* 'l' by itself means we're at the end of the buffer and
12241 there is nothing more to get. */
12242 if (*reply == 'l')
12243 return 0;
12244
12245 /* Convert the reply into binary. Limit the number of bytes to
12246 convert according to our passed-in buffer size, rather than
12247 what was returned in the packet; if the target is
12248 unexpectedly generous and gives us a bigger reply than we
12249 asked for, we don't want to crash. */
12250 rslt = hex2bin (target_buf, buf, len);
12251 return rslt;
12252 }
12253
12254 /* Something went wrong, flag as an error. */
12255 return -1;
12256 }
12257
12258 static void
12259 remote_set_disconnected_tracing (struct target_ops *self, int val)
12260 {
12261 struct remote_state *rs = get_remote_state ();
12262
12263 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12264 {
12265 char *reply;
12266
12267 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12268 putpkt (rs->buf);
12269 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12270 if (*reply == '\0')
12271 error (_("Target does not support this command."));
12272 if (strcmp (reply, "OK") != 0)
12273 error (_("Bogus reply from target: %s"), reply);
12274 }
12275 else if (val)
12276 warning (_("Target does not support disconnected tracing."));
12277 }
12278
12279 static int
12280 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12281 {
12282 struct thread_info *info = find_thread_ptid (ptid);
12283
12284 if (info && info->priv)
12285 return info->priv->core;
12286 return -1;
12287 }
12288
12289 static void
12290 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12291 {
12292 struct remote_state *rs = get_remote_state ();
12293 char *reply;
12294
12295 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12296 putpkt (rs->buf);
12297 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12298 if (*reply == '\0')
12299 error (_("Target does not support this command."));
12300 if (strcmp (reply, "OK") != 0)
12301 error (_("Bogus reply from target: %s"), reply);
12302 }
12303
12304 static struct traceframe_info *
12305 remote_traceframe_info (struct target_ops *self)
12306 {
12307 char *text;
12308
12309 text = target_read_stralloc (&current_target,
12310 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12311 if (text != NULL)
12312 {
12313 struct traceframe_info *info;
12314 struct cleanup *back_to = make_cleanup (xfree, text);
12315
12316 info = parse_traceframe_info (text);
12317 do_cleanups (back_to);
12318 return info;
12319 }
12320
12321 return NULL;
12322 }
12323
12324 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12325 instruction on which a fast tracepoint may be placed. Returns -1
12326 if the packet is not supported, and 0 if the minimum instruction
12327 length is unknown. */
12328
12329 static int
12330 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12331 {
12332 struct remote_state *rs = get_remote_state ();
12333 char *reply;
12334
12335 /* If we're not debugging a process yet, the IPA can't be
12336 loaded. */
12337 if (!target_has_execution)
12338 return 0;
12339
12340 /* Make sure the remote is pointing at the right process. */
12341 set_general_process ();
12342
12343 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12344 putpkt (rs->buf);
12345 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12346 if (*reply == '\0')
12347 return -1;
12348 else
12349 {
12350 ULONGEST min_insn_len;
12351
12352 unpack_varlen_hex (reply, &min_insn_len);
12353
12354 return (int) min_insn_len;
12355 }
12356 }
12357
12358 static void
12359 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12360 {
12361 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12362 {
12363 struct remote_state *rs = get_remote_state ();
12364 char *buf = rs->buf;
12365 char *endbuf = rs->buf + get_remote_packet_size ();
12366 enum packet_result result;
12367
12368 gdb_assert (val >= 0 || val == -1);
12369 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12370 /* Send -1 as literal "-1" to avoid host size dependency. */
12371 if (val < 0)
12372 {
12373 *buf++ = '-';
12374 buf += hexnumstr (buf, (ULONGEST) -val);
12375 }
12376 else
12377 buf += hexnumstr (buf, (ULONGEST) val);
12378
12379 putpkt (rs->buf);
12380 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12381 result = packet_ok (rs->buf,
12382 &remote_protocol_packets[PACKET_QTBuffer_size]);
12383
12384 if (result != PACKET_OK)
12385 warning (_("Bogus reply from target: %s"), rs->buf);
12386 }
12387 }
12388
12389 static int
12390 remote_set_trace_notes (struct target_ops *self,
12391 const char *user, const char *notes,
12392 const char *stop_notes)
12393 {
12394 struct remote_state *rs = get_remote_state ();
12395 char *reply;
12396 char *buf = rs->buf;
12397 char *endbuf = rs->buf + get_remote_packet_size ();
12398 int nbytes;
12399
12400 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12401 if (user)
12402 {
12403 buf += xsnprintf (buf, endbuf - buf, "user:");
12404 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12405 buf += 2 * nbytes;
12406 *buf++ = ';';
12407 }
12408 if (notes)
12409 {
12410 buf += xsnprintf (buf, endbuf - buf, "notes:");
12411 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12412 buf += 2 * nbytes;
12413 *buf++ = ';';
12414 }
12415 if (stop_notes)
12416 {
12417 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12418 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12419 buf += 2 * nbytes;
12420 *buf++ = ';';
12421 }
12422 /* Ensure the buffer is terminated. */
12423 *buf = '\0';
12424
12425 putpkt (rs->buf);
12426 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12427 if (*reply == '\0')
12428 return 0;
12429
12430 if (strcmp (reply, "OK") != 0)
12431 error (_("Bogus reply from target: %s"), reply);
12432
12433 return 1;
12434 }
12435
12436 static int
12437 remote_use_agent (struct target_ops *self, int use)
12438 {
12439 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12440 {
12441 struct remote_state *rs = get_remote_state ();
12442
12443 /* If the stub supports QAgent. */
12444 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12445 putpkt (rs->buf);
12446 getpkt (&rs->buf, &rs->buf_size, 0);
12447
12448 if (strcmp (rs->buf, "OK") == 0)
12449 {
12450 use_agent = use;
12451 return 1;
12452 }
12453 }
12454
12455 return 0;
12456 }
12457
12458 static int
12459 remote_can_use_agent (struct target_ops *self)
12460 {
12461 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12462 }
12463
12464 struct btrace_target_info
12465 {
12466 /* The ptid of the traced thread. */
12467 ptid_t ptid;
12468
12469 /* The obtained branch trace configuration. */
12470 struct btrace_config conf;
12471 };
12472
12473 /* Reset our idea of our target's btrace configuration. */
12474
12475 static void
12476 remote_btrace_reset (void)
12477 {
12478 struct remote_state *rs = get_remote_state ();
12479
12480 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12481 }
12482
12483 /* Check whether the target supports branch tracing. */
12484
12485 static int
12486 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12487 {
12488 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12489 return 0;
12490 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12491 return 0;
12492
12493 switch (format)
12494 {
12495 case BTRACE_FORMAT_NONE:
12496 return 0;
12497
12498 case BTRACE_FORMAT_BTS:
12499 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12500
12501 case BTRACE_FORMAT_PT:
12502 /* The trace is decoded on the host. Even if our target supports it,
12503 we still need to have libipt to decode the trace. */
12504 #if defined (HAVE_LIBIPT)
12505 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12506 #else /* !defined (HAVE_LIBIPT) */
12507 return 0;
12508 #endif /* !defined (HAVE_LIBIPT) */
12509 }
12510
12511 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12512 }
12513
12514 /* Synchronize the configuration with the target. */
12515
12516 static void
12517 btrace_sync_conf (const struct btrace_config *conf)
12518 {
12519 struct packet_config *packet;
12520 struct remote_state *rs;
12521 char *buf, *pos, *endbuf;
12522
12523 rs = get_remote_state ();
12524 buf = rs->buf;
12525 endbuf = buf + get_remote_packet_size ();
12526
12527 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12528 if (packet_config_support (packet) == PACKET_ENABLE
12529 && conf->bts.size != rs->btrace_config.bts.size)
12530 {
12531 pos = buf;
12532 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12533 conf->bts.size);
12534
12535 putpkt (buf);
12536 getpkt (&buf, &rs->buf_size, 0);
12537
12538 if (packet_ok (buf, packet) == PACKET_ERROR)
12539 {
12540 if (buf[0] == 'E' && buf[1] == '.')
12541 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12542 else
12543 error (_("Failed to configure the BTS buffer size."));
12544 }
12545
12546 rs->btrace_config.bts.size = conf->bts.size;
12547 }
12548
12549 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12550 if (packet_config_support (packet) == PACKET_ENABLE
12551 && conf->pt.size != rs->btrace_config.pt.size)
12552 {
12553 pos = buf;
12554 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12555 conf->pt.size);
12556
12557 putpkt (buf);
12558 getpkt (&buf, &rs->buf_size, 0);
12559
12560 if (packet_ok (buf, packet) == PACKET_ERROR)
12561 {
12562 if (buf[0] == 'E' && buf[1] == '.')
12563 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12564 else
12565 error (_("Failed to configure the trace buffer size."));
12566 }
12567
12568 rs->btrace_config.pt.size = conf->pt.size;
12569 }
12570 }
12571
12572 /* Read the current thread's btrace configuration from the target and
12573 store it into CONF. */
12574
12575 static void
12576 btrace_read_config (struct btrace_config *conf)
12577 {
12578 char *xml;
12579
12580 xml = target_read_stralloc (&current_target,
12581 TARGET_OBJECT_BTRACE_CONF, "");
12582 if (xml != NULL)
12583 {
12584 struct cleanup *cleanup;
12585
12586 cleanup = make_cleanup (xfree, xml);
12587 parse_xml_btrace_conf (conf, xml);
12588 do_cleanups (cleanup);
12589 }
12590 }
12591
12592 /* Enable branch tracing. */
12593
12594 static struct btrace_target_info *
12595 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12596 const struct btrace_config *conf)
12597 {
12598 struct btrace_target_info *tinfo = NULL;
12599 struct packet_config *packet = NULL;
12600 struct remote_state *rs = get_remote_state ();
12601 char *buf = rs->buf;
12602 char *endbuf = rs->buf + get_remote_packet_size ();
12603
12604 switch (conf->format)
12605 {
12606 case BTRACE_FORMAT_BTS:
12607 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12608 break;
12609
12610 case BTRACE_FORMAT_PT:
12611 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12612 break;
12613 }
12614
12615 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12616 error (_("Target does not support branch tracing."));
12617
12618 btrace_sync_conf (conf);
12619
12620 set_general_thread (ptid);
12621
12622 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12623 putpkt (rs->buf);
12624 getpkt (&rs->buf, &rs->buf_size, 0);
12625
12626 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12627 {
12628 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12629 error (_("Could not enable branch tracing for %s: %s"),
12630 target_pid_to_str (ptid), rs->buf + 2);
12631 else
12632 error (_("Could not enable branch tracing for %s."),
12633 target_pid_to_str (ptid));
12634 }
12635
12636 tinfo = XCNEW (struct btrace_target_info);
12637 tinfo->ptid = ptid;
12638
12639 /* If we fail to read the configuration, we lose some information, but the
12640 tracing itself is not impacted. */
12641 TRY
12642 {
12643 btrace_read_config (&tinfo->conf);
12644 }
12645 CATCH (err, RETURN_MASK_ERROR)
12646 {
12647 if (err.message != NULL)
12648 warning ("%s", err.message);
12649 }
12650 END_CATCH
12651
12652 return tinfo;
12653 }
12654
12655 /* Disable branch tracing. */
12656
12657 static void
12658 remote_disable_btrace (struct target_ops *self,
12659 struct btrace_target_info *tinfo)
12660 {
12661 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12662 struct remote_state *rs = get_remote_state ();
12663 char *buf = rs->buf;
12664 char *endbuf = rs->buf + get_remote_packet_size ();
12665
12666 if (packet_config_support (packet) != PACKET_ENABLE)
12667 error (_("Target does not support branch tracing."));
12668
12669 set_general_thread (tinfo->ptid);
12670
12671 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12672 putpkt (rs->buf);
12673 getpkt (&rs->buf, &rs->buf_size, 0);
12674
12675 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12676 {
12677 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12678 error (_("Could not disable branch tracing for %s: %s"),
12679 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12680 else
12681 error (_("Could not disable branch tracing for %s."),
12682 target_pid_to_str (tinfo->ptid));
12683 }
12684
12685 xfree (tinfo);
12686 }
12687
12688 /* Teardown branch tracing. */
12689
12690 static void
12691 remote_teardown_btrace (struct target_ops *self,
12692 struct btrace_target_info *tinfo)
12693 {
12694 /* We must not talk to the target during teardown. */
12695 xfree (tinfo);
12696 }
12697
12698 /* Read the branch trace. */
12699
12700 static enum btrace_error
12701 remote_read_btrace (struct target_ops *self,
12702 struct btrace_data *btrace,
12703 struct btrace_target_info *tinfo,
12704 enum btrace_read_type type)
12705 {
12706 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12707 struct remote_state *rs = get_remote_state ();
12708 struct cleanup *cleanup;
12709 const char *annex;
12710 char *xml;
12711
12712 if (packet_config_support (packet) != PACKET_ENABLE)
12713 error (_("Target does not support branch tracing."));
12714
12715 #if !defined(HAVE_LIBEXPAT)
12716 error (_("Cannot process branch tracing result. XML parsing not supported."));
12717 #endif
12718
12719 switch (type)
12720 {
12721 case BTRACE_READ_ALL:
12722 annex = "all";
12723 break;
12724 case BTRACE_READ_NEW:
12725 annex = "new";
12726 break;
12727 case BTRACE_READ_DELTA:
12728 annex = "delta";
12729 break;
12730 default:
12731 internal_error (__FILE__, __LINE__,
12732 _("Bad branch tracing read type: %u."),
12733 (unsigned int) type);
12734 }
12735
12736 xml = target_read_stralloc (&current_target,
12737 TARGET_OBJECT_BTRACE, annex);
12738 if (xml == NULL)
12739 return BTRACE_ERR_UNKNOWN;
12740
12741 cleanup = make_cleanup (xfree, xml);
12742 parse_xml_btrace (btrace, xml);
12743 do_cleanups (cleanup);
12744
12745 return BTRACE_ERR_NONE;
12746 }
12747
12748 static const struct btrace_config *
12749 remote_btrace_conf (struct target_ops *self,
12750 const struct btrace_target_info *tinfo)
12751 {
12752 return &tinfo->conf;
12753 }
12754
12755 static int
12756 remote_augmented_libraries_svr4_read (struct target_ops *self)
12757 {
12758 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12759 == PACKET_ENABLE);
12760 }
12761
12762 /* Implementation of to_load. */
12763
12764 static void
12765 remote_load (struct target_ops *self, const char *name, int from_tty)
12766 {
12767 generic_load (name, from_tty);
12768 }
12769
12770 /* Accepts an integer PID; returns a string representing a file that
12771 can be opened on the remote side to get the symbols for the child
12772 process. Returns NULL if the operation is not supported. */
12773
12774 static char *
12775 remote_pid_to_exec_file (struct target_ops *self, int pid)
12776 {
12777 static char *filename = NULL;
12778 struct inferior *inf;
12779 char *annex = NULL;
12780
12781 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12782 return NULL;
12783
12784 if (filename != NULL)
12785 xfree (filename);
12786
12787 inf = find_inferior_pid (pid);
12788 if (inf == NULL)
12789 internal_error (__FILE__, __LINE__,
12790 _("not currently attached to process %d"), pid);
12791
12792 if (!inf->fake_pid_p)
12793 {
12794 const int annex_size = 9;
12795
12796 annex = (char *) alloca (annex_size);
12797 xsnprintf (annex, annex_size, "%x", pid);
12798 }
12799
12800 filename = target_read_stralloc (&current_target,
12801 TARGET_OBJECT_EXEC_FILE, annex);
12802
12803 return filename;
12804 }
12805
12806 /* Implement the to_can_do_single_step target_ops method. */
12807
12808 static int
12809 remote_can_do_single_step (struct target_ops *ops)
12810 {
12811 /* We can only tell whether target supports single step or not by
12812 supported s and S vCont actions if the stub supports vContSupported
12813 feature. If the stub doesn't support vContSupported feature,
12814 we have conservatively to think target doesn't supports single
12815 step. */
12816 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12817 {
12818 struct remote_state *rs = get_remote_state ();
12819
12820 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12821 remote_vcont_probe (rs);
12822
12823 return rs->supports_vCont.s && rs->supports_vCont.S;
12824 }
12825 else
12826 return 0;
12827 }
12828
12829 static void
12830 init_remote_ops (void)
12831 {
12832 remote_ops.to_shortname = "remote";
12833 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12834 remote_ops.to_doc =
12835 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12836 Specify the serial device it is connected to\n\
12837 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12838 remote_ops.to_open = remote_open;
12839 remote_ops.to_close = remote_close;
12840 remote_ops.to_detach = remote_detach;
12841 remote_ops.to_disconnect = remote_disconnect;
12842 remote_ops.to_resume = remote_resume;
12843 remote_ops.to_wait = remote_wait;
12844 remote_ops.to_fetch_registers = remote_fetch_registers;
12845 remote_ops.to_store_registers = remote_store_registers;
12846 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12847 remote_ops.to_files_info = remote_files_info;
12848 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12849 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12850 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12851 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12852 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12853 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12854 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12855 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12856 remote_ops.to_watchpoint_addr_within_range =
12857 remote_watchpoint_addr_within_range;
12858 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12859 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12860 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12861 remote_ops.to_region_ok_for_hw_watchpoint
12862 = remote_region_ok_for_hw_watchpoint;
12863 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12864 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12865 remote_ops.to_kill = remote_kill;
12866 remote_ops.to_load = remote_load;
12867 remote_ops.to_mourn_inferior = remote_mourn;
12868 remote_ops.to_pass_signals = remote_pass_signals;
12869 remote_ops.to_program_signals = remote_program_signals;
12870 remote_ops.to_thread_alive = remote_thread_alive;
12871 remote_ops.to_thread_name = remote_thread_name;
12872 remote_ops.to_update_thread_list = remote_update_thread_list;
12873 remote_ops.to_pid_to_str = remote_pid_to_str;
12874 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12875 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12876 remote_ops.to_stop = remote_stop;
12877 remote_ops.to_interrupt = remote_interrupt;
12878 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12879 remote_ops.to_xfer_partial = remote_xfer_partial;
12880 remote_ops.to_rcmd = remote_rcmd;
12881 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12882 remote_ops.to_log_command = serial_log_command;
12883 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12884 remote_ops.to_stratum = process_stratum;
12885 remote_ops.to_has_all_memory = default_child_has_all_memory;
12886 remote_ops.to_has_memory = default_child_has_memory;
12887 remote_ops.to_has_stack = default_child_has_stack;
12888 remote_ops.to_has_registers = default_child_has_registers;
12889 remote_ops.to_has_execution = default_child_has_execution;
12890 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12891 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12892 remote_ops.to_magic = OPS_MAGIC;
12893 remote_ops.to_memory_map = remote_memory_map;
12894 remote_ops.to_flash_erase = remote_flash_erase;
12895 remote_ops.to_flash_done = remote_flash_done;
12896 remote_ops.to_read_description = remote_read_description;
12897 remote_ops.to_search_memory = remote_search_memory;
12898 remote_ops.to_can_async_p = remote_can_async_p;
12899 remote_ops.to_is_async_p = remote_is_async_p;
12900 remote_ops.to_async = remote_async;
12901 remote_ops.to_can_do_single_step = remote_can_do_single_step;
12902 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12903 remote_ops.to_terminal_ours = remote_terminal_ours;
12904 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12905 remote_ops.to_supports_multi_process = remote_supports_multi_process;
12906 remote_ops.to_supports_disable_randomization
12907 = remote_supports_disable_randomization;
12908 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12909 remote_ops.to_fileio_open = remote_hostio_open;
12910 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12911 remote_ops.to_fileio_pread = remote_hostio_pread;
12912 remote_ops.to_fileio_fstat = remote_hostio_fstat;
12913 remote_ops.to_fileio_close = remote_hostio_close;
12914 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12915 remote_ops.to_fileio_readlink = remote_hostio_readlink;
12916 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12917 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12918 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12919 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12920 remote_ops.to_trace_init = remote_trace_init;
12921 remote_ops.to_download_tracepoint = remote_download_tracepoint;
12922 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12923 remote_ops.to_download_trace_state_variable
12924 = remote_download_trace_state_variable;
12925 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12926 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12927 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12928 remote_ops.to_trace_start = remote_trace_start;
12929 remote_ops.to_get_trace_status = remote_get_trace_status;
12930 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12931 remote_ops.to_trace_stop = remote_trace_stop;
12932 remote_ops.to_trace_find = remote_trace_find;
12933 remote_ops.to_get_trace_state_variable_value
12934 = remote_get_trace_state_variable_value;
12935 remote_ops.to_save_trace_data = remote_save_trace_data;
12936 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
12937 remote_ops.to_upload_trace_state_variables
12938 = remote_upload_trace_state_variables;
12939 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
12940 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
12941 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12942 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
12943 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
12944 remote_ops.to_set_trace_notes = remote_set_trace_notes;
12945 remote_ops.to_core_of_thread = remote_core_of_thread;
12946 remote_ops.to_verify_memory = remote_verify_memory;
12947 remote_ops.to_get_tib_address = remote_get_tib_address;
12948 remote_ops.to_set_permissions = remote_set_permissions;
12949 remote_ops.to_static_tracepoint_marker_at
12950 = remote_static_tracepoint_marker_at;
12951 remote_ops.to_static_tracepoint_markers_by_strid
12952 = remote_static_tracepoint_markers_by_strid;
12953 remote_ops.to_traceframe_info = remote_traceframe_info;
12954 remote_ops.to_use_agent = remote_use_agent;
12955 remote_ops.to_can_use_agent = remote_can_use_agent;
12956 remote_ops.to_supports_btrace = remote_supports_btrace;
12957 remote_ops.to_enable_btrace = remote_enable_btrace;
12958 remote_ops.to_disable_btrace = remote_disable_btrace;
12959 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12960 remote_ops.to_read_btrace = remote_read_btrace;
12961 remote_ops.to_btrace_conf = remote_btrace_conf;
12962 remote_ops.to_augmented_libraries_svr4_read =
12963 remote_augmented_libraries_svr4_read;
12964 }
12965
12966 /* Set up the extended remote vector by making a copy of the standard
12967 remote vector and adding to it. */
12968
12969 static void
12970 init_extended_remote_ops (void)
12971 {
12972 extended_remote_ops = remote_ops;
12973
12974 extended_remote_ops.to_shortname = "extended-remote";
12975 extended_remote_ops.to_longname =
12976 "Extended remote serial target in gdb-specific protocol";
12977 extended_remote_ops.to_doc =
12978 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12979 Specify the serial device it is connected to (e.g. /dev/ttya).";
12980 extended_remote_ops.to_open = extended_remote_open;
12981 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12982 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
12983 extended_remote_ops.to_detach = extended_remote_detach;
12984 extended_remote_ops.to_attach = extended_remote_attach;
12985 extended_remote_ops.to_post_attach = extended_remote_post_attach;
12986 extended_remote_ops.to_kill = extended_remote_kill;
12987 extended_remote_ops.to_supports_disable_randomization
12988 = extended_remote_supports_disable_randomization;
12989 extended_remote_ops.to_follow_fork = remote_follow_fork;
12990 extended_remote_ops.to_follow_exec = remote_follow_exec;
12991 extended_remote_ops.to_insert_fork_catchpoint
12992 = remote_insert_fork_catchpoint;
12993 extended_remote_ops.to_remove_fork_catchpoint
12994 = remote_remove_fork_catchpoint;
12995 extended_remote_ops.to_insert_vfork_catchpoint
12996 = remote_insert_vfork_catchpoint;
12997 extended_remote_ops.to_remove_vfork_catchpoint
12998 = remote_remove_vfork_catchpoint;
12999 extended_remote_ops.to_insert_exec_catchpoint
13000 = remote_insert_exec_catchpoint;
13001 extended_remote_ops.to_remove_exec_catchpoint
13002 = remote_remove_exec_catchpoint;
13003 }
13004
13005 static int
13006 remote_can_async_p (struct target_ops *ops)
13007 {
13008 struct remote_state *rs = get_remote_state ();
13009
13010 if (!target_async_permitted)
13011 /* We only enable async when the user specifically asks for it. */
13012 return 0;
13013
13014 /* We're async whenever the serial device is. */
13015 return serial_can_async_p (rs->remote_desc);
13016 }
13017
13018 static int
13019 remote_is_async_p (struct target_ops *ops)
13020 {
13021 struct remote_state *rs = get_remote_state ();
13022
13023 if (!target_async_permitted)
13024 /* We only enable async when the user specifically asks for it. */
13025 return 0;
13026
13027 /* We're async whenever the serial device is. */
13028 return serial_is_async_p (rs->remote_desc);
13029 }
13030
13031 /* Pass the SERIAL event on and up to the client. One day this code
13032 will be able to delay notifying the client of an event until the
13033 point where an entire packet has been received. */
13034
13035 static serial_event_ftype remote_async_serial_handler;
13036
13037 static void
13038 remote_async_serial_handler (struct serial *scb, void *context)
13039 {
13040 struct remote_state *rs = (struct remote_state *) context;
13041
13042 /* Don't propogate error information up to the client. Instead let
13043 the client find out about the error by querying the target. */
13044 inferior_event_handler (INF_REG_EVENT, NULL);
13045 }
13046
13047 static void
13048 remote_async_inferior_event_handler (gdb_client_data data)
13049 {
13050 inferior_event_handler (INF_REG_EVENT, NULL);
13051 }
13052
13053 static void
13054 remote_async (struct target_ops *ops, int enable)
13055 {
13056 struct remote_state *rs = get_remote_state ();
13057
13058 if (enable)
13059 {
13060 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13061
13062 /* If there are pending events in the stop reply queue tell the
13063 event loop to process them. */
13064 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13065 mark_async_event_handler (remote_async_inferior_event_token);
13066 /* For simplicity, below we clear the pending events token
13067 without remembering whether it is marked, so here we always
13068 mark it. If there's actually no pending notification to
13069 process, this ends up being a no-op (other than a spurious
13070 event-loop wakeup). */
13071 if (target_is_non_stop_p ())
13072 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13073 }
13074 else
13075 {
13076 serial_async (rs->remote_desc, NULL, NULL);
13077 /* If the core is disabling async, it doesn't want to be
13078 disturbed with target events. Clear all async event sources
13079 too. */
13080 clear_async_event_handler (remote_async_inferior_event_token);
13081 if (target_is_non_stop_p ())
13082 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13083 }
13084 }
13085
13086 static void
13087 set_remote_cmd (char *args, int from_tty)
13088 {
13089 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13090 }
13091
13092 static void
13093 show_remote_cmd (char *args, int from_tty)
13094 {
13095 /* We can't just use cmd_show_list here, because we want to skip
13096 the redundant "show remote Z-packet" and the legacy aliases. */
13097 struct cleanup *showlist_chain;
13098 struct cmd_list_element *list = remote_show_cmdlist;
13099 struct ui_out *uiout = current_uiout;
13100
13101 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13102 for (; list != NULL; list = list->next)
13103 if (strcmp (list->name, "Z-packet") == 0)
13104 continue;
13105 else if (list->type == not_set_cmd)
13106 /* Alias commands are exactly like the original, except they
13107 don't have the normal type. */
13108 continue;
13109 else
13110 {
13111 struct cleanup *option_chain
13112 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13113
13114 ui_out_field_string (uiout, "name", list->name);
13115 ui_out_text (uiout, ": ");
13116 if (list->type == show_cmd)
13117 do_show_command ((char *) NULL, from_tty, list);
13118 else
13119 cmd_func (list, NULL, from_tty);
13120 /* Close the tuple. */
13121 do_cleanups (option_chain);
13122 }
13123
13124 /* Close the tuple. */
13125 do_cleanups (showlist_chain);
13126 }
13127
13128
13129 /* Function to be called whenever a new objfile (shlib) is detected. */
13130 static void
13131 remote_new_objfile (struct objfile *objfile)
13132 {
13133 struct remote_state *rs = get_remote_state ();
13134
13135 if (rs->remote_desc != 0) /* Have a remote connection. */
13136 remote_check_symbols ();
13137 }
13138
13139 /* Pull all the tracepoints defined on the target and create local
13140 data structures representing them. We don't want to create real
13141 tracepoints yet, we don't want to mess up the user's existing
13142 collection. */
13143
13144 static int
13145 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13146 {
13147 struct remote_state *rs = get_remote_state ();
13148 char *p;
13149
13150 /* Ask for a first packet of tracepoint definition. */
13151 putpkt ("qTfP");
13152 getpkt (&rs->buf, &rs->buf_size, 0);
13153 p = rs->buf;
13154 while (*p && *p != 'l')
13155 {
13156 parse_tracepoint_definition (p, utpp);
13157 /* Ask for another packet of tracepoint definition. */
13158 putpkt ("qTsP");
13159 getpkt (&rs->buf, &rs->buf_size, 0);
13160 p = rs->buf;
13161 }
13162 return 0;
13163 }
13164
13165 static int
13166 remote_upload_trace_state_variables (struct target_ops *self,
13167 struct uploaded_tsv **utsvp)
13168 {
13169 struct remote_state *rs = get_remote_state ();
13170 char *p;
13171
13172 /* Ask for a first packet of variable definition. */
13173 putpkt ("qTfV");
13174 getpkt (&rs->buf, &rs->buf_size, 0);
13175 p = rs->buf;
13176 while (*p && *p != 'l')
13177 {
13178 parse_tsv_definition (p, utsvp);
13179 /* Ask for another packet of variable definition. */
13180 putpkt ("qTsV");
13181 getpkt (&rs->buf, &rs->buf_size, 0);
13182 p = rs->buf;
13183 }
13184 return 0;
13185 }
13186
13187 /* The "set/show range-stepping" show hook. */
13188
13189 static void
13190 show_range_stepping (struct ui_file *file, int from_tty,
13191 struct cmd_list_element *c,
13192 const char *value)
13193 {
13194 fprintf_filtered (file,
13195 _("Debugger's willingness to use range stepping "
13196 "is %s.\n"), value);
13197 }
13198
13199 /* The "set/show range-stepping" set hook. */
13200
13201 static void
13202 set_range_stepping (char *ignore_args, int from_tty,
13203 struct cmd_list_element *c)
13204 {
13205 struct remote_state *rs = get_remote_state ();
13206
13207 /* Whene enabling, check whether range stepping is actually
13208 supported by the target, and warn if not. */
13209 if (use_range_stepping)
13210 {
13211 if (rs->remote_desc != NULL)
13212 {
13213 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13214 remote_vcont_probe (rs);
13215
13216 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13217 && rs->supports_vCont.r)
13218 return;
13219 }
13220
13221 warning (_("Range stepping is not supported by the current target"));
13222 }
13223 }
13224
13225 void
13226 _initialize_remote (void)
13227 {
13228 struct remote_state *rs;
13229 struct cmd_list_element *cmd;
13230 const char *cmd_name;
13231
13232 /* architecture specific data */
13233 remote_gdbarch_data_handle =
13234 gdbarch_data_register_post_init (init_remote_state);
13235 remote_g_packet_data_handle =
13236 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13237
13238 remote_pspace_data
13239 = register_program_space_data_with_cleanup (NULL,
13240 remote_pspace_data_cleanup);
13241
13242 /* Initialize the per-target state. At the moment there is only one
13243 of these, not one per target. Only one target is active at a
13244 time. */
13245 remote_state = new_remote_state ();
13246
13247 init_remote_ops ();
13248 add_target (&remote_ops);
13249
13250 init_extended_remote_ops ();
13251 add_target (&extended_remote_ops);
13252
13253 /* Hook into new objfile notification. */
13254 observer_attach_new_objfile (remote_new_objfile);
13255 /* We're no longer interested in notification events of an inferior
13256 when it exits. */
13257 observer_attach_inferior_exit (discard_pending_stop_replies);
13258
13259 /* Set up signal handlers. */
13260 async_sigint_remote_token =
13261 create_async_signal_handler (async_remote_interrupt, NULL);
13262 async_sigint_remote_twice_token =
13263 create_async_signal_handler (async_remote_interrupt_twice, NULL);
13264
13265 #if 0
13266 init_remote_threadtests ();
13267 #endif
13268
13269 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13270 /* set/show remote ... */
13271
13272 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13273 Remote protocol specific variables\n\
13274 Configure various remote-protocol specific variables such as\n\
13275 the packets being used"),
13276 &remote_set_cmdlist, "set remote ",
13277 0 /* allow-unknown */, &setlist);
13278 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13279 Remote protocol specific variables\n\
13280 Configure various remote-protocol specific variables such as\n\
13281 the packets being used"),
13282 &remote_show_cmdlist, "show remote ",
13283 0 /* allow-unknown */, &showlist);
13284
13285 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13286 Compare section data on target to the exec file.\n\
13287 Argument is a single section name (default: all loaded sections).\n\
13288 To compare only read-only loaded sections, specify the -r option."),
13289 &cmdlist);
13290
13291 add_cmd ("packet", class_maintenance, packet_command, _("\
13292 Send an arbitrary packet to a remote target.\n\
13293 maintenance packet TEXT\n\
13294 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13295 this command sends the string TEXT to the inferior, and displays the\n\
13296 response packet. GDB supplies the initial `$' character, and the\n\
13297 terminating `#' character and checksum."),
13298 &maintenancelist);
13299
13300 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13301 Set whether to send break if interrupted."), _("\
13302 Show whether to send break if interrupted."), _("\
13303 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13304 set_remotebreak, show_remotebreak,
13305 &setlist, &showlist);
13306 cmd_name = "remotebreak";
13307 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13308 deprecate_cmd (cmd, "set remote interrupt-sequence");
13309 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13310 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13311 deprecate_cmd (cmd, "show remote interrupt-sequence");
13312
13313 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13314 interrupt_sequence_modes, &interrupt_sequence_mode,
13315 _("\
13316 Set interrupt sequence to remote target."), _("\
13317 Show interrupt sequence to remote target."), _("\
13318 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13319 NULL, show_interrupt_sequence,
13320 &remote_set_cmdlist,
13321 &remote_show_cmdlist);
13322
13323 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13324 &interrupt_on_connect, _("\
13325 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13326 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13327 If set, interrupt sequence is sent to remote target."),
13328 NULL, NULL,
13329 &remote_set_cmdlist, &remote_show_cmdlist);
13330
13331 /* Install commands for configuring memory read/write packets. */
13332
13333 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13334 Set the maximum number of bytes per memory write packet (deprecated)."),
13335 &setlist);
13336 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13337 Show the maximum number of bytes per memory write packet (deprecated)."),
13338 &showlist);
13339 add_cmd ("memory-write-packet-size", no_class,
13340 set_memory_write_packet_size, _("\
13341 Set the maximum number of bytes per memory-write packet.\n\
13342 Specify the number of bytes in a packet or 0 (zero) for the\n\
13343 default packet size. The actual limit is further reduced\n\
13344 dependent on the target. Specify ``fixed'' to disable the\n\
13345 further restriction and ``limit'' to enable that restriction."),
13346 &remote_set_cmdlist);
13347 add_cmd ("memory-read-packet-size", no_class,
13348 set_memory_read_packet_size, _("\
13349 Set the maximum number of bytes per memory-read packet.\n\
13350 Specify the number of bytes in a packet or 0 (zero) for the\n\
13351 default packet size. The actual limit is further reduced\n\
13352 dependent on the target. Specify ``fixed'' to disable the\n\
13353 further restriction and ``limit'' to enable that restriction."),
13354 &remote_set_cmdlist);
13355 add_cmd ("memory-write-packet-size", no_class,
13356 show_memory_write_packet_size,
13357 _("Show the maximum number of bytes per memory-write packet."),
13358 &remote_show_cmdlist);
13359 add_cmd ("memory-read-packet-size", no_class,
13360 show_memory_read_packet_size,
13361 _("Show the maximum number of bytes per memory-read packet."),
13362 &remote_show_cmdlist);
13363
13364 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13365 &remote_hw_watchpoint_limit, _("\
13366 Set the maximum number of target hardware watchpoints."), _("\
13367 Show the maximum number of target hardware watchpoints."), _("\
13368 Specify a negative limit for unlimited."),
13369 NULL, NULL, /* FIXME: i18n: The maximum
13370 number of target hardware
13371 watchpoints is %s. */
13372 &remote_set_cmdlist, &remote_show_cmdlist);
13373 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13374 &remote_hw_watchpoint_length_limit, _("\
13375 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13376 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13377 Specify a negative limit for unlimited."),
13378 NULL, NULL, /* FIXME: i18n: The maximum
13379 length (in bytes) of a target
13380 hardware watchpoint is %s. */
13381 &remote_set_cmdlist, &remote_show_cmdlist);
13382 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13383 &remote_hw_breakpoint_limit, _("\
13384 Set the maximum number of target hardware breakpoints."), _("\
13385 Show the maximum number of target hardware breakpoints."), _("\
13386 Specify a negative limit for unlimited."),
13387 NULL, NULL, /* FIXME: i18n: The maximum
13388 number of target hardware
13389 breakpoints is %s. */
13390 &remote_set_cmdlist, &remote_show_cmdlist);
13391
13392 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13393 &remote_address_size, _("\
13394 Set the maximum size of the address (in bits) in a memory packet."), _("\
13395 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13396 NULL,
13397 NULL, /* FIXME: i18n: */
13398 &setlist, &showlist);
13399
13400 init_all_packet_configs ();
13401
13402 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13403 "X", "binary-download", 1);
13404
13405 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13406 "vCont", "verbose-resume", 0);
13407
13408 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13409 "QPassSignals", "pass-signals", 0);
13410
13411 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13412 "QProgramSignals", "program-signals", 0);
13413
13414 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13415 "qSymbol", "symbol-lookup", 0);
13416
13417 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13418 "P", "set-register", 1);
13419
13420 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13421 "p", "fetch-register", 1);
13422
13423 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13424 "Z0", "software-breakpoint", 0);
13425
13426 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13427 "Z1", "hardware-breakpoint", 0);
13428
13429 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13430 "Z2", "write-watchpoint", 0);
13431
13432 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13433 "Z3", "read-watchpoint", 0);
13434
13435 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13436 "Z4", "access-watchpoint", 0);
13437
13438 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13439 "qXfer:auxv:read", "read-aux-vector", 0);
13440
13441 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13442 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13443
13444 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13445 "qXfer:features:read", "target-features", 0);
13446
13447 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13448 "qXfer:libraries:read", "library-info", 0);
13449
13450 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13451 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13452
13453 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13454 "qXfer:memory-map:read", "memory-map", 0);
13455
13456 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13457 "qXfer:spu:read", "read-spu-object", 0);
13458
13459 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13460 "qXfer:spu:write", "write-spu-object", 0);
13461
13462 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13463 "qXfer:osdata:read", "osdata", 0);
13464
13465 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13466 "qXfer:threads:read", "threads", 0);
13467
13468 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13469 "qXfer:siginfo:read", "read-siginfo-object", 0);
13470
13471 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13472 "qXfer:siginfo:write", "write-siginfo-object", 0);
13473
13474 add_packet_config_cmd
13475 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13476 "qXfer:traceframe-info:read", "traceframe-info", 0);
13477
13478 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13479 "qXfer:uib:read", "unwind-info-block", 0);
13480
13481 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13482 "qGetTLSAddr", "get-thread-local-storage-address",
13483 0);
13484
13485 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13486 "qGetTIBAddr", "get-thread-information-block-address",
13487 0);
13488
13489 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13490 "bc", "reverse-continue", 0);
13491
13492 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13493 "bs", "reverse-step", 0);
13494
13495 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13496 "qSupported", "supported-packets", 0);
13497
13498 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13499 "qSearch:memory", "search-memory", 0);
13500
13501 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13502 "qTStatus", "trace-status", 0);
13503
13504 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13505 "vFile:setfs", "hostio-setfs", 0);
13506
13507 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13508 "vFile:open", "hostio-open", 0);
13509
13510 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13511 "vFile:pread", "hostio-pread", 0);
13512
13513 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13514 "vFile:pwrite", "hostio-pwrite", 0);
13515
13516 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13517 "vFile:close", "hostio-close", 0);
13518
13519 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13520 "vFile:unlink", "hostio-unlink", 0);
13521
13522 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13523 "vFile:readlink", "hostio-readlink", 0);
13524
13525 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13526 "vFile:fstat", "hostio-fstat", 0);
13527
13528 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13529 "vAttach", "attach", 0);
13530
13531 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13532 "vRun", "run", 0);
13533
13534 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13535 "QStartNoAckMode", "noack", 0);
13536
13537 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13538 "vKill", "kill", 0);
13539
13540 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13541 "qAttached", "query-attached", 0);
13542
13543 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13544 "ConditionalTracepoints",
13545 "conditional-tracepoints", 0);
13546
13547 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13548 "ConditionalBreakpoints",
13549 "conditional-breakpoints", 0);
13550
13551 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13552 "BreakpointCommands",
13553 "breakpoint-commands", 0);
13554
13555 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13556 "FastTracepoints", "fast-tracepoints", 0);
13557
13558 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13559 "TracepointSource", "TracepointSource", 0);
13560
13561 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13562 "QAllow", "allow", 0);
13563
13564 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13565 "StaticTracepoints", "static-tracepoints", 0);
13566
13567 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13568 "InstallInTrace", "install-in-trace", 0);
13569
13570 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13571 "qXfer:statictrace:read", "read-sdata-object", 0);
13572
13573 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13574 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13575
13576 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13577 "QDisableRandomization", "disable-randomization", 0);
13578
13579 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13580 "QAgent", "agent", 0);
13581
13582 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13583 "QTBuffer:size", "trace-buffer-size", 0);
13584
13585 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13586 "Qbtrace:off", "disable-btrace", 0);
13587
13588 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13589 "Qbtrace:bts", "enable-btrace-bts", 0);
13590
13591 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13592 "Qbtrace:pt", "enable-btrace-pt", 0);
13593
13594 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13595 "qXfer:btrace", "read-btrace", 0);
13596
13597 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13598 "qXfer:btrace-conf", "read-btrace-conf", 0);
13599
13600 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13601 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13602
13603 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13604 "multiprocess-feature", "multiprocess-feature", 0);
13605
13606 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13607 "swbreak-feature", "swbreak-feature", 0);
13608
13609 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13610 "hwbreak-feature", "hwbreak-feature", 0);
13611
13612 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13613 "fork-event-feature", "fork-event-feature", 0);
13614
13615 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13616 "vfork-event-feature", "vfork-event-feature", 0);
13617
13618 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13619 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13620
13621 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13622 "vContSupported", "verbose-resume-supported", 0);
13623
13624 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13625 "exec-event-feature", "exec-event-feature", 0);
13626
13627 /* Assert that we've registered "set remote foo-packet" commands
13628 for all packet configs. */
13629 {
13630 int i;
13631
13632 for (i = 0; i < PACKET_MAX; i++)
13633 {
13634 /* Ideally all configs would have a command associated. Some
13635 still don't though. */
13636 int excepted;
13637
13638 switch (i)
13639 {
13640 case PACKET_QNonStop:
13641 case PACKET_EnableDisableTracepoints_feature:
13642 case PACKET_tracenz_feature:
13643 case PACKET_DisconnectedTracing_feature:
13644 case PACKET_augmented_libraries_svr4_read_feature:
13645 case PACKET_qCRC:
13646 /* Additions to this list need to be well justified:
13647 pre-existing packets are OK; new packets are not. */
13648 excepted = 1;
13649 break;
13650 default:
13651 excepted = 0;
13652 break;
13653 }
13654
13655 /* This catches both forgetting to add a config command, and
13656 forgetting to remove a packet from the exception list. */
13657 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13658 }
13659 }
13660
13661 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13662 Z sub-packet has its own set and show commands, but users may
13663 have sets to this variable in their .gdbinit files (or in their
13664 documentation). */
13665 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13666 &remote_Z_packet_detect, _("\
13667 Set use of remote protocol `Z' packets"), _("\
13668 Show use of remote protocol `Z' packets "), _("\
13669 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13670 packets."),
13671 set_remote_protocol_Z_packet_cmd,
13672 show_remote_protocol_Z_packet_cmd,
13673 /* FIXME: i18n: Use of remote protocol
13674 `Z' packets is %s. */
13675 &remote_set_cmdlist, &remote_show_cmdlist);
13676
13677 add_prefix_cmd ("remote", class_files, remote_command, _("\
13678 Manipulate files on the remote system\n\
13679 Transfer files to and from the remote target system."),
13680 &remote_cmdlist, "remote ",
13681 0 /* allow-unknown */, &cmdlist);
13682
13683 add_cmd ("put", class_files, remote_put_command,
13684 _("Copy a local file to the remote system."),
13685 &remote_cmdlist);
13686
13687 add_cmd ("get", class_files, remote_get_command,
13688 _("Copy a remote file to the local system."),
13689 &remote_cmdlist);
13690
13691 add_cmd ("delete", class_files, remote_delete_command,
13692 _("Delete a remote file."),
13693 &remote_cmdlist);
13694
13695 add_setshow_string_noescape_cmd ("exec-file", class_files,
13696 &remote_exec_file_var, _("\
13697 Set the remote pathname for \"run\""), _("\
13698 Show the remote pathname for \"run\""), NULL,
13699 set_remote_exec_file,
13700 show_remote_exec_file,
13701 &remote_set_cmdlist,
13702 &remote_show_cmdlist);
13703
13704 add_setshow_boolean_cmd ("range-stepping", class_run,
13705 &use_range_stepping, _("\
13706 Enable or disable range stepping."), _("\
13707 Show whether target-assisted range stepping is enabled."), _("\
13708 If on, and the target supports it, when stepping a source line, GDB\n\
13709 tells the target to step the corresponding range of addresses itself instead\n\
13710 of issuing multiple single-steps. This speeds up source level\n\
13711 stepping. If off, GDB always issues single-steps, even if range\n\
13712 stepping is supported by the target. The default is on."),
13713 set_range_stepping,
13714 show_range_stepping,
13715 &setlist,
13716 &showlist);
13717
13718 /* Eventually initialize fileio. See fileio.c */
13719 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13720
13721 /* Take advantage of the fact that the TID field is not used, to tag
13722 special ptids with it set to != 0. */
13723 magic_null_ptid = ptid_build (42000, -1, 1);
13724 not_sent_ptid = ptid_build (42000, -2, 1);
13725 any_thread_ptid = ptid_build (42000, 0, 1);
13726
13727 target_buf_size = 2048;
13728 target_buf = (char *) xmalloc (target_buf_size);
13729 }
13730
This page took 0.485787 seconds and 5 git commands to generate.