5270bd281d370e16ae85434942f2aba712b1c7c8
[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 threadref echo_nextthread;
405 threadref nextthread;
406 threadref resultthreadlist[MAXTHREADLISTRESULTS];
407
408 /* The state of remote notification. */
409 struct remote_notif_state *notif_state;
410
411 /* The branch trace configuration. */
412 struct btrace_config btrace_config;
413
414 /* The argument to the last "vFile:setfs:" packet we sent, used
415 to avoid sending repeated unnecessary "vFile:setfs:" packets.
416 Initialized to -1 to indicate that no "vFile:setfs:" packet
417 has yet been sent. */
418 int fs_pid;
419
420 /* A readahead cache for vFile:pread. Often, reading a binary
421 involves a sequence of small reads. E.g., when parsing an ELF
422 file. A readahead cache helps mostly the case of remote
423 debugging on a connection with higher latency, due to the
424 request/reply nature of the RSP. We only cache data for a single
425 file descriptor at a time. */
426 struct readahead_cache readahead_cache;
427 };
428
429 /* Private data that we'll store in (struct thread_info)->private. */
430 struct private_thread_info
431 {
432 char *extra;
433 char *name;
434 int core;
435
436 /* Whether the target stopped for a breakpoint/watchpoint. */
437 enum target_stop_reason stop_reason;
438
439 /* This is set to the data address of the access causing the target
440 to stop for a watchpoint. */
441 CORE_ADDR watch_data_address;
442 };
443
444 static void
445 free_private_thread_info (struct private_thread_info *info)
446 {
447 xfree (info->extra);
448 xfree (info->name);
449 xfree (info);
450 }
451
452 /* This data could be associated with a target, but we do not always
453 have access to the current target when we need it, so for now it is
454 static. This will be fine for as long as only one target is in use
455 at a time. */
456 static struct remote_state *remote_state;
457
458 static struct remote_state *
459 get_remote_state_raw (void)
460 {
461 return remote_state;
462 }
463
464 /* Allocate a new struct remote_state with xmalloc, initialize it, and
465 return it. */
466
467 static struct remote_state *
468 new_remote_state (void)
469 {
470 struct remote_state *result = XCNEW (struct remote_state);
471
472 /* The default buffer size is unimportant; it will be expanded
473 whenever a larger buffer is needed. */
474 result->buf_size = 400;
475 result->buf = (char *) xmalloc (result->buf_size);
476 result->remote_traceframe_number = -1;
477 result->last_sent_signal = GDB_SIGNAL_0;
478 result->fs_pid = -1;
479
480 return result;
481 }
482
483 /* Description of the remote protocol for a given architecture. */
484
485 struct packet_reg
486 {
487 long offset; /* Offset into G packet. */
488 long regnum; /* GDB's internal register number. */
489 LONGEST pnum; /* Remote protocol register number. */
490 int in_g_packet; /* Always part of G packet. */
491 /* long size in bytes; == register_size (target_gdbarch (), regnum);
492 at present. */
493 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
494 at present. */
495 };
496
497 struct remote_arch_state
498 {
499 /* Description of the remote protocol registers. */
500 long sizeof_g_packet;
501
502 /* Description of the remote protocol registers indexed by REGNUM
503 (making an array gdbarch_num_regs in size). */
504 struct packet_reg *regs;
505
506 /* This is the size (in chars) of the first response to the ``g''
507 packet. It is used as a heuristic when determining the maximum
508 size of memory-read and memory-write packets. A target will
509 typically only reserve a buffer large enough to hold the ``g''
510 packet. The size does not include packet overhead (headers and
511 trailers). */
512 long actual_register_packet_size;
513
514 /* This is the maximum size (in chars) of a non read/write packet.
515 It is also used as a cap on the size of read/write packets. */
516 long remote_packet_size;
517 };
518
519 /* Utility: generate error from an incoming stub packet. */
520 static void
521 trace_error (char *buf)
522 {
523 if (*buf++ != 'E')
524 return; /* not an error msg */
525 switch (*buf)
526 {
527 case '1': /* malformed packet error */
528 if (*++buf == '0') /* general case: */
529 error (_("remote.c: error in outgoing packet."));
530 else
531 error (_("remote.c: error in outgoing packet at field #%ld."),
532 strtol (buf, NULL, 16));
533 default:
534 error (_("Target returns error code '%s'."), buf);
535 }
536 }
537
538 /* Utility: wait for reply from stub, while accepting "O" packets. */
539 static char *
540 remote_get_noisy_reply (char **buf_p,
541 long *sizeof_buf)
542 {
543 do /* Loop on reply from remote stub. */
544 {
545 char *buf;
546
547 QUIT; /* Allow user to bail out with ^C. */
548 getpkt (buf_p, sizeof_buf, 0);
549 buf = *buf_p;
550 if (buf[0] == 'E')
551 trace_error (buf);
552 else if (startswith (buf, "qRelocInsn:"))
553 {
554 ULONGEST ul;
555 CORE_ADDR from, to, org_to;
556 char *p, *pp;
557 int adjusted_size = 0;
558 int relocated = 0;
559
560 p = buf + strlen ("qRelocInsn:");
561 pp = unpack_varlen_hex (p, &ul);
562 if (*pp != ';')
563 error (_("invalid qRelocInsn packet: %s"), buf);
564 from = ul;
565
566 p = pp + 1;
567 unpack_varlen_hex (p, &ul);
568 to = ul;
569
570 org_to = to;
571
572 TRY
573 {
574 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
575 relocated = 1;
576 }
577 CATCH (ex, RETURN_MASK_ALL)
578 {
579 if (ex.error == MEMORY_ERROR)
580 {
581 /* Propagate memory errors silently back to the
582 target. The stub may have limited the range of
583 addresses we can write to, for example. */
584 }
585 else
586 {
587 /* Something unexpectedly bad happened. Be verbose
588 so we can tell what, and propagate the error back
589 to the stub, so it doesn't get stuck waiting for
590 a response. */
591 exception_fprintf (gdb_stderr, ex,
592 _("warning: relocating instruction: "));
593 }
594 putpkt ("E01");
595 }
596 END_CATCH
597
598 if (relocated)
599 {
600 adjusted_size = to - org_to;
601
602 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
603 putpkt (buf);
604 }
605 }
606 else if (buf[0] == 'O' && buf[1] != 'K')
607 remote_console_output (buf + 1); /* 'O' message from stub */
608 else
609 return buf; /* Here's the actual reply. */
610 }
611 while (1);
612 }
613
614 /* Handle for retreving the remote protocol data from gdbarch. */
615 static struct gdbarch_data *remote_gdbarch_data_handle;
616
617 static struct remote_arch_state *
618 get_remote_arch_state (void)
619 {
620 gdb_assert (target_gdbarch () != NULL);
621 return ((struct remote_arch_state *)
622 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
623 }
624
625 /* Fetch the global remote target state. */
626
627 static struct remote_state *
628 get_remote_state (void)
629 {
630 /* Make sure that the remote architecture state has been
631 initialized, because doing so might reallocate rs->buf. Any
632 function which calls getpkt also needs to be mindful of changes
633 to rs->buf, but this call limits the number of places which run
634 into trouble. */
635 get_remote_arch_state ();
636
637 return get_remote_state_raw ();
638 }
639
640 /* Cleanup routine for the remote module's pspace data. */
641
642 static void
643 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
644 {
645 char *remote_exec_file = (char *) arg;
646
647 xfree (remote_exec_file);
648 }
649
650 /* Fetch the remote exec-file from the current program space. */
651
652 static const char *
653 get_remote_exec_file (void)
654 {
655 char *remote_exec_file;
656
657 remote_exec_file
658 = (char *) program_space_data (current_program_space,
659 remote_pspace_data);
660 if (remote_exec_file == NULL)
661 return "";
662
663 return remote_exec_file;
664 }
665
666 /* Set the remote exec file for PSPACE. */
667
668 static void
669 set_pspace_remote_exec_file (struct program_space *pspace,
670 char *remote_exec_file)
671 {
672 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
673
674 xfree (old_file);
675 set_program_space_data (pspace, remote_pspace_data,
676 xstrdup (remote_exec_file));
677 }
678
679 /* The "set/show remote exec-file" set command hook. */
680
681 static void
682 set_remote_exec_file (char *ignored, int from_tty,
683 struct cmd_list_element *c)
684 {
685 gdb_assert (remote_exec_file_var != NULL);
686 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
687 }
688
689 /* The "set/show remote exec-file" show command hook. */
690
691 static void
692 show_remote_exec_file (struct ui_file *file, int from_tty,
693 struct cmd_list_element *cmd, const char *value)
694 {
695 fprintf_filtered (file, "%s\n", remote_exec_file_var);
696 }
697
698 static int
699 compare_pnums (const void *lhs_, const void *rhs_)
700 {
701 const struct packet_reg * const *lhs
702 = (const struct packet_reg * const *) lhs_;
703 const struct packet_reg * const *rhs
704 = (const struct packet_reg * const *) rhs_;
705
706 if ((*lhs)->pnum < (*rhs)->pnum)
707 return -1;
708 else if ((*lhs)->pnum == (*rhs)->pnum)
709 return 0;
710 else
711 return 1;
712 }
713
714 static int
715 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
716 {
717 int regnum, num_remote_regs, offset;
718 struct packet_reg **remote_regs;
719
720 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
721 {
722 struct packet_reg *r = &regs[regnum];
723
724 if (register_size (gdbarch, regnum) == 0)
725 /* Do not try to fetch zero-sized (placeholder) registers. */
726 r->pnum = -1;
727 else
728 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
729
730 r->regnum = regnum;
731 }
732
733 /* Define the g/G packet format as the contents of each register
734 with a remote protocol number, in order of ascending protocol
735 number. */
736
737 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
738 for (num_remote_regs = 0, regnum = 0;
739 regnum < gdbarch_num_regs (gdbarch);
740 regnum++)
741 if (regs[regnum].pnum != -1)
742 remote_regs[num_remote_regs++] = &regs[regnum];
743
744 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
745 compare_pnums);
746
747 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
748 {
749 remote_regs[regnum]->in_g_packet = 1;
750 remote_regs[regnum]->offset = offset;
751 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
752 }
753
754 return offset;
755 }
756
757 /* Given the architecture described by GDBARCH, return the remote
758 protocol register's number and the register's offset in the g/G
759 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
760 If the target does not have a mapping for REGNUM, return false,
761 otherwise, return true. */
762
763 int
764 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
765 int *pnum, int *poffset)
766 {
767 int sizeof_g_packet;
768 struct packet_reg *regs;
769 struct cleanup *old_chain;
770
771 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
772
773 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
774 old_chain = make_cleanup (xfree, regs);
775
776 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
777
778 *pnum = regs[regnum].pnum;
779 *poffset = regs[regnum].offset;
780
781 do_cleanups (old_chain);
782
783 return *pnum != -1;
784 }
785
786 static void *
787 init_remote_state (struct gdbarch *gdbarch)
788 {
789 struct remote_state *rs = get_remote_state_raw ();
790 struct remote_arch_state *rsa;
791
792 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
793
794 /* Use the architecture to build a regnum<->pnum table, which will be
795 1:1 unless a feature set specifies otherwise. */
796 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
797 gdbarch_num_regs (gdbarch),
798 struct packet_reg);
799
800 /* Record the maximum possible size of the g packet - it may turn out
801 to be smaller. */
802 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
803
804 /* Default maximum number of characters in a packet body. Many
805 remote stubs have a hardwired buffer size of 400 bytes
806 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
807 as the maximum packet-size to ensure that the packet and an extra
808 NUL character can always fit in the buffer. This stops GDB
809 trashing stubs that try to squeeze an extra NUL into what is
810 already a full buffer (As of 1999-12-04 that was most stubs). */
811 rsa->remote_packet_size = 400 - 1;
812
813 /* This one is filled in when a ``g'' packet is received. */
814 rsa->actual_register_packet_size = 0;
815
816 /* Should rsa->sizeof_g_packet needs more space than the
817 default, adjust the size accordingly. Remember that each byte is
818 encoded as two characters. 32 is the overhead for the packet
819 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
820 (``$NN:G...#NN'') is a better guess, the below has been padded a
821 little. */
822 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
823 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
824
825 /* Make sure that the packet buffer is plenty big enough for
826 this architecture. */
827 if (rs->buf_size < rsa->remote_packet_size)
828 {
829 rs->buf_size = 2 * rsa->remote_packet_size;
830 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
831 }
832
833 return rsa;
834 }
835
836 /* Return the current allowed size of a remote packet. This is
837 inferred from the current architecture, and should be used to
838 limit the length of outgoing packets. */
839 static long
840 get_remote_packet_size (void)
841 {
842 struct remote_state *rs = get_remote_state ();
843 struct remote_arch_state *rsa = get_remote_arch_state ();
844
845 if (rs->explicit_packet_size)
846 return rs->explicit_packet_size;
847
848 return rsa->remote_packet_size;
849 }
850
851 static struct packet_reg *
852 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
853 {
854 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
855 return NULL;
856 else
857 {
858 struct packet_reg *r = &rsa->regs[regnum];
859
860 gdb_assert (r->regnum == regnum);
861 return r;
862 }
863 }
864
865 static struct packet_reg *
866 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
867 {
868 int i;
869
870 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
871 {
872 struct packet_reg *r = &rsa->regs[i];
873
874 if (r->pnum == pnum)
875 return r;
876 }
877 return NULL;
878 }
879
880 static struct target_ops remote_ops;
881
882 static struct target_ops extended_remote_ops;
883
884 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
885 ``forever'' still use the normal timeout mechanism. This is
886 currently used by the ASYNC code to guarentee that target reads
887 during the initial connect always time-out. Once getpkt has been
888 modified to return a timeout indication and, in turn
889 remote_wait()/wait_for_inferior() have gained a timeout parameter
890 this can go away. */
891 static int wait_forever_enabled_p = 1;
892
893 /* Allow the user to specify what sequence to send to the remote
894 when he requests a program interruption: Although ^C is usually
895 what remote systems expect (this is the default, here), it is
896 sometimes preferable to send a break. On other systems such
897 as the Linux kernel, a break followed by g, which is Magic SysRq g
898 is required in order to interrupt the execution. */
899 const char interrupt_sequence_control_c[] = "Ctrl-C";
900 const char interrupt_sequence_break[] = "BREAK";
901 const char interrupt_sequence_break_g[] = "BREAK-g";
902 static const char *const interrupt_sequence_modes[] =
903 {
904 interrupt_sequence_control_c,
905 interrupt_sequence_break,
906 interrupt_sequence_break_g,
907 NULL
908 };
909 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
910
911 static void
912 show_interrupt_sequence (struct ui_file *file, int from_tty,
913 struct cmd_list_element *c,
914 const char *value)
915 {
916 if (interrupt_sequence_mode == interrupt_sequence_control_c)
917 fprintf_filtered (file,
918 _("Send the ASCII ETX character (Ctrl-c) "
919 "to the remote target to interrupt the "
920 "execution of the program.\n"));
921 else if (interrupt_sequence_mode == interrupt_sequence_break)
922 fprintf_filtered (file,
923 _("send a break signal to the remote target "
924 "to interrupt the execution of the program.\n"));
925 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
926 fprintf_filtered (file,
927 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
928 "the remote target to interrupt the execution "
929 "of Linux kernel.\n"));
930 else
931 internal_error (__FILE__, __LINE__,
932 _("Invalid value for interrupt_sequence_mode: %s."),
933 interrupt_sequence_mode);
934 }
935
936 /* This boolean variable specifies whether interrupt_sequence is sent
937 to the remote target when gdb connects to it.
938 This is mostly needed when you debug the Linux kernel: The Linux kernel
939 expects BREAK g which is Magic SysRq g for connecting gdb. */
940 static int interrupt_on_connect = 0;
941
942 /* This variable is used to implement the "set/show remotebreak" commands.
943 Since these commands are now deprecated in favor of "set/show remote
944 interrupt-sequence", it no longer has any effect on the code. */
945 static int remote_break;
946
947 static void
948 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
949 {
950 if (remote_break)
951 interrupt_sequence_mode = interrupt_sequence_break;
952 else
953 interrupt_sequence_mode = interrupt_sequence_control_c;
954 }
955
956 static void
957 show_remotebreak (struct ui_file *file, int from_tty,
958 struct cmd_list_element *c,
959 const char *value)
960 {
961 }
962
963 /* This variable sets the number of bits in an address that are to be
964 sent in a memory ("M" or "m") packet. Normally, after stripping
965 leading zeros, the entire address would be sent. This variable
966 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
967 initial implementation of remote.c restricted the address sent in
968 memory packets to ``host::sizeof long'' bytes - (typically 32
969 bits). Consequently, for 64 bit targets, the upper 32 bits of an
970 address was never sent. Since fixing this bug may cause a break in
971 some remote targets this variable is principly provided to
972 facilitate backward compatibility. */
973
974 static unsigned int remote_address_size;
975
976 /* Temporary to track who currently owns the terminal. See
977 remote_terminal_* for more details. */
978
979 static int remote_async_terminal_ours_p;
980
981 \f
982 /* User configurable variables for the number of characters in a
983 memory read/write packet. MIN (rsa->remote_packet_size,
984 rsa->sizeof_g_packet) is the default. Some targets need smaller
985 values (fifo overruns, et.al.) and some users need larger values
986 (speed up transfers). The variables ``preferred_*'' (the user
987 request), ``current_*'' (what was actually set) and ``forced_*''
988 (Positive - a soft limit, negative - a hard limit). */
989
990 struct memory_packet_config
991 {
992 char *name;
993 long size;
994 int fixed_p;
995 };
996
997 /* The default max memory-write-packet-size. The 16k is historical.
998 (It came from older GDB's using alloca for buffers and the
999 knowledge (folklore?) that some hosts don't cope very well with
1000 large alloca calls.) */
1001 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1002
1003 /* The minimum remote packet size for memory transfers. Ensures we
1004 can write at least one byte. */
1005 #define MIN_MEMORY_PACKET_SIZE 20
1006
1007 /* Compute the current size of a read/write packet. Since this makes
1008 use of ``actual_register_packet_size'' the computation is dynamic. */
1009
1010 static long
1011 get_memory_packet_size (struct memory_packet_config *config)
1012 {
1013 struct remote_state *rs = get_remote_state ();
1014 struct remote_arch_state *rsa = get_remote_arch_state ();
1015
1016 long what_they_get;
1017 if (config->fixed_p)
1018 {
1019 if (config->size <= 0)
1020 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1021 else
1022 what_they_get = config->size;
1023 }
1024 else
1025 {
1026 what_they_get = get_remote_packet_size ();
1027 /* Limit the packet to the size specified by the user. */
1028 if (config->size > 0
1029 && what_they_get > config->size)
1030 what_they_get = config->size;
1031
1032 /* Limit it to the size of the targets ``g'' response unless we have
1033 permission from the stub to use a larger packet size. */
1034 if (rs->explicit_packet_size == 0
1035 && rsa->actual_register_packet_size > 0
1036 && what_they_get > rsa->actual_register_packet_size)
1037 what_they_get = rsa->actual_register_packet_size;
1038 }
1039 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1040 what_they_get = MIN_MEMORY_PACKET_SIZE;
1041
1042 /* Make sure there is room in the global buffer for this packet
1043 (including its trailing NUL byte). */
1044 if (rs->buf_size < what_they_get + 1)
1045 {
1046 rs->buf_size = 2 * what_they_get;
1047 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1048 }
1049
1050 return what_they_get;
1051 }
1052
1053 /* Update the size of a read/write packet. If they user wants
1054 something really big then do a sanity check. */
1055
1056 static void
1057 set_memory_packet_size (char *args, struct memory_packet_config *config)
1058 {
1059 int fixed_p = config->fixed_p;
1060 long size = config->size;
1061
1062 if (args == NULL)
1063 error (_("Argument required (integer, `fixed' or `limited')."));
1064 else if (strcmp (args, "hard") == 0
1065 || strcmp (args, "fixed") == 0)
1066 fixed_p = 1;
1067 else if (strcmp (args, "soft") == 0
1068 || strcmp (args, "limit") == 0)
1069 fixed_p = 0;
1070 else
1071 {
1072 char *end;
1073
1074 size = strtoul (args, &end, 0);
1075 if (args == end)
1076 error (_("Invalid %s (bad syntax)."), config->name);
1077
1078 /* Instead of explicitly capping the size of a packet to or
1079 disallowing it, the user is allowed to set the size to
1080 something arbitrarily large. */
1081 }
1082
1083 /* So that the query shows the correct value. */
1084 if (size <= 0)
1085 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1086
1087 /* Extra checks? */
1088 if (fixed_p && !config->fixed_p)
1089 {
1090 if (! query (_("The target may not be able to correctly handle a %s\n"
1091 "of %ld bytes. Change the packet size? "),
1092 config->name, size))
1093 error (_("Packet size not changed."));
1094 }
1095 /* Update the config. */
1096 config->fixed_p = fixed_p;
1097 config->size = size;
1098 }
1099
1100 static void
1101 show_memory_packet_size (struct memory_packet_config *config)
1102 {
1103 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1104 if (config->fixed_p)
1105 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1106 get_memory_packet_size (config));
1107 else
1108 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1109 get_memory_packet_size (config));
1110 }
1111
1112 static struct memory_packet_config memory_write_packet_config =
1113 {
1114 "memory-write-packet-size",
1115 };
1116
1117 static void
1118 set_memory_write_packet_size (char *args, int from_tty)
1119 {
1120 set_memory_packet_size (args, &memory_write_packet_config);
1121 }
1122
1123 static void
1124 show_memory_write_packet_size (char *args, int from_tty)
1125 {
1126 show_memory_packet_size (&memory_write_packet_config);
1127 }
1128
1129 static long
1130 get_memory_write_packet_size (void)
1131 {
1132 return get_memory_packet_size (&memory_write_packet_config);
1133 }
1134
1135 static struct memory_packet_config memory_read_packet_config =
1136 {
1137 "memory-read-packet-size",
1138 };
1139
1140 static void
1141 set_memory_read_packet_size (char *args, int from_tty)
1142 {
1143 set_memory_packet_size (args, &memory_read_packet_config);
1144 }
1145
1146 static void
1147 show_memory_read_packet_size (char *args, int from_tty)
1148 {
1149 show_memory_packet_size (&memory_read_packet_config);
1150 }
1151
1152 static long
1153 get_memory_read_packet_size (void)
1154 {
1155 long size = get_memory_packet_size (&memory_read_packet_config);
1156
1157 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1158 extra buffer size argument before the memory read size can be
1159 increased beyond this. */
1160 if (size > get_remote_packet_size ())
1161 size = get_remote_packet_size ();
1162 return size;
1163 }
1164
1165 \f
1166 /* Generic configuration support for packets the stub optionally
1167 supports. Allows the user to specify the use of the packet as well
1168 as allowing GDB to auto-detect support in the remote stub. */
1169
1170 enum packet_support
1171 {
1172 PACKET_SUPPORT_UNKNOWN = 0,
1173 PACKET_ENABLE,
1174 PACKET_DISABLE
1175 };
1176
1177 struct packet_config
1178 {
1179 const char *name;
1180 const char *title;
1181
1182 /* If auto, GDB auto-detects support for this packet or feature,
1183 either through qSupported, or by trying the packet and looking
1184 at the response. If true, GDB assumes the target supports this
1185 packet. If false, the packet is disabled. Configs that don't
1186 have an associated command always have this set to auto. */
1187 enum auto_boolean detect;
1188
1189 /* Does the target support this packet? */
1190 enum packet_support support;
1191 };
1192
1193 /* Analyze a packet's return value and update the packet config
1194 accordingly. */
1195
1196 enum packet_result
1197 {
1198 PACKET_ERROR,
1199 PACKET_OK,
1200 PACKET_UNKNOWN
1201 };
1202
1203 static enum packet_support packet_config_support (struct packet_config *config);
1204 static enum packet_support packet_support (int packet);
1205
1206 static void
1207 show_packet_config_cmd (struct packet_config *config)
1208 {
1209 char *support = "internal-error";
1210
1211 switch (packet_config_support (config))
1212 {
1213 case PACKET_ENABLE:
1214 support = "enabled";
1215 break;
1216 case PACKET_DISABLE:
1217 support = "disabled";
1218 break;
1219 case PACKET_SUPPORT_UNKNOWN:
1220 support = "unknown";
1221 break;
1222 }
1223 switch (config->detect)
1224 {
1225 case AUTO_BOOLEAN_AUTO:
1226 printf_filtered (_("Support for the `%s' packet "
1227 "is auto-detected, currently %s.\n"),
1228 config->name, support);
1229 break;
1230 case AUTO_BOOLEAN_TRUE:
1231 case AUTO_BOOLEAN_FALSE:
1232 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1233 config->name, support);
1234 break;
1235 }
1236 }
1237
1238 static void
1239 add_packet_config_cmd (struct packet_config *config, const char *name,
1240 const char *title, int legacy)
1241 {
1242 char *set_doc;
1243 char *show_doc;
1244 char *cmd_name;
1245
1246 config->name = name;
1247 config->title = title;
1248 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1249 name, title);
1250 show_doc = xstrprintf ("Show current use of remote "
1251 "protocol `%s' (%s) packet",
1252 name, title);
1253 /* set/show TITLE-packet {auto,on,off} */
1254 cmd_name = xstrprintf ("%s-packet", title);
1255 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1256 &config->detect, set_doc,
1257 show_doc, NULL, /* help_doc */
1258 NULL,
1259 show_remote_protocol_packet_cmd,
1260 &remote_set_cmdlist, &remote_show_cmdlist);
1261 /* The command code copies the documentation strings. */
1262 xfree (set_doc);
1263 xfree (show_doc);
1264 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1265 if (legacy)
1266 {
1267 char *legacy_name;
1268
1269 legacy_name = xstrprintf ("%s-packet", name);
1270 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1271 &remote_set_cmdlist);
1272 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1273 &remote_show_cmdlist);
1274 }
1275 }
1276
1277 static enum packet_result
1278 packet_check_result (const char *buf)
1279 {
1280 if (buf[0] != '\0')
1281 {
1282 /* The stub recognized the packet request. Check that the
1283 operation succeeded. */
1284 if (buf[0] == 'E'
1285 && isxdigit (buf[1]) && isxdigit (buf[2])
1286 && buf[3] == '\0')
1287 /* "Enn" - definitly an error. */
1288 return PACKET_ERROR;
1289
1290 /* Always treat "E." as an error. This will be used for
1291 more verbose error messages, such as E.memtypes. */
1292 if (buf[0] == 'E' && buf[1] == '.')
1293 return PACKET_ERROR;
1294
1295 /* The packet may or may not be OK. Just assume it is. */
1296 return PACKET_OK;
1297 }
1298 else
1299 /* The stub does not support the packet. */
1300 return PACKET_UNKNOWN;
1301 }
1302
1303 static enum packet_result
1304 packet_ok (const char *buf, struct packet_config *config)
1305 {
1306 enum packet_result result;
1307
1308 if (config->detect != AUTO_BOOLEAN_TRUE
1309 && config->support == PACKET_DISABLE)
1310 internal_error (__FILE__, __LINE__,
1311 _("packet_ok: attempt to use a disabled packet"));
1312
1313 result = packet_check_result (buf);
1314 switch (result)
1315 {
1316 case PACKET_OK:
1317 case PACKET_ERROR:
1318 /* The stub recognized the packet request. */
1319 if (config->support == PACKET_SUPPORT_UNKNOWN)
1320 {
1321 if (remote_debug)
1322 fprintf_unfiltered (gdb_stdlog,
1323 "Packet %s (%s) is supported\n",
1324 config->name, config->title);
1325 config->support = PACKET_ENABLE;
1326 }
1327 break;
1328 case PACKET_UNKNOWN:
1329 /* The stub does not support the packet. */
1330 if (config->detect == AUTO_BOOLEAN_AUTO
1331 && config->support == PACKET_ENABLE)
1332 {
1333 /* If the stub previously indicated that the packet was
1334 supported then there is a protocol error. */
1335 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1336 config->name, config->title);
1337 }
1338 else if (config->detect == AUTO_BOOLEAN_TRUE)
1339 {
1340 /* The user set it wrong. */
1341 error (_("Enabled packet %s (%s) not recognized by stub"),
1342 config->name, config->title);
1343 }
1344
1345 if (remote_debug)
1346 fprintf_unfiltered (gdb_stdlog,
1347 "Packet %s (%s) is NOT supported\n",
1348 config->name, config->title);
1349 config->support = PACKET_DISABLE;
1350 break;
1351 }
1352
1353 return result;
1354 }
1355
1356 enum {
1357 PACKET_vCont = 0,
1358 PACKET_X,
1359 PACKET_qSymbol,
1360 PACKET_P,
1361 PACKET_p,
1362 PACKET_Z0,
1363 PACKET_Z1,
1364 PACKET_Z2,
1365 PACKET_Z3,
1366 PACKET_Z4,
1367 PACKET_vFile_setfs,
1368 PACKET_vFile_open,
1369 PACKET_vFile_pread,
1370 PACKET_vFile_pwrite,
1371 PACKET_vFile_close,
1372 PACKET_vFile_unlink,
1373 PACKET_vFile_readlink,
1374 PACKET_vFile_fstat,
1375 PACKET_qXfer_auxv,
1376 PACKET_qXfer_features,
1377 PACKET_qXfer_exec_file,
1378 PACKET_qXfer_libraries,
1379 PACKET_qXfer_libraries_svr4,
1380 PACKET_qXfer_memory_map,
1381 PACKET_qXfer_spu_read,
1382 PACKET_qXfer_spu_write,
1383 PACKET_qXfer_osdata,
1384 PACKET_qXfer_threads,
1385 PACKET_qXfer_statictrace_read,
1386 PACKET_qXfer_traceframe_info,
1387 PACKET_qXfer_uib,
1388 PACKET_qGetTIBAddr,
1389 PACKET_qGetTLSAddr,
1390 PACKET_qSupported,
1391 PACKET_qTStatus,
1392 PACKET_QPassSignals,
1393 PACKET_QProgramSignals,
1394 PACKET_qCRC,
1395 PACKET_qSearch_memory,
1396 PACKET_vAttach,
1397 PACKET_vRun,
1398 PACKET_QStartNoAckMode,
1399 PACKET_vKill,
1400 PACKET_qXfer_siginfo_read,
1401 PACKET_qXfer_siginfo_write,
1402 PACKET_qAttached,
1403
1404 /* Support for conditional tracepoints. */
1405 PACKET_ConditionalTracepoints,
1406
1407 /* Support for target-side breakpoint conditions. */
1408 PACKET_ConditionalBreakpoints,
1409
1410 /* Support for target-side breakpoint commands. */
1411 PACKET_BreakpointCommands,
1412
1413 /* Support for fast tracepoints. */
1414 PACKET_FastTracepoints,
1415
1416 /* Support for static tracepoints. */
1417 PACKET_StaticTracepoints,
1418
1419 /* Support for installing tracepoints while a trace experiment is
1420 running. */
1421 PACKET_InstallInTrace,
1422
1423 PACKET_bc,
1424 PACKET_bs,
1425 PACKET_TracepointSource,
1426 PACKET_QAllow,
1427 PACKET_qXfer_fdpic,
1428 PACKET_QDisableRandomization,
1429 PACKET_QAgent,
1430 PACKET_QTBuffer_size,
1431 PACKET_Qbtrace_off,
1432 PACKET_Qbtrace_bts,
1433 PACKET_Qbtrace_pt,
1434 PACKET_qXfer_btrace,
1435
1436 /* Support for the QNonStop packet. */
1437 PACKET_QNonStop,
1438
1439 /* Support for multi-process extensions. */
1440 PACKET_multiprocess_feature,
1441
1442 /* Support for enabling and disabling tracepoints while a trace
1443 experiment is running. */
1444 PACKET_EnableDisableTracepoints_feature,
1445
1446 /* Support for collecting strings using the tracenz bytecode. */
1447 PACKET_tracenz_feature,
1448
1449 /* Support for continuing to run a trace experiment while GDB is
1450 disconnected. */
1451 PACKET_DisconnectedTracing_feature,
1452
1453 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1454 PACKET_augmented_libraries_svr4_read_feature,
1455
1456 /* Support for the qXfer:btrace-conf:read packet. */
1457 PACKET_qXfer_btrace_conf,
1458
1459 /* Support for the Qbtrace-conf:bts:size packet. */
1460 PACKET_Qbtrace_conf_bts_size,
1461
1462 /* Support for swbreak+ feature. */
1463 PACKET_swbreak_feature,
1464
1465 /* Support for hwbreak+ feature. */
1466 PACKET_hwbreak_feature,
1467
1468 /* Support for fork events. */
1469 PACKET_fork_event_feature,
1470
1471 /* Support for vfork events. */
1472 PACKET_vfork_event_feature,
1473
1474 /* Support for the Qbtrace-conf:pt:size packet. */
1475 PACKET_Qbtrace_conf_pt_size,
1476
1477 /* Support for exec events. */
1478 PACKET_exec_event_feature,
1479
1480 /* Support for query supported vCont actions. */
1481 PACKET_vContSupported,
1482
1483 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 /* Clear the thread's private info on resume. */
5331
5332 static void
5333 resume_clear_thread_private_info (struct thread_info *thread)
5334 {
5335 if (thread->priv != NULL)
5336 {
5337 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5338 thread->priv->watch_data_address = 0;
5339 }
5340 }
5341
5342 /* Append a vCont continue-with-signal action for threads that have a
5343 non-zero stop signal. */
5344
5345 static char *
5346 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5347 {
5348 struct thread_info *thread;
5349
5350 ALL_NON_EXITED_THREADS (thread)
5351 if (ptid_match (thread->ptid, ptid)
5352 && !ptid_equal (inferior_ptid, thread->ptid)
5353 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5354 {
5355 p = append_resumption (p, endp, thread->ptid,
5356 0, thread->suspend.stop_signal);
5357 thread->suspend.stop_signal = GDB_SIGNAL_0;
5358 resume_clear_thread_private_info (thread);
5359 }
5360
5361 return p;
5362 }
5363
5364 /* Resume the remote inferior by using a "vCont" packet. The thread
5365 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5366 resumed thread should be single-stepped and/or signalled. If PTID
5367 equals minus_one_ptid, then all threads are resumed; the thread to
5368 be stepped and/or signalled is given in the global INFERIOR_PTID.
5369 This function returns non-zero iff it resumes the inferior.
5370
5371 This function issues a strict subset of all possible vCont commands at the
5372 moment. */
5373
5374 static int
5375 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5376 {
5377 struct remote_state *rs = get_remote_state ();
5378 char *p;
5379 char *endp;
5380
5381 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5382 remote_vcont_probe (rs);
5383
5384 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5385 return 0;
5386
5387 p = rs->buf;
5388 endp = rs->buf + get_remote_packet_size ();
5389
5390 /* If we could generate a wider range of packets, we'd have to worry
5391 about overflowing BUF. Should there be a generic
5392 "multi-part-packet" packet? */
5393
5394 p += xsnprintf (p, endp - p, "vCont");
5395
5396 if (ptid_equal (ptid, magic_null_ptid))
5397 {
5398 /* MAGIC_NULL_PTID means that we don't have any active threads,
5399 so we don't have any TID numbers the inferior will
5400 understand. Make sure to only send forms that do not specify
5401 a TID. */
5402 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5403 }
5404 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5405 {
5406 /* Resume all threads (of all processes, or of a single
5407 process), with preference for INFERIOR_PTID. This assumes
5408 inferior_ptid belongs to the set of all threads we are about
5409 to resume. */
5410 if (step || siggnal != GDB_SIGNAL_0)
5411 {
5412 /* Step inferior_ptid, with or without signal. */
5413 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5414 }
5415
5416 /* Also pass down any pending signaled resumption for other
5417 threads not the current. */
5418 p = append_pending_thread_resumptions (p, endp, ptid);
5419
5420 /* And continue others without a signal. */
5421 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5422 }
5423 else
5424 {
5425 /* Scheduler locking; resume only PTID. */
5426 append_resumption (p, endp, ptid, step, siggnal);
5427 }
5428
5429 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5430 putpkt (rs->buf);
5431
5432 if (target_is_non_stop_p ())
5433 {
5434 /* In non-stop, the stub replies to vCont with "OK". The stop
5435 reply will be reported asynchronously by means of a `%Stop'
5436 notification. */
5437 getpkt (&rs->buf, &rs->buf_size, 0);
5438 if (strcmp (rs->buf, "OK") != 0)
5439 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5440 }
5441
5442 return 1;
5443 }
5444
5445 /* Tell the remote machine to resume. */
5446
5447 static void
5448 remote_resume (struct target_ops *ops,
5449 ptid_t ptid, int step, enum gdb_signal siggnal)
5450 {
5451 struct remote_state *rs = get_remote_state ();
5452 char *buf;
5453 struct thread_info *thread;
5454
5455 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5456 (explained in remote-notif.c:handle_notification) so
5457 remote_notif_process is not called. We need find a place where
5458 it is safe to start a 'vNotif' sequence. It is good to do it
5459 before resuming inferior, because inferior was stopped and no RSP
5460 traffic at that moment. */
5461 if (!target_is_non_stop_p ())
5462 remote_notif_process (rs->notif_state, &notif_client_stop);
5463
5464 rs->last_sent_signal = siggnal;
5465 rs->last_sent_step = step;
5466
5467 /* The vCont packet doesn't need to specify threads via Hc. */
5468 /* No reverse support (yet) for vCont. */
5469 if (execution_direction != EXEC_REVERSE)
5470 if (remote_vcont_resume (ptid, step, siggnal))
5471 goto done;
5472
5473 /* All other supported resume packets do use Hc, so set the continue
5474 thread. */
5475 if (ptid_equal (ptid, minus_one_ptid))
5476 set_continue_thread (any_thread_ptid);
5477 else
5478 set_continue_thread (ptid);
5479
5480 ALL_NON_EXITED_THREADS (thread)
5481 resume_clear_thread_private_info (thread);
5482
5483 buf = rs->buf;
5484 if (execution_direction == EXEC_REVERSE)
5485 {
5486 /* We don't pass signals to the target in reverse exec mode. */
5487 if (info_verbose && siggnal != GDB_SIGNAL_0)
5488 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5489 siggnal);
5490
5491 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5492 error (_("Remote reverse-step not supported."));
5493 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5494 error (_("Remote reverse-continue not supported."));
5495
5496 strcpy (buf, step ? "bs" : "bc");
5497 }
5498 else if (siggnal != GDB_SIGNAL_0)
5499 {
5500 buf[0] = step ? 'S' : 'C';
5501 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5502 buf[2] = tohex (((int) siggnal) & 0xf);
5503 buf[3] = '\0';
5504 }
5505 else
5506 strcpy (buf, step ? "s" : "c");
5507
5508 putpkt (buf);
5509
5510 done:
5511 /* We are about to start executing the inferior, let's register it
5512 with the event loop. NOTE: this is the one place where all the
5513 execution commands end up. We could alternatively do this in each
5514 of the execution commands in infcmd.c. */
5515 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5516 into infcmd.c in order to allow inferior function calls to work
5517 NOT asynchronously. */
5518 if (target_can_async_p ())
5519 target_async (1);
5520
5521 /* We've just told the target to resume. The remote server will
5522 wait for the inferior to stop, and then send a stop reply. In
5523 the mean time, we can't start another command/query ourselves
5524 because the stub wouldn't be ready to process it. This applies
5525 only to the base all-stop protocol, however. In non-stop (which
5526 only supports vCont), the stub replies with an "OK", and is
5527 immediate able to process further serial input. */
5528 if (!target_is_non_stop_p ())
5529 rs->waiting_for_stop_reply = 1;
5530 }
5531 \f
5532
5533 /* Set up the signal handler for SIGINT, while the target is
5534 executing, ovewriting the 'regular' SIGINT signal handler. */
5535 static void
5536 async_initialize_sigint_signal_handler (void)
5537 {
5538 signal (SIGINT, async_handle_remote_sigint);
5539 }
5540
5541 /* Signal handler for SIGINT, while the target is executing. */
5542 static void
5543 async_handle_remote_sigint (int sig)
5544 {
5545 signal (sig, async_handle_remote_sigint_twice);
5546 /* Note we need to go through gdb_call_async_signal_handler in order
5547 to wake up the event loop on Windows. */
5548 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5549 }
5550
5551 /* Signal handler for SIGINT, installed after SIGINT has already been
5552 sent once. It will take effect the second time that the user sends
5553 a ^C. */
5554 static void
5555 async_handle_remote_sigint_twice (int sig)
5556 {
5557 signal (sig, async_handle_remote_sigint);
5558 /* See note in async_handle_remote_sigint. */
5559 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5560 }
5561
5562 /* Implementation of to_check_pending_interrupt. */
5563
5564 static void
5565 remote_check_pending_interrupt (struct target_ops *self)
5566 {
5567 struct async_signal_handler *token = async_sigint_remote_twice_token;
5568
5569 if (async_signal_handler_is_marked (token))
5570 {
5571 clear_async_signal_handler (token);
5572 call_async_signal_handler (token);
5573 }
5574 }
5575
5576 /* Perform the real interruption of the target execution, in response
5577 to a ^C. */
5578 static void
5579 async_remote_interrupt (gdb_client_data arg)
5580 {
5581 if (remote_debug)
5582 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5583
5584 target_stop (inferior_ptid);
5585 }
5586
5587 /* Perform interrupt, if the first attempt did not succeed. Just give
5588 up on the target alltogether. */
5589 static void
5590 async_remote_interrupt_twice (gdb_client_data arg)
5591 {
5592 if (remote_debug)
5593 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5594
5595 interrupt_query ();
5596 }
5597
5598 /* Reinstall the usual SIGINT handlers, after the target has
5599 stopped. */
5600 static void
5601 async_cleanup_sigint_signal_handler (void *dummy)
5602 {
5603 signal (SIGINT, handle_sigint);
5604 }
5605
5606 /* Send ^C to target to halt it. Target will respond, and send us a
5607 packet. */
5608 static void (*ofunc) (int);
5609
5610 /* The command line interface's interrupt routine. This function is installed
5611 as a signal handler for SIGINT. The first time a user requests an
5612 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5613 response from the target (it didn't stop when the user requested it),
5614 we ask the user if he'd like to detach from the target. */
5615
5616 static void
5617 sync_remote_interrupt (int signo)
5618 {
5619 /* If this doesn't work, try more severe steps. */
5620 signal (signo, sync_remote_interrupt_twice);
5621
5622 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5623 }
5624
5625 /* The user typed ^C twice. */
5626
5627 static void
5628 sync_remote_interrupt_twice (int signo)
5629 {
5630 signal (signo, ofunc);
5631 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5632 signal (signo, sync_remote_interrupt);
5633 }
5634
5635 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5636 thread, all threads of a remote process, or all threads of all
5637 processes. */
5638
5639 static void
5640 remote_stop_ns (ptid_t ptid)
5641 {
5642 struct remote_state *rs = get_remote_state ();
5643 char *p = rs->buf;
5644 char *endp = rs->buf + get_remote_packet_size ();
5645
5646 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5647 remote_vcont_probe (rs);
5648
5649 if (!rs->supports_vCont.t)
5650 error (_("Remote server does not support stopping threads"));
5651
5652 if (ptid_equal (ptid, minus_one_ptid)
5653 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5654 p += xsnprintf (p, endp - p, "vCont;t");
5655 else
5656 {
5657 ptid_t nptid;
5658
5659 p += xsnprintf (p, endp - p, "vCont;t:");
5660
5661 if (ptid_is_pid (ptid))
5662 /* All (-1) threads of process. */
5663 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5664 else
5665 {
5666 /* Small optimization: if we already have a stop reply for
5667 this thread, no use in telling the stub we want this
5668 stopped. */
5669 if (peek_stop_reply (ptid))
5670 return;
5671
5672 nptid = ptid;
5673 }
5674
5675 write_ptid (p, endp, nptid);
5676 }
5677
5678 /* In non-stop, we get an immediate OK reply. The stop reply will
5679 come in asynchronously by notification. */
5680 putpkt (rs->buf);
5681 getpkt (&rs->buf, &rs->buf_size, 0);
5682 if (strcmp (rs->buf, "OK") != 0)
5683 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5684 }
5685
5686 /* All-stop version of target_interrupt. Sends a break or a ^C to
5687 interrupt the remote target. It is undefined which thread of which
5688 process reports the interrupt. */
5689
5690 static void
5691 remote_interrupt_as (ptid_t ptid)
5692 {
5693 struct remote_state *rs = get_remote_state ();
5694
5695 rs->ctrlc_pending_p = 1;
5696
5697 /* If the inferior is stopped already, but the core didn't know
5698 about it yet, just ignore the request. The cached wait status
5699 will be collected in remote_wait. */
5700 if (rs->cached_wait_status)
5701 return;
5702
5703 /* Send interrupt_sequence to remote target. */
5704 send_interrupt_sequence ();
5705 }
5706
5707 /* Implement the to_stop function for the remote targets. */
5708
5709 static void
5710 remote_stop (struct target_ops *self, ptid_t ptid)
5711 {
5712 if (remote_debug)
5713 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5714
5715 if (target_is_non_stop_p ())
5716 remote_stop_ns (ptid);
5717 else
5718 {
5719 /* We don't currently have a way to transparently pause the
5720 remote target in all-stop mode. Interrupt it instead. */
5721 remote_interrupt_as (ptid);
5722 }
5723 }
5724
5725 /* Implement the to_interrupt function for the remote targets. */
5726
5727 static void
5728 remote_interrupt (struct target_ops *self, ptid_t ptid)
5729 {
5730 if (remote_debug)
5731 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5732
5733 if (target_is_non_stop_p ())
5734 {
5735 /* We don't currently have a way to ^C the remote target in
5736 non-stop mode. Stop it (with no signal) instead. */
5737 remote_stop_ns (ptid);
5738 }
5739 else
5740 remote_interrupt_as (ptid);
5741 }
5742
5743 /* Ask the user what to do when an interrupt is received. */
5744
5745 static void
5746 interrupt_query (void)
5747 {
5748 struct remote_state *rs = get_remote_state ();
5749 struct cleanup *old_chain;
5750
5751 old_chain = make_cleanup_restore_target_terminal ();
5752 target_terminal_ours ();
5753
5754 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5755 {
5756 if (query (_("The target is not responding to interrupt requests.\n"
5757 "Stop debugging it? ")))
5758 {
5759 remote_unpush_target ();
5760 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5761 }
5762 }
5763 else
5764 {
5765 if (query (_("Interrupted while waiting for the program.\n"
5766 "Give up waiting? ")))
5767 quit ();
5768 }
5769
5770 do_cleanups (old_chain);
5771 }
5772
5773 /* Enable/disable target terminal ownership. Most targets can use
5774 terminal groups to control terminal ownership. Remote targets are
5775 different in that explicit transfer of ownership to/from GDB/target
5776 is required. */
5777
5778 static void
5779 remote_terminal_inferior (struct target_ops *self)
5780 {
5781 if (!target_async_permitted)
5782 /* Nothing to do. */
5783 return;
5784
5785 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5786 idempotent. The event-loop GDB talking to an asynchronous target
5787 with a synchronous command calls this function from both
5788 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5789 transfer the terminal to the target when it shouldn't this guard
5790 can go away. */
5791 if (!remote_async_terminal_ours_p)
5792 return;
5793 delete_file_handler (input_fd);
5794 remote_async_terminal_ours_p = 0;
5795 async_initialize_sigint_signal_handler ();
5796 /* NOTE: At this point we could also register our selves as the
5797 recipient of all input. Any characters typed could then be
5798 passed on down to the target. */
5799 }
5800
5801 static void
5802 remote_terminal_ours (struct target_ops *self)
5803 {
5804 if (!target_async_permitted)
5805 /* Nothing to do. */
5806 return;
5807
5808 /* See FIXME in remote_terminal_inferior. */
5809 if (remote_async_terminal_ours_p)
5810 return;
5811 async_cleanup_sigint_signal_handler (NULL);
5812 add_file_handler (input_fd, stdin_event_handler, 0);
5813 remote_async_terminal_ours_p = 1;
5814 }
5815
5816 static void
5817 remote_console_output (char *msg)
5818 {
5819 char *p;
5820
5821 for (p = msg; p[0] && p[1]; p += 2)
5822 {
5823 char tb[2];
5824 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5825
5826 tb[0] = c;
5827 tb[1] = 0;
5828 fputs_unfiltered (tb, gdb_stdtarg);
5829 }
5830 gdb_flush (gdb_stdtarg);
5831 }
5832
5833 typedef struct cached_reg
5834 {
5835 int num;
5836 gdb_byte data[MAX_REGISTER_SIZE];
5837 } cached_reg_t;
5838
5839 DEF_VEC_O(cached_reg_t);
5840
5841 typedef struct stop_reply
5842 {
5843 struct notif_event base;
5844
5845 /* The identifier of the thread about this event */
5846 ptid_t ptid;
5847
5848 /* The remote state this event is associated with. When the remote
5849 connection, represented by a remote_state object, is closed,
5850 all the associated stop_reply events should be released. */
5851 struct remote_state *rs;
5852
5853 struct target_waitstatus ws;
5854
5855 /* Expedited registers. This makes remote debugging a bit more
5856 efficient for those targets that provide critical registers as
5857 part of their normal status mechanism (as another roundtrip to
5858 fetch them is avoided). */
5859 VEC(cached_reg_t) *regcache;
5860
5861 enum target_stop_reason stop_reason;
5862
5863 CORE_ADDR watch_data_address;
5864
5865 int core;
5866 } *stop_reply_p;
5867
5868 DECLARE_QUEUE_P (stop_reply_p);
5869 DEFINE_QUEUE_P (stop_reply_p);
5870 /* The list of already fetched and acknowledged stop events. This
5871 queue is used for notification Stop, and other notifications
5872 don't need queue for their events, because the notification events
5873 of Stop can't be consumed immediately, so that events should be
5874 queued first, and be consumed by remote_wait_{ns,as} one per
5875 time. Other notifications can consume their events immediately,
5876 so queue is not needed for them. */
5877 static QUEUE (stop_reply_p) *stop_reply_queue;
5878
5879 static void
5880 stop_reply_xfree (struct stop_reply *r)
5881 {
5882 notif_event_xfree ((struct notif_event *) r);
5883 }
5884
5885 /* Return the length of the stop reply queue. */
5886
5887 static int
5888 stop_reply_queue_length (void)
5889 {
5890 return QUEUE_length (stop_reply_p, stop_reply_queue);
5891 }
5892
5893 static void
5894 remote_notif_stop_parse (struct notif_client *self, char *buf,
5895 struct notif_event *event)
5896 {
5897 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5898 }
5899
5900 static void
5901 remote_notif_stop_ack (struct notif_client *self, char *buf,
5902 struct notif_event *event)
5903 {
5904 struct stop_reply *stop_reply = (struct stop_reply *) event;
5905
5906 /* acknowledge */
5907 putpkt ((char *) self->ack_command);
5908
5909 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5910 /* We got an unknown stop reply. */
5911 error (_("Unknown stop reply"));
5912
5913 push_stop_reply (stop_reply);
5914 }
5915
5916 static int
5917 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5918 {
5919 /* We can't get pending events in remote_notif_process for
5920 notification stop, and we have to do this in remote_wait_ns
5921 instead. If we fetch all queued events from stub, remote stub
5922 may exit and we have no chance to process them back in
5923 remote_wait_ns. */
5924 mark_async_event_handler (remote_async_inferior_event_token);
5925 return 0;
5926 }
5927
5928 static void
5929 stop_reply_dtr (struct notif_event *event)
5930 {
5931 struct stop_reply *r = (struct stop_reply *) event;
5932
5933 VEC_free (cached_reg_t, r->regcache);
5934 }
5935
5936 static struct notif_event *
5937 remote_notif_stop_alloc_reply (void)
5938 {
5939 /* We cast to a pointer to the "base class". */
5940 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5941
5942 r->dtr = stop_reply_dtr;
5943
5944 return r;
5945 }
5946
5947 /* A client of notification Stop. */
5948
5949 struct notif_client notif_client_stop =
5950 {
5951 "Stop",
5952 "vStopped",
5953 remote_notif_stop_parse,
5954 remote_notif_stop_ack,
5955 remote_notif_stop_can_get_pending_events,
5956 remote_notif_stop_alloc_reply,
5957 REMOTE_NOTIF_STOP,
5958 };
5959
5960 /* A parameter to pass data in and out. */
5961
5962 struct queue_iter_param
5963 {
5964 void *input;
5965 struct stop_reply *output;
5966 };
5967
5968 /* Determine if THREAD is a pending fork parent thread. ARG contains
5969 the pid of the process that owns the threads we want to check, or
5970 -1 if we want to check all threads. */
5971
5972 static int
5973 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5974 ptid_t thread_ptid)
5975 {
5976 if (ws->kind == TARGET_WAITKIND_FORKED
5977 || ws->kind == TARGET_WAITKIND_VFORKED)
5978 {
5979 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5980 return 1;
5981 }
5982
5983 return 0;
5984 }
5985
5986 /* Check whether EVENT is a fork event, and if it is, remove the
5987 fork child from the context list passed in DATA. */
5988
5989 static int
5990 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5991 QUEUE_ITER (stop_reply_p) *iter,
5992 stop_reply_p event,
5993 void *data)
5994 {
5995 struct queue_iter_param *param = (struct queue_iter_param *) data;
5996 struct threads_listing_context *context
5997 = (struct threads_listing_context *) param->input;
5998
5999 if (event->ws.kind == TARGET_WAITKIND_FORKED
6000 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6001 {
6002 threads_listing_context_remove (&event->ws, context);
6003 }
6004
6005 return 1;
6006 }
6007
6008 /* If CONTEXT contains any fork child threads that have not been
6009 reported yet, remove them from the CONTEXT list. If such a
6010 thread exists it is because we are stopped at a fork catchpoint
6011 and have not yet called follow_fork, which will set up the
6012 host-side data structures for the new process. */
6013
6014 static void
6015 remove_new_fork_children (struct threads_listing_context *context)
6016 {
6017 struct thread_info * thread;
6018 int pid = -1;
6019 struct notif_client *notif = &notif_client_stop;
6020 struct queue_iter_param param;
6021
6022 /* For any threads stopped at a fork event, remove the corresponding
6023 fork child threads from the CONTEXT list. */
6024 ALL_NON_EXITED_THREADS (thread)
6025 {
6026 struct target_waitstatus *ws = &thread->pending_follow;
6027
6028 if (is_pending_fork_parent (ws, pid, thread->ptid))
6029 {
6030 threads_listing_context_remove (ws, context);
6031 }
6032 }
6033
6034 /* Check for any pending fork events (not reported or processed yet)
6035 in process PID and remove those fork child threads from the
6036 CONTEXT list as well. */
6037 remote_notif_get_pending_events (notif);
6038 param.input = context;
6039 param.output = NULL;
6040 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6041 remove_child_of_pending_fork, &param);
6042 }
6043
6044 /* Remove stop replies in the queue if its pid is equal to the given
6045 inferior's pid. */
6046
6047 static int
6048 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6049 QUEUE_ITER (stop_reply_p) *iter,
6050 stop_reply_p event,
6051 void *data)
6052 {
6053 struct queue_iter_param *param = (struct queue_iter_param *) data;
6054 struct inferior *inf = (struct inferior *) param->input;
6055
6056 if (ptid_get_pid (event->ptid) == inf->pid)
6057 {
6058 stop_reply_xfree (event);
6059 QUEUE_remove_elem (stop_reply_p, q, iter);
6060 }
6061
6062 return 1;
6063 }
6064
6065 /* Discard all pending stop replies of inferior INF. */
6066
6067 static void
6068 discard_pending_stop_replies (struct inferior *inf)
6069 {
6070 int i;
6071 struct queue_iter_param param;
6072 struct stop_reply *reply;
6073 struct remote_state *rs = get_remote_state ();
6074 struct remote_notif_state *rns = rs->notif_state;
6075
6076 /* This function can be notified when an inferior exists. When the
6077 target is not remote, the notification state is NULL. */
6078 if (rs->remote_desc == NULL)
6079 return;
6080
6081 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6082
6083 /* Discard the in-flight notification. */
6084 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6085 {
6086 stop_reply_xfree (reply);
6087 rns->pending_event[notif_client_stop.id] = NULL;
6088 }
6089
6090 param.input = inf;
6091 param.output = NULL;
6092 /* Discard the stop replies we have already pulled with
6093 vStopped. */
6094 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6095 remove_stop_reply_for_inferior, &param);
6096 }
6097
6098 /* If its remote state is equal to the given remote state,
6099 remove EVENT from the stop reply queue. */
6100
6101 static int
6102 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6103 QUEUE_ITER (stop_reply_p) *iter,
6104 stop_reply_p event,
6105 void *data)
6106 {
6107 struct queue_iter_param *param = (struct queue_iter_param *) data;
6108 struct remote_state *rs = (struct remote_state *) param->input;
6109
6110 if (event->rs == rs)
6111 {
6112 stop_reply_xfree (event);
6113 QUEUE_remove_elem (stop_reply_p, q, iter);
6114 }
6115
6116 return 1;
6117 }
6118
6119 /* Discard the stop replies for RS in stop_reply_queue. */
6120
6121 static void
6122 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6123 {
6124 struct queue_iter_param param;
6125
6126 param.input = rs;
6127 param.output = NULL;
6128 /* Discard the stop replies we have already pulled with
6129 vStopped. */
6130 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6131 remove_stop_reply_of_remote_state, &param);
6132 }
6133
6134 /* A parameter to pass data in and out. */
6135
6136 static int
6137 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6138 QUEUE_ITER (stop_reply_p) *iter,
6139 stop_reply_p event,
6140 void *data)
6141 {
6142 struct queue_iter_param *param = (struct queue_iter_param *) data;
6143 ptid_t *ptid = (ptid_t *) param->input;
6144
6145 if (ptid_match (event->ptid, *ptid))
6146 {
6147 param->output = event;
6148 QUEUE_remove_elem (stop_reply_p, q, iter);
6149 return 0;
6150 }
6151
6152 return 1;
6153 }
6154
6155 /* Remove the first reply in 'stop_reply_queue' which matches
6156 PTID. */
6157
6158 static struct stop_reply *
6159 remote_notif_remove_queued_reply (ptid_t ptid)
6160 {
6161 struct queue_iter_param param;
6162
6163 param.input = &ptid;
6164 param.output = NULL;
6165
6166 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6167 remote_notif_remove_once_on_match, &param);
6168 if (notif_debug)
6169 fprintf_unfiltered (gdb_stdlog,
6170 "notif: discard queued event: 'Stop' in %s\n",
6171 target_pid_to_str (ptid));
6172
6173 return param.output;
6174 }
6175
6176 /* Look for a queued stop reply belonging to PTID. If one is found,
6177 remove it from the queue, and return it. Returns NULL if none is
6178 found. If there are still queued events left to process, tell the
6179 event loop to get back to target_wait soon. */
6180
6181 static struct stop_reply *
6182 queued_stop_reply (ptid_t ptid)
6183 {
6184 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6185
6186 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6187 /* There's still at least an event left. */
6188 mark_async_event_handler (remote_async_inferior_event_token);
6189
6190 return r;
6191 }
6192
6193 /* Push a fully parsed stop reply in the stop reply queue. Since we
6194 know that we now have at least one queued event left to pass to the
6195 core side, tell the event loop to get back to target_wait soon. */
6196
6197 static void
6198 push_stop_reply (struct stop_reply *new_event)
6199 {
6200 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6201
6202 if (notif_debug)
6203 fprintf_unfiltered (gdb_stdlog,
6204 "notif: push 'Stop' %s to queue %d\n",
6205 target_pid_to_str (new_event->ptid),
6206 QUEUE_length (stop_reply_p,
6207 stop_reply_queue));
6208
6209 mark_async_event_handler (remote_async_inferior_event_token);
6210 }
6211
6212 static int
6213 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6214 QUEUE_ITER (stop_reply_p) *iter,
6215 struct stop_reply *event,
6216 void *data)
6217 {
6218 ptid_t *ptid = (ptid_t *) data;
6219
6220 return !(ptid_equal (*ptid, event->ptid)
6221 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6222 }
6223
6224 /* Returns true if we have a stop reply for PTID. */
6225
6226 static int
6227 peek_stop_reply (ptid_t ptid)
6228 {
6229 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6230 stop_reply_match_ptid_and_ws, &ptid);
6231 }
6232
6233 /* Skip PACKET until the next semi-colon (or end of string). */
6234
6235 static char *
6236 skip_to_semicolon (char *p)
6237 {
6238 while (*p != '\0' && *p != ';')
6239 p++;
6240 return p;
6241 }
6242
6243 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6244 starting with P and ending with PEND matches PREFIX. */
6245
6246 static int
6247 strprefix (const char *p, const char *pend, const char *prefix)
6248 {
6249 for ( ; p < pend; p++, prefix++)
6250 if (*p != *prefix)
6251 return 0;
6252 return *prefix == '\0';
6253 }
6254
6255 /* Parse the stop reply in BUF. Either the function succeeds, and the
6256 result is stored in EVENT, or throws an error. */
6257
6258 static void
6259 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6260 {
6261 struct remote_arch_state *rsa = get_remote_arch_state ();
6262 ULONGEST addr;
6263 char *p;
6264 int skipregs = 0;
6265
6266 event->ptid = null_ptid;
6267 event->rs = get_remote_state ();
6268 event->ws.kind = TARGET_WAITKIND_IGNORE;
6269 event->ws.value.integer = 0;
6270 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6271 event->regcache = NULL;
6272 event->core = -1;
6273
6274 switch (buf[0])
6275 {
6276 case 'T': /* Status with PC, SP, FP, ... */
6277 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6278 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6279 ss = signal number
6280 n... = register number
6281 r... = register contents
6282 */
6283
6284 p = &buf[3]; /* after Txx */
6285 while (*p)
6286 {
6287 char *p1;
6288 int fieldsize;
6289
6290 p1 = strchr (p, ':');
6291 if (p1 == NULL)
6292 error (_("Malformed packet(a) (missing colon): %s\n\
6293 Packet: '%s'\n"),
6294 p, buf);
6295 if (p == p1)
6296 error (_("Malformed packet(a) (missing register number): %s\n\
6297 Packet: '%s'\n"),
6298 p, buf);
6299
6300 /* Some "registers" are actually extended stop information.
6301 Note if you're adding a new entry here: GDB 7.9 and
6302 earlier assume that all register "numbers" that start
6303 with an hex digit are real register numbers. Make sure
6304 the server only sends such a packet if it knows the
6305 client understands it. */
6306
6307 if (strprefix (p, p1, "thread"))
6308 event->ptid = read_ptid (++p1, &p);
6309 else if (strprefix (p, p1, "watch")
6310 || strprefix (p, p1, "rwatch")
6311 || strprefix (p, p1, "awatch"))
6312 {
6313 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6314 p = unpack_varlen_hex (++p1, &addr);
6315 event->watch_data_address = (CORE_ADDR) addr;
6316 }
6317 else if (strprefix (p, p1, "swbreak"))
6318 {
6319 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6320
6321 /* Make sure the stub doesn't forget to indicate support
6322 with qSupported. */
6323 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6324 error (_("Unexpected swbreak stop reason"));
6325
6326 /* The value part is documented as "must be empty",
6327 though we ignore it, in case we ever decide to make
6328 use of it in a backward compatible way. */
6329 p = skip_to_semicolon (p1 + 1);
6330 }
6331 else if (strprefix (p, p1, "hwbreak"))
6332 {
6333 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6334
6335 /* Make sure the stub doesn't forget to indicate support
6336 with qSupported. */
6337 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6338 error (_("Unexpected hwbreak stop reason"));
6339
6340 /* See above. */
6341 p = skip_to_semicolon (p1 + 1);
6342 }
6343 else if (strprefix (p, p1, "library"))
6344 {
6345 event->ws.kind = TARGET_WAITKIND_LOADED;
6346 p = skip_to_semicolon (p1 + 1);
6347 }
6348 else if (strprefix (p, p1, "replaylog"))
6349 {
6350 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6351 /* p1 will indicate "begin" or "end", but it makes
6352 no difference for now, so ignore it. */
6353 p = skip_to_semicolon (p1 + 1);
6354 }
6355 else if (strprefix (p, p1, "core"))
6356 {
6357 ULONGEST c;
6358
6359 p = unpack_varlen_hex (++p1, &c);
6360 event->core = c;
6361 }
6362 else if (strprefix (p, p1, "fork"))
6363 {
6364 event->ws.value.related_pid = read_ptid (++p1, &p);
6365 event->ws.kind = TARGET_WAITKIND_FORKED;
6366 }
6367 else if (strprefix (p, p1, "vfork"))
6368 {
6369 event->ws.value.related_pid = read_ptid (++p1, &p);
6370 event->ws.kind = TARGET_WAITKIND_VFORKED;
6371 }
6372 else if (strprefix (p, p1, "vforkdone"))
6373 {
6374 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6375 p = skip_to_semicolon (p1 + 1);
6376 }
6377 else if (strprefix (p, p1, "exec"))
6378 {
6379 ULONGEST ignored;
6380 char pathname[PATH_MAX];
6381 int pathlen;
6382
6383 /* Determine the length of the execd pathname. */
6384 p = unpack_varlen_hex (++p1, &ignored);
6385 pathlen = (p - p1) / 2;
6386
6387 /* Save the pathname for event reporting and for
6388 the next run command. */
6389 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6390 pathname[pathlen] = '\0';
6391
6392 /* This is freed during event handling. */
6393 event->ws.value.execd_pathname = xstrdup (pathname);
6394 event->ws.kind = TARGET_WAITKIND_EXECD;
6395
6396 /* Skip the registers included in this packet, since
6397 they may be for an architecture different from the
6398 one used by the original program. */
6399 skipregs = 1;
6400 }
6401 else
6402 {
6403 ULONGEST pnum;
6404 char *p_temp;
6405
6406 if (skipregs)
6407 {
6408 p = skip_to_semicolon (p1 + 1);
6409 p++;
6410 continue;
6411 }
6412
6413 /* Maybe a real ``P'' register number. */
6414 p_temp = unpack_varlen_hex (p, &pnum);
6415 /* If the first invalid character is the colon, we got a
6416 register number. Otherwise, it's an unknown stop
6417 reason. */
6418 if (p_temp == p1)
6419 {
6420 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6421 cached_reg_t cached_reg;
6422
6423 if (reg == NULL)
6424 error (_("Remote sent bad register number %s: %s\n\
6425 Packet: '%s'\n"),
6426 hex_string (pnum), p, buf);
6427
6428 cached_reg.num = reg->regnum;
6429
6430 p = p1 + 1;
6431 fieldsize = hex2bin (p, cached_reg.data,
6432 register_size (target_gdbarch (),
6433 reg->regnum));
6434 p += 2 * fieldsize;
6435 if (fieldsize < register_size (target_gdbarch (),
6436 reg->regnum))
6437 warning (_("Remote reply is too short: %s"), buf);
6438
6439 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6440 }
6441 else
6442 {
6443 /* Not a number. Silently skip unknown optional
6444 info. */
6445 p = skip_to_semicolon (p1 + 1);
6446 }
6447 }
6448
6449 if (*p != ';')
6450 error (_("Remote register badly formatted: %s\nhere: %s"),
6451 buf, p);
6452 ++p;
6453 }
6454
6455 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6456 break;
6457
6458 /* fall through */
6459 case 'S': /* Old style status, just signal only. */
6460 {
6461 int sig;
6462
6463 event->ws.kind = TARGET_WAITKIND_STOPPED;
6464 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6465 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6466 event->ws.value.sig = (enum gdb_signal) sig;
6467 else
6468 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6469 }
6470 break;
6471 case 'W': /* Target exited. */
6472 case 'X':
6473 {
6474 char *p;
6475 int pid;
6476 ULONGEST value;
6477
6478 /* GDB used to accept only 2 hex chars here. Stubs should
6479 only send more if they detect GDB supports multi-process
6480 support. */
6481 p = unpack_varlen_hex (&buf[1], &value);
6482
6483 if (buf[0] == 'W')
6484 {
6485 /* The remote process exited. */
6486 event->ws.kind = TARGET_WAITKIND_EXITED;
6487 event->ws.value.integer = value;
6488 }
6489 else
6490 {
6491 /* The remote process exited with a signal. */
6492 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6493 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6494 event->ws.value.sig = (enum gdb_signal) value;
6495 else
6496 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6497 }
6498
6499 /* If no process is specified, assume inferior_ptid. */
6500 pid = ptid_get_pid (inferior_ptid);
6501 if (*p == '\0')
6502 ;
6503 else if (*p == ';')
6504 {
6505 p++;
6506
6507 if (*p == '\0')
6508 ;
6509 else if (startswith (p, "process:"))
6510 {
6511 ULONGEST upid;
6512
6513 p += sizeof ("process:") - 1;
6514 unpack_varlen_hex (p, &upid);
6515 pid = upid;
6516 }
6517 else
6518 error (_("unknown stop reply packet: %s"), buf);
6519 }
6520 else
6521 error (_("unknown stop reply packet: %s"), buf);
6522 event->ptid = pid_to_ptid (pid);
6523 }
6524 break;
6525 }
6526
6527 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6528 error (_("No process or thread specified in stop reply: %s"), buf);
6529 }
6530
6531 /* When the stub wants to tell GDB about a new notification reply, it
6532 sends a notification (%Stop, for example). Those can come it at
6533 any time, hence, we have to make sure that any pending
6534 putpkt/getpkt sequence we're making is finished, before querying
6535 the stub for more events with the corresponding ack command
6536 (vStopped, for example). E.g., if we started a vStopped sequence
6537 immediately upon receiving the notification, something like this
6538 could happen:
6539
6540 1.1) --> Hg 1
6541 1.2) <-- OK
6542 1.3) --> g
6543 1.4) <-- %Stop
6544 1.5) --> vStopped
6545 1.6) <-- (registers reply to step #1.3)
6546
6547 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6548 query.
6549
6550 To solve this, whenever we parse a %Stop notification successfully,
6551 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6552 doing whatever we were doing:
6553
6554 2.1) --> Hg 1
6555 2.2) <-- OK
6556 2.3) --> g
6557 2.4) <-- %Stop
6558 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6559 2.5) <-- (registers reply to step #2.3)
6560
6561 Eventualy after step #2.5, we return to the event loop, which
6562 notices there's an event on the
6563 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6564 associated callback --- the function below. At this point, we're
6565 always safe to start a vStopped sequence. :
6566
6567 2.6) --> vStopped
6568 2.7) <-- T05 thread:2
6569 2.8) --> vStopped
6570 2.9) --> OK
6571 */
6572
6573 void
6574 remote_notif_get_pending_events (struct notif_client *nc)
6575 {
6576 struct remote_state *rs = get_remote_state ();
6577
6578 if (rs->notif_state->pending_event[nc->id] != NULL)
6579 {
6580 if (notif_debug)
6581 fprintf_unfiltered (gdb_stdlog,
6582 "notif: process: '%s' ack pending event\n",
6583 nc->name);
6584
6585 /* acknowledge */
6586 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6587 rs->notif_state->pending_event[nc->id] = NULL;
6588
6589 while (1)
6590 {
6591 getpkt (&rs->buf, &rs->buf_size, 0);
6592 if (strcmp (rs->buf, "OK") == 0)
6593 break;
6594 else
6595 remote_notif_ack (nc, rs->buf);
6596 }
6597 }
6598 else
6599 {
6600 if (notif_debug)
6601 fprintf_unfiltered (gdb_stdlog,
6602 "notif: process: '%s' no pending reply\n",
6603 nc->name);
6604 }
6605 }
6606
6607 /* Called when it is decided that STOP_REPLY holds the info of the
6608 event that is to be returned to the core. This function always
6609 destroys STOP_REPLY. */
6610
6611 static ptid_t
6612 process_stop_reply (struct stop_reply *stop_reply,
6613 struct target_waitstatus *status)
6614 {
6615 ptid_t ptid;
6616
6617 *status = stop_reply->ws;
6618 ptid = stop_reply->ptid;
6619
6620 /* If no thread/process was reported by the stub, assume the current
6621 inferior. */
6622 if (ptid_equal (ptid, null_ptid))
6623 ptid = inferior_ptid;
6624
6625 if (status->kind != TARGET_WAITKIND_EXITED
6626 && status->kind != TARGET_WAITKIND_SIGNALLED)
6627 {
6628 struct remote_state *rs = get_remote_state ();
6629 struct private_thread_info *remote_thr;
6630
6631 /* Expedited registers. */
6632 if (stop_reply->regcache)
6633 {
6634 struct regcache *regcache
6635 = get_thread_arch_regcache (ptid, target_gdbarch ());
6636 cached_reg_t *reg;
6637 int ix;
6638
6639 for (ix = 0;
6640 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6641 ix++)
6642 regcache_raw_supply (regcache, reg->num, reg->data);
6643 VEC_free (cached_reg_t, stop_reply->regcache);
6644 }
6645
6646 remote_notice_new_inferior (ptid, 0);
6647 remote_thr = demand_private_info (ptid);
6648 remote_thr->core = stop_reply->core;
6649 remote_thr->stop_reason = stop_reply->stop_reason;
6650 remote_thr->watch_data_address = stop_reply->watch_data_address;
6651 }
6652
6653 stop_reply_xfree (stop_reply);
6654 return ptid;
6655 }
6656
6657 /* The non-stop mode version of target_wait. */
6658
6659 static ptid_t
6660 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6661 {
6662 struct remote_state *rs = get_remote_state ();
6663 struct stop_reply *stop_reply;
6664 int ret;
6665 int is_notif = 0;
6666
6667 /* If in non-stop mode, get out of getpkt even if a
6668 notification is received. */
6669
6670 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6671 0 /* forever */, &is_notif);
6672 while (1)
6673 {
6674 if (ret != -1 && !is_notif)
6675 switch (rs->buf[0])
6676 {
6677 case 'E': /* Error of some sort. */
6678 /* We're out of sync with the target now. Did it continue
6679 or not? We can't tell which thread it was in non-stop,
6680 so just ignore this. */
6681 warning (_("Remote failure reply: %s"), rs->buf);
6682 break;
6683 case 'O': /* Console output. */
6684 remote_console_output (rs->buf + 1);
6685 break;
6686 default:
6687 warning (_("Invalid remote reply: %s"), rs->buf);
6688 break;
6689 }
6690
6691 /* Acknowledge a pending stop reply that may have arrived in the
6692 mean time. */
6693 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6694 remote_notif_get_pending_events (&notif_client_stop);
6695
6696 /* If indeed we noticed a stop reply, we're done. */
6697 stop_reply = queued_stop_reply (ptid);
6698 if (stop_reply != NULL)
6699 return process_stop_reply (stop_reply, status);
6700
6701 /* Still no event. If we're just polling for an event, then
6702 return to the event loop. */
6703 if (options & TARGET_WNOHANG)
6704 {
6705 status->kind = TARGET_WAITKIND_IGNORE;
6706 return minus_one_ptid;
6707 }
6708
6709 /* Otherwise do a blocking wait. */
6710 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6711 1 /* forever */, &is_notif);
6712 }
6713 }
6714
6715 /* Wait until the remote machine stops, then return, storing status in
6716 STATUS just as `wait' would. */
6717
6718 static ptid_t
6719 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6720 {
6721 struct remote_state *rs = get_remote_state ();
6722 ptid_t event_ptid = null_ptid;
6723 char *buf;
6724 struct stop_reply *stop_reply;
6725
6726 again:
6727
6728 status->kind = TARGET_WAITKIND_IGNORE;
6729 status->value.integer = 0;
6730
6731 stop_reply = queued_stop_reply (ptid);
6732 if (stop_reply != NULL)
6733 return process_stop_reply (stop_reply, status);
6734
6735 if (rs->cached_wait_status)
6736 /* Use the cached wait status, but only once. */
6737 rs->cached_wait_status = 0;
6738 else
6739 {
6740 int ret;
6741 int is_notif;
6742 int forever = ((options & TARGET_WNOHANG) == 0
6743 && wait_forever_enabled_p);
6744
6745 if (!rs->waiting_for_stop_reply)
6746 {
6747 status->kind = TARGET_WAITKIND_NO_RESUMED;
6748 return minus_one_ptid;
6749 }
6750
6751 if (!target_is_async_p ())
6752 {
6753 ofunc = signal (SIGINT, sync_remote_interrupt);
6754 /* If the user hit C-c before this packet, or between packets,
6755 pretend that it was hit right here. */
6756 if (check_quit_flag ())
6757 {
6758 clear_quit_flag ();
6759 sync_remote_interrupt (SIGINT);
6760 }
6761 }
6762
6763 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6764 _never_ wait for ever -> test on target_is_async_p().
6765 However, before we do that we need to ensure that the caller
6766 knows how to take the target into/out of async mode. */
6767 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6768 forever, &is_notif);
6769
6770 if (!target_is_async_p ())
6771 signal (SIGINT, ofunc);
6772
6773 /* GDB gets a notification. Return to core as this event is
6774 not interesting. */
6775 if (ret != -1 && is_notif)
6776 return minus_one_ptid;
6777
6778 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6779 return minus_one_ptid;
6780 }
6781
6782 buf = rs->buf;
6783
6784 /* Assume that the target has acknowledged Ctrl-C unless we receive
6785 an 'F' or 'O' packet. */
6786 if (buf[0] != 'F' && buf[0] != 'O')
6787 rs->ctrlc_pending_p = 0;
6788
6789 switch (buf[0])
6790 {
6791 case 'E': /* Error of some sort. */
6792 /* We're out of sync with the target now. Did it continue or
6793 not? Not is more likely, so report a stop. */
6794 rs->waiting_for_stop_reply = 0;
6795
6796 warning (_("Remote failure reply: %s"), buf);
6797 status->kind = TARGET_WAITKIND_STOPPED;
6798 status->value.sig = GDB_SIGNAL_0;
6799 break;
6800 case 'F': /* File-I/O request. */
6801 remote_fileio_request (buf, rs->ctrlc_pending_p);
6802 rs->ctrlc_pending_p = 0;
6803 break;
6804 case 'T': case 'S': case 'X': case 'W':
6805 {
6806 struct stop_reply *stop_reply;
6807
6808 /* There is a stop reply to handle. */
6809 rs->waiting_for_stop_reply = 0;
6810
6811 stop_reply
6812 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6813 rs->buf);
6814
6815 event_ptid = process_stop_reply (stop_reply, status);
6816 break;
6817 }
6818 case 'O': /* Console output. */
6819 remote_console_output (buf + 1);
6820 break;
6821 case '\0':
6822 if (rs->last_sent_signal != GDB_SIGNAL_0)
6823 {
6824 /* Zero length reply means that we tried 'S' or 'C' and the
6825 remote system doesn't support it. */
6826 target_terminal_ours_for_output ();
6827 printf_filtered
6828 ("Can't send signals to this remote system. %s not sent.\n",
6829 gdb_signal_to_name (rs->last_sent_signal));
6830 rs->last_sent_signal = GDB_SIGNAL_0;
6831 target_terminal_inferior ();
6832
6833 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6834 putpkt ((char *) buf);
6835 break;
6836 }
6837 /* else fallthrough */
6838 default:
6839 warning (_("Invalid remote reply: %s"), buf);
6840 break;
6841 }
6842
6843 if (status->kind == TARGET_WAITKIND_IGNORE)
6844 {
6845 /* Nothing interesting happened. If we're doing a non-blocking
6846 poll, we're done. Otherwise, go back to waiting. */
6847 if (options & TARGET_WNOHANG)
6848 return minus_one_ptid;
6849 else
6850 goto again;
6851 }
6852 else if (status->kind != TARGET_WAITKIND_EXITED
6853 && status->kind != TARGET_WAITKIND_SIGNALLED)
6854 {
6855 if (!ptid_equal (event_ptid, null_ptid))
6856 record_currthread (rs, event_ptid);
6857 else
6858 event_ptid = inferior_ptid;
6859 }
6860 else
6861 /* A process exit. Invalidate our notion of current thread. */
6862 record_currthread (rs, minus_one_ptid);
6863
6864 return event_ptid;
6865 }
6866
6867 /* Wait until the remote machine stops, then return, storing status in
6868 STATUS just as `wait' would. */
6869
6870 static ptid_t
6871 remote_wait (struct target_ops *ops,
6872 ptid_t ptid, struct target_waitstatus *status, int options)
6873 {
6874 ptid_t event_ptid;
6875
6876 if (target_is_non_stop_p ())
6877 event_ptid = remote_wait_ns (ptid, status, options);
6878 else
6879 event_ptid = remote_wait_as (ptid, status, options);
6880
6881 if (target_is_async_p ())
6882 {
6883 /* If there are are events left in the queue tell the event loop
6884 to return here. */
6885 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6886 mark_async_event_handler (remote_async_inferior_event_token);
6887 }
6888
6889 return event_ptid;
6890 }
6891
6892 /* Fetch a single register using a 'p' packet. */
6893
6894 static int
6895 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6896 {
6897 struct remote_state *rs = get_remote_state ();
6898 char *buf, *p;
6899 char regp[MAX_REGISTER_SIZE];
6900 int i;
6901
6902 if (packet_support (PACKET_p) == PACKET_DISABLE)
6903 return 0;
6904
6905 if (reg->pnum == -1)
6906 return 0;
6907
6908 p = rs->buf;
6909 *p++ = 'p';
6910 p += hexnumstr (p, reg->pnum);
6911 *p++ = '\0';
6912 putpkt (rs->buf);
6913 getpkt (&rs->buf, &rs->buf_size, 0);
6914
6915 buf = rs->buf;
6916
6917 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6918 {
6919 case PACKET_OK:
6920 break;
6921 case PACKET_UNKNOWN:
6922 return 0;
6923 case PACKET_ERROR:
6924 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6925 gdbarch_register_name (get_regcache_arch (regcache),
6926 reg->regnum),
6927 buf);
6928 }
6929
6930 /* If this register is unfetchable, tell the regcache. */
6931 if (buf[0] == 'x')
6932 {
6933 regcache_raw_supply (regcache, reg->regnum, NULL);
6934 return 1;
6935 }
6936
6937 /* Otherwise, parse and supply the value. */
6938 p = buf;
6939 i = 0;
6940 while (p[0] != 0)
6941 {
6942 if (p[1] == 0)
6943 error (_("fetch_register_using_p: early buf termination"));
6944
6945 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6946 p += 2;
6947 }
6948 regcache_raw_supply (regcache, reg->regnum, regp);
6949 return 1;
6950 }
6951
6952 /* Fetch the registers included in the target's 'g' packet. */
6953
6954 static int
6955 send_g_packet (void)
6956 {
6957 struct remote_state *rs = get_remote_state ();
6958 int buf_len;
6959
6960 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6961 remote_send (&rs->buf, &rs->buf_size);
6962
6963 /* We can get out of synch in various cases. If the first character
6964 in the buffer is not a hex character, assume that has happened
6965 and try to fetch another packet to read. */
6966 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6967 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6968 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6969 && rs->buf[0] != 'x') /* New: unavailable register value. */
6970 {
6971 if (remote_debug)
6972 fprintf_unfiltered (gdb_stdlog,
6973 "Bad register packet; fetching a new packet\n");
6974 getpkt (&rs->buf, &rs->buf_size, 0);
6975 }
6976
6977 buf_len = strlen (rs->buf);
6978
6979 /* Sanity check the received packet. */
6980 if (buf_len % 2 != 0)
6981 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6982
6983 return buf_len / 2;
6984 }
6985
6986 static void
6987 process_g_packet (struct regcache *regcache)
6988 {
6989 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6990 struct remote_state *rs = get_remote_state ();
6991 struct remote_arch_state *rsa = get_remote_arch_state ();
6992 int i, buf_len;
6993 char *p;
6994 char *regs;
6995
6996 buf_len = strlen (rs->buf);
6997
6998 /* Further sanity checks, with knowledge of the architecture. */
6999 if (buf_len > 2 * rsa->sizeof_g_packet)
7000 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7001
7002 /* Save the size of the packet sent to us by the target. It is used
7003 as a heuristic when determining the max size of packets that the
7004 target can safely receive. */
7005 if (rsa->actual_register_packet_size == 0)
7006 rsa->actual_register_packet_size = buf_len;
7007
7008 /* If this is smaller than we guessed the 'g' packet would be,
7009 update our records. A 'g' reply that doesn't include a register's
7010 value implies either that the register is not available, or that
7011 the 'p' packet must be used. */
7012 if (buf_len < 2 * rsa->sizeof_g_packet)
7013 {
7014 rsa->sizeof_g_packet = buf_len / 2;
7015
7016 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7017 {
7018 if (rsa->regs[i].pnum == -1)
7019 continue;
7020
7021 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7022 rsa->regs[i].in_g_packet = 0;
7023 else
7024 rsa->regs[i].in_g_packet = 1;
7025 }
7026 }
7027
7028 regs = (char *) alloca (rsa->sizeof_g_packet);
7029
7030 /* Unimplemented registers read as all bits zero. */
7031 memset (regs, 0, rsa->sizeof_g_packet);
7032
7033 /* Reply describes registers byte by byte, each byte encoded as two
7034 hex characters. Suck them all up, then supply them to the
7035 register cacheing/storage mechanism. */
7036
7037 p = rs->buf;
7038 for (i = 0; i < rsa->sizeof_g_packet; i++)
7039 {
7040 if (p[0] == 0 || p[1] == 0)
7041 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7042 internal_error (__FILE__, __LINE__,
7043 _("unexpected end of 'g' packet reply"));
7044
7045 if (p[0] == 'x' && p[1] == 'x')
7046 regs[i] = 0; /* 'x' */
7047 else
7048 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7049 p += 2;
7050 }
7051
7052 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7053 {
7054 struct packet_reg *r = &rsa->regs[i];
7055
7056 if (r->in_g_packet)
7057 {
7058 if (r->offset * 2 >= strlen (rs->buf))
7059 /* This shouldn't happen - we adjusted in_g_packet above. */
7060 internal_error (__FILE__, __LINE__,
7061 _("unexpected end of 'g' packet reply"));
7062 else if (rs->buf[r->offset * 2] == 'x')
7063 {
7064 gdb_assert (r->offset * 2 < strlen (rs->buf));
7065 /* The register isn't available, mark it as such (at
7066 the same time setting the value to zero). */
7067 regcache_raw_supply (regcache, r->regnum, NULL);
7068 }
7069 else
7070 regcache_raw_supply (regcache, r->regnum,
7071 regs + r->offset);
7072 }
7073 }
7074 }
7075
7076 static void
7077 fetch_registers_using_g (struct regcache *regcache)
7078 {
7079 send_g_packet ();
7080 process_g_packet (regcache);
7081 }
7082
7083 /* Make the remote selected traceframe match GDB's selected
7084 traceframe. */
7085
7086 static void
7087 set_remote_traceframe (void)
7088 {
7089 int newnum;
7090 struct remote_state *rs = get_remote_state ();
7091
7092 if (rs->remote_traceframe_number == get_traceframe_number ())
7093 return;
7094
7095 /* Avoid recursion, remote_trace_find calls us again. */
7096 rs->remote_traceframe_number = get_traceframe_number ();
7097
7098 newnum = target_trace_find (tfind_number,
7099 get_traceframe_number (), 0, 0, NULL);
7100
7101 /* Should not happen. If it does, all bets are off. */
7102 if (newnum != get_traceframe_number ())
7103 warning (_("could not set remote traceframe"));
7104 }
7105
7106 static void
7107 remote_fetch_registers (struct target_ops *ops,
7108 struct regcache *regcache, int regnum)
7109 {
7110 struct remote_arch_state *rsa = get_remote_arch_state ();
7111 int i;
7112
7113 set_remote_traceframe ();
7114 set_general_thread (inferior_ptid);
7115
7116 if (regnum >= 0)
7117 {
7118 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7119
7120 gdb_assert (reg != NULL);
7121
7122 /* If this register might be in the 'g' packet, try that first -
7123 we are likely to read more than one register. If this is the
7124 first 'g' packet, we might be overly optimistic about its
7125 contents, so fall back to 'p'. */
7126 if (reg->in_g_packet)
7127 {
7128 fetch_registers_using_g (regcache);
7129 if (reg->in_g_packet)
7130 return;
7131 }
7132
7133 if (fetch_register_using_p (regcache, reg))
7134 return;
7135
7136 /* This register is not available. */
7137 regcache_raw_supply (regcache, reg->regnum, NULL);
7138
7139 return;
7140 }
7141
7142 fetch_registers_using_g (regcache);
7143
7144 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7145 if (!rsa->regs[i].in_g_packet)
7146 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7147 {
7148 /* This register is not available. */
7149 regcache_raw_supply (regcache, i, NULL);
7150 }
7151 }
7152
7153 /* Prepare to store registers. Since we may send them all (using a
7154 'G' request), we have to read out the ones we don't want to change
7155 first. */
7156
7157 static void
7158 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7159 {
7160 struct remote_arch_state *rsa = get_remote_arch_state ();
7161 int i;
7162 gdb_byte buf[MAX_REGISTER_SIZE];
7163
7164 /* Make sure the entire registers array is valid. */
7165 switch (packet_support (PACKET_P))
7166 {
7167 case PACKET_DISABLE:
7168 case PACKET_SUPPORT_UNKNOWN:
7169 /* Make sure all the necessary registers are cached. */
7170 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7171 if (rsa->regs[i].in_g_packet)
7172 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7173 break;
7174 case PACKET_ENABLE:
7175 break;
7176 }
7177 }
7178
7179 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7180 packet was not recognized. */
7181
7182 static int
7183 store_register_using_P (const struct regcache *regcache,
7184 struct packet_reg *reg)
7185 {
7186 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7187 struct remote_state *rs = get_remote_state ();
7188 /* Try storing a single register. */
7189 char *buf = rs->buf;
7190 gdb_byte regp[MAX_REGISTER_SIZE];
7191 char *p;
7192
7193 if (packet_support (PACKET_P) == PACKET_DISABLE)
7194 return 0;
7195
7196 if (reg->pnum == -1)
7197 return 0;
7198
7199 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7200 p = buf + strlen (buf);
7201 regcache_raw_collect (regcache, reg->regnum, regp);
7202 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7203 putpkt (rs->buf);
7204 getpkt (&rs->buf, &rs->buf_size, 0);
7205
7206 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7207 {
7208 case PACKET_OK:
7209 return 1;
7210 case PACKET_ERROR:
7211 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7212 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7213 case PACKET_UNKNOWN:
7214 return 0;
7215 default:
7216 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7217 }
7218 }
7219
7220 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7221 contents of the register cache buffer. FIXME: ignores errors. */
7222
7223 static void
7224 store_registers_using_G (const struct regcache *regcache)
7225 {
7226 struct remote_state *rs = get_remote_state ();
7227 struct remote_arch_state *rsa = get_remote_arch_state ();
7228 gdb_byte *regs;
7229 char *p;
7230
7231 /* Extract all the registers in the regcache copying them into a
7232 local buffer. */
7233 {
7234 int i;
7235
7236 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7237 memset (regs, 0, rsa->sizeof_g_packet);
7238 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7239 {
7240 struct packet_reg *r = &rsa->regs[i];
7241
7242 if (r->in_g_packet)
7243 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7244 }
7245 }
7246
7247 /* Command describes registers byte by byte,
7248 each byte encoded as two hex characters. */
7249 p = rs->buf;
7250 *p++ = 'G';
7251 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7252 updated. */
7253 bin2hex (regs, p, rsa->sizeof_g_packet);
7254 putpkt (rs->buf);
7255 getpkt (&rs->buf, &rs->buf_size, 0);
7256 if (packet_check_result (rs->buf) == PACKET_ERROR)
7257 error (_("Could not write registers; remote failure reply '%s'"),
7258 rs->buf);
7259 }
7260
7261 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7262 of the register cache buffer. FIXME: ignores errors. */
7263
7264 static void
7265 remote_store_registers (struct target_ops *ops,
7266 struct regcache *regcache, int regnum)
7267 {
7268 struct remote_arch_state *rsa = get_remote_arch_state ();
7269 int i;
7270
7271 set_remote_traceframe ();
7272 set_general_thread (inferior_ptid);
7273
7274 if (regnum >= 0)
7275 {
7276 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7277
7278 gdb_assert (reg != NULL);
7279
7280 /* Always prefer to store registers using the 'P' packet if
7281 possible; we often change only a small number of registers.
7282 Sometimes we change a larger number; we'd need help from a
7283 higher layer to know to use 'G'. */
7284 if (store_register_using_P (regcache, reg))
7285 return;
7286
7287 /* For now, don't complain if we have no way to write the
7288 register. GDB loses track of unavailable registers too
7289 easily. Some day, this may be an error. We don't have
7290 any way to read the register, either... */
7291 if (!reg->in_g_packet)
7292 return;
7293
7294 store_registers_using_G (regcache);
7295 return;
7296 }
7297
7298 store_registers_using_G (regcache);
7299
7300 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7301 if (!rsa->regs[i].in_g_packet)
7302 if (!store_register_using_P (regcache, &rsa->regs[i]))
7303 /* See above for why we do not issue an error here. */
7304 continue;
7305 }
7306 \f
7307
7308 /* Return the number of hex digits in num. */
7309
7310 static int
7311 hexnumlen (ULONGEST num)
7312 {
7313 int i;
7314
7315 for (i = 0; num != 0; i++)
7316 num >>= 4;
7317
7318 return max (i, 1);
7319 }
7320
7321 /* Set BUF to the minimum number of hex digits representing NUM. */
7322
7323 static int
7324 hexnumstr (char *buf, ULONGEST num)
7325 {
7326 int len = hexnumlen (num);
7327
7328 return hexnumnstr (buf, num, len);
7329 }
7330
7331
7332 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7333
7334 static int
7335 hexnumnstr (char *buf, ULONGEST num, int width)
7336 {
7337 int i;
7338
7339 buf[width] = '\0';
7340
7341 for (i = width - 1; i >= 0; i--)
7342 {
7343 buf[i] = "0123456789abcdef"[(num & 0xf)];
7344 num >>= 4;
7345 }
7346
7347 return width;
7348 }
7349
7350 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7351
7352 static CORE_ADDR
7353 remote_address_masked (CORE_ADDR addr)
7354 {
7355 unsigned int address_size = remote_address_size;
7356
7357 /* If "remoteaddresssize" was not set, default to target address size. */
7358 if (!address_size)
7359 address_size = gdbarch_addr_bit (target_gdbarch ());
7360
7361 if (address_size > 0
7362 && address_size < (sizeof (ULONGEST) * 8))
7363 {
7364 /* Only create a mask when that mask can safely be constructed
7365 in a ULONGEST variable. */
7366 ULONGEST mask = 1;
7367
7368 mask = (mask << address_size) - 1;
7369 addr &= mask;
7370 }
7371 return addr;
7372 }
7373
7374 /* Determine whether the remote target supports binary downloading.
7375 This is accomplished by sending a no-op memory write of zero length
7376 to the target at the specified address. It does not suffice to send
7377 the whole packet, since many stubs strip the eighth bit and
7378 subsequently compute a wrong checksum, which causes real havoc with
7379 remote_write_bytes.
7380
7381 NOTE: This can still lose if the serial line is not eight-bit
7382 clean. In cases like this, the user should clear "remote
7383 X-packet". */
7384
7385 static void
7386 check_binary_download (CORE_ADDR addr)
7387 {
7388 struct remote_state *rs = get_remote_state ();
7389
7390 switch (packet_support (PACKET_X))
7391 {
7392 case PACKET_DISABLE:
7393 break;
7394 case PACKET_ENABLE:
7395 break;
7396 case PACKET_SUPPORT_UNKNOWN:
7397 {
7398 char *p;
7399
7400 p = rs->buf;
7401 *p++ = 'X';
7402 p += hexnumstr (p, (ULONGEST) addr);
7403 *p++ = ',';
7404 p += hexnumstr (p, (ULONGEST) 0);
7405 *p++ = ':';
7406 *p = '\0';
7407
7408 putpkt_binary (rs->buf, (int) (p - rs->buf));
7409 getpkt (&rs->buf, &rs->buf_size, 0);
7410
7411 if (rs->buf[0] == '\0')
7412 {
7413 if (remote_debug)
7414 fprintf_unfiltered (gdb_stdlog,
7415 "binary downloading NOT "
7416 "supported by target\n");
7417 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7418 }
7419 else
7420 {
7421 if (remote_debug)
7422 fprintf_unfiltered (gdb_stdlog,
7423 "binary downloading supported by target\n");
7424 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7425 }
7426 break;
7427 }
7428 }
7429 }
7430
7431 /* Helper function to resize the payload in order to try to get a good
7432 alignment. We try to write an amount of data such that the next write will
7433 start on an address aligned on REMOTE_ALIGN_WRITES. */
7434
7435 static int
7436 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7437 {
7438 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7439 }
7440
7441 /* Write memory data directly to the remote machine.
7442 This does not inform the data cache; the data cache uses this.
7443 HEADER is the starting part of the packet.
7444 MEMADDR is the address in the remote memory space.
7445 MYADDR is the address of the buffer in our space.
7446 LEN_UNITS is the number of addressable units to write.
7447 UNIT_SIZE is the length in bytes of an addressable unit.
7448 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7449 should send data as binary ('X'), or hex-encoded ('M').
7450
7451 The function creates packet of the form
7452 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7453
7454 where encoding of <DATA> is terminated by PACKET_FORMAT.
7455
7456 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7457 are omitted.
7458
7459 Return the transferred status, error or OK (an
7460 'enum target_xfer_status' value). Save the number of addressable units
7461 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7462
7463 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7464 exchange between gdb and the stub could look like (?? in place of the
7465 checksum):
7466
7467 -> $m1000,4#??
7468 <- aaaabbbbccccdddd
7469
7470 -> $M1000,3:eeeeffffeeee#??
7471 <- OK
7472
7473 -> $m1000,4#??
7474 <- eeeeffffeeeedddd */
7475
7476 static enum target_xfer_status
7477 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7478 const gdb_byte *myaddr, ULONGEST len_units,
7479 int unit_size, ULONGEST *xfered_len_units,
7480 char packet_format, int use_length)
7481 {
7482 struct remote_state *rs = get_remote_state ();
7483 char *p;
7484 char *plen = NULL;
7485 int plenlen = 0;
7486 int todo_units;
7487 int units_written;
7488 int payload_capacity_bytes;
7489 int payload_length_bytes;
7490
7491 if (packet_format != 'X' && packet_format != 'M')
7492 internal_error (__FILE__, __LINE__,
7493 _("remote_write_bytes_aux: bad packet format"));
7494
7495 if (len_units == 0)
7496 return TARGET_XFER_EOF;
7497
7498 payload_capacity_bytes = get_memory_write_packet_size ();
7499
7500 /* The packet buffer will be large enough for the payload;
7501 get_memory_packet_size ensures this. */
7502 rs->buf[0] = '\0';
7503
7504 /* Compute the size of the actual payload by subtracting out the
7505 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7506
7507 payload_capacity_bytes -= strlen ("$,:#NN");
7508 if (!use_length)
7509 /* The comma won't be used. */
7510 payload_capacity_bytes += 1;
7511 payload_capacity_bytes -= strlen (header);
7512 payload_capacity_bytes -= hexnumlen (memaddr);
7513
7514 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7515
7516 strcat (rs->buf, header);
7517 p = rs->buf + strlen (header);
7518
7519 /* Compute a best guess of the number of bytes actually transfered. */
7520 if (packet_format == 'X')
7521 {
7522 /* Best guess at number of bytes that will fit. */
7523 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7524 if (use_length)
7525 payload_capacity_bytes -= hexnumlen (todo_units);
7526 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7527 }
7528 else
7529 {
7530 /* Number of bytes that will fit. */
7531 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7532 if (use_length)
7533 payload_capacity_bytes -= hexnumlen (todo_units);
7534 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7535 }
7536
7537 if (todo_units <= 0)
7538 internal_error (__FILE__, __LINE__,
7539 _("minimum packet size too small to write data"));
7540
7541 /* If we already need another packet, then try to align the end
7542 of this packet to a useful boundary. */
7543 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7544 todo_units = align_for_efficient_write (todo_units, memaddr);
7545
7546 /* Append "<memaddr>". */
7547 memaddr = remote_address_masked (memaddr);
7548 p += hexnumstr (p, (ULONGEST) memaddr);
7549
7550 if (use_length)
7551 {
7552 /* Append ",". */
7553 *p++ = ',';
7554
7555 /* Append the length and retain its location and size. It may need to be
7556 adjusted once the packet body has been created. */
7557 plen = p;
7558 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7559 p += plenlen;
7560 }
7561
7562 /* Append ":". */
7563 *p++ = ':';
7564 *p = '\0';
7565
7566 /* Append the packet body. */
7567 if (packet_format == 'X')
7568 {
7569 /* Binary mode. Send target system values byte by byte, in
7570 increasing byte addresses. Only escape certain critical
7571 characters. */
7572 payload_length_bytes =
7573 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7574 &units_written, payload_capacity_bytes);
7575
7576 /* If not all TODO units fit, then we'll need another packet. Make
7577 a second try to keep the end of the packet aligned. Don't do
7578 this if the packet is tiny. */
7579 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7580 {
7581 int new_todo_units;
7582
7583 new_todo_units = align_for_efficient_write (units_written, memaddr);
7584
7585 if (new_todo_units != units_written)
7586 payload_length_bytes =
7587 remote_escape_output (myaddr, new_todo_units, unit_size,
7588 (gdb_byte *) p, &units_written,
7589 payload_capacity_bytes);
7590 }
7591
7592 p += payload_length_bytes;
7593 if (use_length && units_written < todo_units)
7594 {
7595 /* Escape chars have filled up the buffer prematurely,
7596 and we have actually sent fewer units than planned.
7597 Fix-up the length field of the packet. Use the same
7598 number of characters as before. */
7599 plen += hexnumnstr (plen, (ULONGEST) units_written,
7600 plenlen);
7601 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7602 }
7603 }
7604 else
7605 {
7606 /* Normal mode: Send target system values byte by byte, in
7607 increasing byte addresses. Each byte is encoded as a two hex
7608 value. */
7609 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7610 units_written = todo_units;
7611 }
7612
7613 putpkt_binary (rs->buf, (int) (p - rs->buf));
7614 getpkt (&rs->buf, &rs->buf_size, 0);
7615
7616 if (rs->buf[0] == 'E')
7617 return TARGET_XFER_E_IO;
7618
7619 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7620 send fewer units than we'd planned. */
7621 *xfered_len_units = (ULONGEST) units_written;
7622 return TARGET_XFER_OK;
7623 }
7624
7625 /* Write memory data directly to the remote machine.
7626 This does not inform the data cache; the data cache uses this.
7627 MEMADDR is the address in the remote memory space.
7628 MYADDR is the address of the buffer in our space.
7629 LEN is the number of bytes.
7630
7631 Return the transferred status, error or OK (an
7632 'enum target_xfer_status' value). Save the number of bytes
7633 transferred in *XFERED_LEN. Only transfer a single packet. */
7634
7635 static enum target_xfer_status
7636 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7637 int unit_size, ULONGEST *xfered_len)
7638 {
7639 char *packet_format = 0;
7640
7641 /* Check whether the target supports binary download. */
7642 check_binary_download (memaddr);
7643
7644 switch (packet_support (PACKET_X))
7645 {
7646 case PACKET_ENABLE:
7647 packet_format = "X";
7648 break;
7649 case PACKET_DISABLE:
7650 packet_format = "M";
7651 break;
7652 case PACKET_SUPPORT_UNKNOWN:
7653 internal_error (__FILE__, __LINE__,
7654 _("remote_write_bytes: bad internal state"));
7655 default:
7656 internal_error (__FILE__, __LINE__, _("bad switch"));
7657 }
7658
7659 return remote_write_bytes_aux (packet_format,
7660 memaddr, myaddr, len, unit_size, xfered_len,
7661 packet_format[0], 1);
7662 }
7663
7664 /* Read memory data directly from the remote machine.
7665 This does not use the data cache; the data cache uses this.
7666 MEMADDR is the address in the remote memory space.
7667 MYADDR is the address of the buffer in our space.
7668 LEN_UNITS is the number of addressable memory units to read..
7669 UNIT_SIZE is the length in bytes of an addressable unit.
7670
7671 Return the transferred status, error or OK (an
7672 'enum target_xfer_status' value). Save the number of bytes
7673 transferred in *XFERED_LEN_UNITS.
7674
7675 See the comment of remote_write_bytes_aux for an example of
7676 memory read/write exchange between gdb and the stub. */
7677
7678 static enum target_xfer_status
7679 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7680 int unit_size, ULONGEST *xfered_len_units)
7681 {
7682 struct remote_state *rs = get_remote_state ();
7683 int buf_size_bytes; /* Max size of packet output buffer. */
7684 char *p;
7685 int todo_units;
7686 int decoded_bytes;
7687
7688 buf_size_bytes = get_memory_read_packet_size ();
7689 /* The packet buffer will be large enough for the payload;
7690 get_memory_packet_size ensures this. */
7691
7692 /* Number of units that will fit. */
7693 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7694
7695 /* Construct "m"<memaddr>","<len>". */
7696 memaddr = remote_address_masked (memaddr);
7697 p = rs->buf;
7698 *p++ = 'm';
7699 p += hexnumstr (p, (ULONGEST) memaddr);
7700 *p++ = ',';
7701 p += hexnumstr (p, (ULONGEST) todo_units);
7702 *p = '\0';
7703 putpkt (rs->buf);
7704 getpkt (&rs->buf, &rs->buf_size, 0);
7705 if (rs->buf[0] == 'E'
7706 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7707 && rs->buf[3] == '\0')
7708 return TARGET_XFER_E_IO;
7709 /* Reply describes memory byte by byte, each byte encoded as two hex
7710 characters. */
7711 p = rs->buf;
7712 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7713 /* Return what we have. Let higher layers handle partial reads. */
7714 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7715 return TARGET_XFER_OK;
7716 }
7717
7718 /* Using the set of read-only target sections of remote, read live
7719 read-only memory.
7720
7721 For interface/parameters/return description see target.h,
7722 to_xfer_partial. */
7723
7724 static enum target_xfer_status
7725 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7726 ULONGEST memaddr, ULONGEST len,
7727 int unit_size, ULONGEST *xfered_len)
7728 {
7729 struct target_section *secp;
7730 struct target_section_table *table;
7731
7732 secp = target_section_by_addr (ops, memaddr);
7733 if (secp != NULL
7734 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7735 secp->the_bfd_section)
7736 & SEC_READONLY))
7737 {
7738 struct target_section *p;
7739 ULONGEST memend = memaddr + len;
7740
7741 table = target_get_section_table (ops);
7742
7743 for (p = table->sections; p < table->sections_end; p++)
7744 {
7745 if (memaddr >= p->addr)
7746 {
7747 if (memend <= p->endaddr)
7748 {
7749 /* Entire transfer is within this section. */
7750 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7751 xfered_len);
7752 }
7753 else if (memaddr >= p->endaddr)
7754 {
7755 /* This section ends before the transfer starts. */
7756 continue;
7757 }
7758 else
7759 {
7760 /* This section overlaps the transfer. Just do half. */
7761 len = p->endaddr - memaddr;
7762 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7763 xfered_len);
7764 }
7765 }
7766 }
7767 }
7768
7769 return TARGET_XFER_EOF;
7770 }
7771
7772 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7773 first if the requested memory is unavailable in traceframe.
7774 Otherwise, fall back to remote_read_bytes_1. */
7775
7776 static enum target_xfer_status
7777 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7778 gdb_byte *myaddr, ULONGEST len, int unit_size,
7779 ULONGEST *xfered_len)
7780 {
7781 if (len == 0)
7782 return TARGET_XFER_EOF;
7783
7784 if (get_traceframe_number () != -1)
7785 {
7786 VEC(mem_range_s) *available;
7787
7788 /* If we fail to get the set of available memory, then the
7789 target does not support querying traceframe info, and so we
7790 attempt reading from the traceframe anyway (assuming the
7791 target implements the old QTro packet then). */
7792 if (traceframe_available_memory (&available, memaddr, len))
7793 {
7794 struct cleanup *old_chain;
7795
7796 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7797
7798 if (VEC_empty (mem_range_s, available)
7799 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7800 {
7801 enum target_xfer_status res;
7802
7803 /* Don't read into the traceframe's available
7804 memory. */
7805 if (!VEC_empty (mem_range_s, available))
7806 {
7807 LONGEST oldlen = len;
7808
7809 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7810 gdb_assert (len <= oldlen);
7811 }
7812
7813 do_cleanups (old_chain);
7814
7815 /* This goes through the topmost target again. */
7816 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7817 len, unit_size, xfered_len);
7818 if (res == TARGET_XFER_OK)
7819 return TARGET_XFER_OK;
7820 else
7821 {
7822 /* No use trying further, we know some memory starting
7823 at MEMADDR isn't available. */
7824 *xfered_len = len;
7825 return TARGET_XFER_UNAVAILABLE;
7826 }
7827 }
7828
7829 /* Don't try to read more than how much is available, in
7830 case the target implements the deprecated QTro packet to
7831 cater for older GDBs (the target's knowledge of read-only
7832 sections may be outdated by now). */
7833 len = VEC_index (mem_range_s, available, 0)->length;
7834
7835 do_cleanups (old_chain);
7836 }
7837 }
7838
7839 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7840 }
7841
7842 \f
7843
7844 /* Sends a packet with content determined by the printf format string
7845 FORMAT and the remaining arguments, then gets the reply. Returns
7846 whether the packet was a success, a failure, or unknown. */
7847
7848 static enum packet_result remote_send_printf (const char *format, ...)
7849 ATTRIBUTE_PRINTF (1, 2);
7850
7851 static enum packet_result
7852 remote_send_printf (const char *format, ...)
7853 {
7854 struct remote_state *rs = get_remote_state ();
7855 int max_size = get_remote_packet_size ();
7856 va_list ap;
7857
7858 va_start (ap, format);
7859
7860 rs->buf[0] = '\0';
7861 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7862 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7863
7864 if (putpkt (rs->buf) < 0)
7865 error (_("Communication problem with target."));
7866
7867 rs->buf[0] = '\0';
7868 getpkt (&rs->buf, &rs->buf_size, 0);
7869
7870 return packet_check_result (rs->buf);
7871 }
7872
7873 static void
7874 restore_remote_timeout (void *p)
7875 {
7876 int value = *(int *)p;
7877
7878 remote_timeout = value;
7879 }
7880
7881 /* Flash writing can take quite some time. We'll set
7882 effectively infinite timeout for flash operations.
7883 In future, we'll need to decide on a better approach. */
7884 static const int remote_flash_timeout = 1000;
7885
7886 static void
7887 remote_flash_erase (struct target_ops *ops,
7888 ULONGEST address, LONGEST length)
7889 {
7890 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7891 int saved_remote_timeout = remote_timeout;
7892 enum packet_result ret;
7893 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7894 &saved_remote_timeout);
7895
7896 remote_timeout = remote_flash_timeout;
7897
7898 ret = remote_send_printf ("vFlashErase:%s,%s",
7899 phex (address, addr_size),
7900 phex (length, 4));
7901 switch (ret)
7902 {
7903 case PACKET_UNKNOWN:
7904 error (_("Remote target does not support flash erase"));
7905 case PACKET_ERROR:
7906 error (_("Error erasing flash with vFlashErase packet"));
7907 default:
7908 break;
7909 }
7910
7911 do_cleanups (back_to);
7912 }
7913
7914 static enum target_xfer_status
7915 remote_flash_write (struct target_ops *ops, ULONGEST address,
7916 ULONGEST length, ULONGEST *xfered_len,
7917 const gdb_byte *data)
7918 {
7919 int saved_remote_timeout = remote_timeout;
7920 enum target_xfer_status 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_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7926 xfered_len,'X', 0);
7927 do_cleanups (back_to);
7928
7929 return ret;
7930 }
7931
7932 static void
7933 remote_flash_done (struct target_ops *ops)
7934 {
7935 int saved_remote_timeout = remote_timeout;
7936 int ret;
7937 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7938 &saved_remote_timeout);
7939
7940 remote_timeout = remote_flash_timeout;
7941 ret = remote_send_printf ("vFlashDone");
7942 do_cleanups (back_to);
7943
7944 switch (ret)
7945 {
7946 case PACKET_UNKNOWN:
7947 error (_("Remote target does not support vFlashDone"));
7948 case PACKET_ERROR:
7949 error (_("Error finishing flash operation"));
7950 default:
7951 break;
7952 }
7953 }
7954
7955 static void
7956 remote_files_info (struct target_ops *ignore)
7957 {
7958 puts_filtered ("Debugging a target over a serial line.\n");
7959 }
7960 \f
7961 /* Stuff for dealing with the packets which are part of this protocol.
7962 See comment at top of file for details. */
7963
7964 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7965 error to higher layers. Called when a serial error is detected.
7966 The exception message is STRING, followed by a colon and a blank,
7967 the system error message for errno at function entry and final dot
7968 for output compatibility with throw_perror_with_name. */
7969
7970 static void
7971 unpush_and_perror (const char *string)
7972 {
7973 int saved_errno = errno;
7974
7975 remote_unpush_target ();
7976 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7977 safe_strerror (saved_errno));
7978 }
7979
7980 /* Read a single character from the remote end. */
7981
7982 static int
7983 readchar (int timeout)
7984 {
7985 int ch;
7986 struct remote_state *rs = get_remote_state ();
7987
7988 ch = serial_readchar (rs->remote_desc, timeout);
7989
7990 if (ch >= 0)
7991 return ch;
7992
7993 switch ((enum serial_rc) ch)
7994 {
7995 case SERIAL_EOF:
7996 remote_unpush_target ();
7997 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7998 /* no return */
7999 case SERIAL_ERROR:
8000 unpush_and_perror (_("Remote communication error. "
8001 "Target disconnected."));
8002 /* no return */
8003 case SERIAL_TIMEOUT:
8004 break;
8005 }
8006 return ch;
8007 }
8008
8009 /* Wrapper for serial_write that closes the target and throws if
8010 writing fails. */
8011
8012 static void
8013 remote_serial_write (const char *str, int len)
8014 {
8015 struct remote_state *rs = get_remote_state ();
8016
8017 if (serial_write (rs->remote_desc, str, len))
8018 {
8019 unpush_and_perror (_("Remote communication error. "
8020 "Target disconnected."));
8021 }
8022 }
8023
8024 /* Send the command in *BUF to the remote machine, and read the reply
8025 into *BUF. Report an error if we get an error reply. Resize
8026 *BUF using xrealloc if necessary to hold the result, and update
8027 *SIZEOF_BUF. */
8028
8029 static void
8030 remote_send (char **buf,
8031 long *sizeof_buf)
8032 {
8033 putpkt (*buf);
8034 getpkt (buf, sizeof_buf, 0);
8035
8036 if ((*buf)[0] == 'E')
8037 error (_("Remote failure reply: %s"), *buf);
8038 }
8039
8040 /* Return a pointer to an xmalloc'ed string representing an escaped
8041 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8042 etc. The caller is responsible for releasing the returned
8043 memory. */
8044
8045 static char *
8046 escape_buffer (const char *buf, int n)
8047 {
8048 struct cleanup *old_chain;
8049 struct ui_file *stb;
8050 char *str;
8051
8052 stb = mem_fileopen ();
8053 old_chain = make_cleanup_ui_file_delete (stb);
8054
8055 fputstrn_unfiltered (buf, n, '\\', stb);
8056 str = ui_file_xstrdup (stb, NULL);
8057 do_cleanups (old_chain);
8058 return str;
8059 }
8060
8061 /* Display a null-terminated packet on stdout, for debugging, using C
8062 string notation. */
8063
8064 static void
8065 print_packet (const char *buf)
8066 {
8067 puts_filtered ("\"");
8068 fputstr_filtered (buf, '"', gdb_stdout);
8069 puts_filtered ("\"");
8070 }
8071
8072 int
8073 putpkt (const char *buf)
8074 {
8075 return putpkt_binary (buf, strlen (buf));
8076 }
8077
8078 /* Send a packet to the remote machine, with error checking. The data
8079 of the packet is in BUF. The string in BUF can be at most
8080 get_remote_packet_size () - 5 to account for the $, # and checksum,
8081 and for a possible /0 if we are debugging (remote_debug) and want
8082 to print the sent packet as a string. */
8083
8084 static int
8085 putpkt_binary (const char *buf, int cnt)
8086 {
8087 struct remote_state *rs = get_remote_state ();
8088 int i;
8089 unsigned char csum = 0;
8090 char *buf2 = (char *) xmalloc (cnt + 6);
8091 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8092
8093 int ch;
8094 int tcount = 0;
8095 char *p;
8096 char *message;
8097
8098 /* Catch cases like trying to read memory or listing threads while
8099 we're waiting for a stop reply. The remote server wouldn't be
8100 ready to handle this request, so we'd hang and timeout. We don't
8101 have to worry about this in synchronous mode, because in that
8102 case it's not possible to issue a command while the target is
8103 running. This is not a problem in non-stop mode, because in that
8104 case, the stub is always ready to process serial input. */
8105 if (!target_is_non_stop_p ()
8106 && target_is_async_p ()
8107 && rs->waiting_for_stop_reply)
8108 {
8109 error (_("Cannot execute this command while the target is running.\n"
8110 "Use the \"interrupt\" command to stop the target\n"
8111 "and then try again."));
8112 }
8113
8114 /* We're sending out a new packet. Make sure we don't look at a
8115 stale cached response. */
8116 rs->cached_wait_status = 0;
8117
8118 /* Copy the packet into buffer BUF2, encapsulating it
8119 and giving it a checksum. */
8120
8121 p = buf2;
8122 *p++ = '$';
8123
8124 for (i = 0; i < cnt; i++)
8125 {
8126 csum += buf[i];
8127 *p++ = buf[i];
8128 }
8129 *p++ = '#';
8130 *p++ = tohex ((csum >> 4) & 0xf);
8131 *p++ = tohex (csum & 0xf);
8132
8133 /* Send it over and over until we get a positive ack. */
8134
8135 while (1)
8136 {
8137 int started_error_output = 0;
8138
8139 if (remote_debug)
8140 {
8141 struct cleanup *old_chain;
8142 char *str;
8143
8144 *p = '\0';
8145 str = escape_buffer (buf2, p - buf2);
8146 old_chain = make_cleanup (xfree, str);
8147 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8148 gdb_flush (gdb_stdlog);
8149 do_cleanups (old_chain);
8150 }
8151 remote_serial_write (buf2, p - buf2);
8152
8153 /* If this is a no acks version of the remote protocol, send the
8154 packet and move on. */
8155 if (rs->noack_mode)
8156 break;
8157
8158 /* Read until either a timeout occurs (-2) or '+' is read.
8159 Handle any notification that arrives in the mean time. */
8160 while (1)
8161 {
8162 ch = readchar (remote_timeout);
8163
8164 if (remote_debug)
8165 {
8166 switch (ch)
8167 {
8168 case '+':
8169 case '-':
8170 case SERIAL_TIMEOUT:
8171 case '$':
8172 case '%':
8173 if (started_error_output)
8174 {
8175 putchar_unfiltered ('\n');
8176 started_error_output = 0;
8177 }
8178 }
8179 }
8180
8181 switch (ch)
8182 {
8183 case '+':
8184 if (remote_debug)
8185 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8186 do_cleanups (old_chain);
8187 return 1;
8188 case '-':
8189 if (remote_debug)
8190 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8191 /* FALLTHROUGH */
8192 case SERIAL_TIMEOUT:
8193 tcount++;
8194 if (tcount > 3)
8195 {
8196 do_cleanups (old_chain);
8197 return 0;
8198 }
8199 break; /* Retransmit buffer. */
8200 case '$':
8201 {
8202 if (remote_debug)
8203 fprintf_unfiltered (gdb_stdlog,
8204 "Packet instead of Ack, ignoring it\n");
8205 /* It's probably an old response sent because an ACK
8206 was lost. Gobble up the packet and ack it so it
8207 doesn't get retransmitted when we resend this
8208 packet. */
8209 skip_frame ();
8210 remote_serial_write ("+", 1);
8211 continue; /* Now, go look for +. */
8212 }
8213
8214 case '%':
8215 {
8216 int val;
8217
8218 /* If we got a notification, handle it, and go back to looking
8219 for an ack. */
8220 /* We've found the start of a notification. Now
8221 collect the data. */
8222 val = read_frame (&rs->buf, &rs->buf_size);
8223 if (val >= 0)
8224 {
8225 if (remote_debug)
8226 {
8227 struct cleanup *old_chain;
8228 char *str;
8229
8230 str = escape_buffer (rs->buf, val);
8231 old_chain = make_cleanup (xfree, str);
8232 fprintf_unfiltered (gdb_stdlog,
8233 " Notification received: %s\n",
8234 str);
8235 do_cleanups (old_chain);
8236 }
8237 handle_notification (rs->notif_state, rs->buf);
8238 /* We're in sync now, rewait for the ack. */
8239 tcount = 0;
8240 }
8241 else
8242 {
8243 if (remote_debug)
8244 {
8245 if (!started_error_output)
8246 {
8247 started_error_output = 1;
8248 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8249 }
8250 fputc_unfiltered (ch & 0177, gdb_stdlog);
8251 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8252 }
8253 }
8254 continue;
8255 }
8256 /* fall-through */
8257 default:
8258 if (remote_debug)
8259 {
8260 if (!started_error_output)
8261 {
8262 started_error_output = 1;
8263 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8264 }
8265 fputc_unfiltered (ch & 0177, gdb_stdlog);
8266 }
8267 continue;
8268 }
8269 break; /* Here to retransmit. */
8270 }
8271
8272 #if 0
8273 /* This is wrong. If doing a long backtrace, the user should be
8274 able to get out next time we call QUIT, without anything as
8275 violent as interrupt_query. If we want to provide a way out of
8276 here without getting to the next QUIT, it should be based on
8277 hitting ^C twice as in remote_wait. */
8278 if (quit_flag)
8279 {
8280 quit_flag = 0;
8281 interrupt_query ();
8282 }
8283 #endif
8284 }
8285
8286 do_cleanups (old_chain);
8287 return 0;
8288 }
8289
8290 /* Come here after finding the start of a frame when we expected an
8291 ack. Do our best to discard the rest of this packet. */
8292
8293 static void
8294 skip_frame (void)
8295 {
8296 int c;
8297
8298 while (1)
8299 {
8300 c = readchar (remote_timeout);
8301 switch (c)
8302 {
8303 case SERIAL_TIMEOUT:
8304 /* Nothing we can do. */
8305 return;
8306 case '#':
8307 /* Discard the two bytes of checksum and stop. */
8308 c = readchar (remote_timeout);
8309 if (c >= 0)
8310 c = readchar (remote_timeout);
8311
8312 return;
8313 case '*': /* Run length encoding. */
8314 /* Discard the repeat count. */
8315 c = readchar (remote_timeout);
8316 if (c < 0)
8317 return;
8318 break;
8319 default:
8320 /* A regular character. */
8321 break;
8322 }
8323 }
8324 }
8325
8326 /* Come here after finding the start of the frame. Collect the rest
8327 into *BUF, verifying the checksum, length, and handling run-length
8328 compression. NUL terminate the buffer. If there is not enough room,
8329 expand *BUF using xrealloc.
8330
8331 Returns -1 on error, number of characters in buffer (ignoring the
8332 trailing NULL) on success. (could be extended to return one of the
8333 SERIAL status indications). */
8334
8335 static long
8336 read_frame (char **buf_p,
8337 long *sizeof_buf)
8338 {
8339 unsigned char csum;
8340 long bc;
8341 int c;
8342 char *buf = *buf_p;
8343 struct remote_state *rs = get_remote_state ();
8344
8345 csum = 0;
8346 bc = 0;
8347
8348 while (1)
8349 {
8350 c = readchar (remote_timeout);
8351 switch (c)
8352 {
8353 case SERIAL_TIMEOUT:
8354 if (remote_debug)
8355 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8356 return -1;
8357 case '$':
8358 if (remote_debug)
8359 fputs_filtered ("Saw new packet start in middle of old one\n",
8360 gdb_stdlog);
8361 return -1; /* Start a new packet, count retries. */
8362 case '#':
8363 {
8364 unsigned char pktcsum;
8365 int check_0 = 0;
8366 int check_1 = 0;
8367
8368 buf[bc] = '\0';
8369
8370 check_0 = readchar (remote_timeout);
8371 if (check_0 >= 0)
8372 check_1 = readchar (remote_timeout);
8373
8374 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8375 {
8376 if (remote_debug)
8377 fputs_filtered ("Timeout in checksum, retrying\n",
8378 gdb_stdlog);
8379 return -1;
8380 }
8381 else if (check_0 < 0 || check_1 < 0)
8382 {
8383 if (remote_debug)
8384 fputs_filtered ("Communication error in checksum\n",
8385 gdb_stdlog);
8386 return -1;
8387 }
8388
8389 /* Don't recompute the checksum; with no ack packets we
8390 don't have any way to indicate a packet retransmission
8391 is necessary. */
8392 if (rs->noack_mode)
8393 return bc;
8394
8395 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8396 if (csum == pktcsum)
8397 return bc;
8398
8399 if (remote_debug)
8400 {
8401 struct cleanup *old_chain;
8402 char *str;
8403
8404 str = escape_buffer (buf, bc);
8405 old_chain = make_cleanup (xfree, str);
8406 fprintf_unfiltered (gdb_stdlog,
8407 "Bad checksum, sentsum=0x%x, "
8408 "csum=0x%x, buf=%s\n",
8409 pktcsum, csum, str);
8410 do_cleanups (old_chain);
8411 }
8412 /* Number of characters in buffer ignoring trailing
8413 NULL. */
8414 return -1;
8415 }
8416 case '*': /* Run length encoding. */
8417 {
8418 int repeat;
8419
8420 csum += c;
8421 c = readchar (remote_timeout);
8422 csum += c;
8423 repeat = c - ' ' + 3; /* Compute repeat count. */
8424
8425 /* The character before ``*'' is repeated. */
8426
8427 if (repeat > 0 && repeat <= 255 && bc > 0)
8428 {
8429 if (bc + repeat - 1 >= *sizeof_buf - 1)
8430 {
8431 /* Make some more room in the buffer. */
8432 *sizeof_buf += repeat;
8433 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8434 buf = *buf_p;
8435 }
8436
8437 memset (&buf[bc], buf[bc - 1], repeat);
8438 bc += repeat;
8439 continue;
8440 }
8441
8442 buf[bc] = '\0';
8443 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8444 return -1;
8445 }
8446 default:
8447 if (bc >= *sizeof_buf - 1)
8448 {
8449 /* Make some more room in the buffer. */
8450 *sizeof_buf *= 2;
8451 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8452 buf = *buf_p;
8453 }
8454
8455 buf[bc++] = c;
8456 csum += c;
8457 continue;
8458 }
8459 }
8460 }
8461
8462 /* Read a packet from the remote machine, with error checking, and
8463 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8464 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8465 rather than timing out; this is used (in synchronous mode) to wait
8466 for a target that is is executing user code to stop. */
8467 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8468 don't have to change all the calls to getpkt to deal with the
8469 return value, because at the moment I don't know what the right
8470 thing to do it for those. */
8471 void
8472 getpkt (char **buf,
8473 long *sizeof_buf,
8474 int forever)
8475 {
8476 int timed_out;
8477
8478 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8479 }
8480
8481
8482 /* Read a packet from the remote machine, with error checking, and
8483 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8484 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8485 rather than timing out; this is used (in synchronous mode) to wait
8486 for a target that is is executing user code to stop. If FOREVER ==
8487 0, this function is allowed to time out gracefully and return an
8488 indication of this to the caller. Otherwise return the number of
8489 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8490 enough reason to return to the caller. *IS_NOTIF is an output
8491 boolean that indicates whether *BUF holds a notification or not
8492 (a regular packet). */
8493
8494 static int
8495 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8496 int expecting_notif, int *is_notif)
8497 {
8498 struct remote_state *rs = get_remote_state ();
8499 int c;
8500 int tries;
8501 int timeout;
8502 int val = -1;
8503
8504 /* We're reading a new response. Make sure we don't look at a
8505 previously cached response. */
8506 rs->cached_wait_status = 0;
8507
8508 strcpy (*buf, "timeout");
8509
8510 if (forever)
8511 timeout = watchdog > 0 ? watchdog : -1;
8512 else if (expecting_notif)
8513 timeout = 0; /* There should already be a char in the buffer. If
8514 not, bail out. */
8515 else
8516 timeout = remote_timeout;
8517
8518 #define MAX_TRIES 3
8519
8520 /* Process any number of notifications, and then return when
8521 we get a packet. */
8522 for (;;)
8523 {
8524 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8525 times. */
8526 for (tries = 1; tries <= MAX_TRIES; tries++)
8527 {
8528 /* This can loop forever if the remote side sends us
8529 characters continuously, but if it pauses, we'll get
8530 SERIAL_TIMEOUT from readchar because of timeout. Then
8531 we'll count that as a retry.
8532
8533 Note that even when forever is set, we will only wait
8534 forever prior to the start of a packet. After that, we
8535 expect characters to arrive at a brisk pace. They should
8536 show up within remote_timeout intervals. */
8537 do
8538 c = readchar (timeout);
8539 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8540
8541 if (c == SERIAL_TIMEOUT)
8542 {
8543 if (expecting_notif)
8544 return -1; /* Don't complain, it's normal to not get
8545 anything in this case. */
8546
8547 if (forever) /* Watchdog went off? Kill the target. */
8548 {
8549 QUIT;
8550 remote_unpush_target ();
8551 throw_error (TARGET_CLOSE_ERROR,
8552 _("Watchdog timeout has expired. "
8553 "Target detached."));
8554 }
8555 if (remote_debug)
8556 fputs_filtered ("Timed out.\n", gdb_stdlog);
8557 }
8558 else
8559 {
8560 /* We've found the start of a packet or notification.
8561 Now collect the data. */
8562 val = read_frame (buf, sizeof_buf);
8563 if (val >= 0)
8564 break;
8565 }
8566
8567 remote_serial_write ("-", 1);
8568 }
8569
8570 if (tries > MAX_TRIES)
8571 {
8572 /* We have tried hard enough, and just can't receive the
8573 packet/notification. Give up. */
8574 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8575
8576 /* Skip the ack char if we're in no-ack mode. */
8577 if (!rs->noack_mode)
8578 remote_serial_write ("+", 1);
8579 return -1;
8580 }
8581
8582 /* If we got an ordinary packet, return that to our caller. */
8583 if (c == '$')
8584 {
8585 if (remote_debug)
8586 {
8587 struct cleanup *old_chain;
8588 char *str;
8589
8590 str = escape_buffer (*buf, val);
8591 old_chain = make_cleanup (xfree, str);
8592 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8593 do_cleanups (old_chain);
8594 }
8595
8596 /* Skip the ack char if we're in no-ack mode. */
8597 if (!rs->noack_mode)
8598 remote_serial_write ("+", 1);
8599 if (is_notif != NULL)
8600 *is_notif = 0;
8601 return val;
8602 }
8603
8604 /* If we got a notification, handle it, and go back to looking
8605 for a packet. */
8606 else
8607 {
8608 gdb_assert (c == '%');
8609
8610 if (remote_debug)
8611 {
8612 struct cleanup *old_chain;
8613 char *str;
8614
8615 str = escape_buffer (*buf, val);
8616 old_chain = make_cleanup (xfree, str);
8617 fprintf_unfiltered (gdb_stdlog,
8618 " Notification received: %s\n",
8619 str);
8620 do_cleanups (old_chain);
8621 }
8622 if (is_notif != NULL)
8623 *is_notif = 1;
8624
8625 handle_notification (rs->notif_state, *buf);
8626
8627 /* Notifications require no acknowledgement. */
8628
8629 if (expecting_notif)
8630 return val;
8631 }
8632 }
8633 }
8634
8635 static int
8636 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8637 {
8638 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8639 }
8640
8641 static int
8642 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8643 int *is_notif)
8644 {
8645 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8646 is_notif);
8647 }
8648
8649 /* Check whether EVENT is a fork event for the process specified
8650 by the pid passed in DATA, and if it is, kill the fork child. */
8651
8652 static int
8653 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8654 QUEUE_ITER (stop_reply_p) *iter,
8655 stop_reply_p event,
8656 void *data)
8657 {
8658 struct queue_iter_param *param = (struct queue_iter_param *) data;
8659 int parent_pid = *(int *) param->input;
8660
8661 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8662 {
8663 struct remote_state *rs = get_remote_state ();
8664 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8665 int res;
8666
8667 res = remote_vkill (child_pid, rs);
8668 if (res != 0)
8669 error (_("Can't kill fork child process %d"), child_pid);
8670 }
8671
8672 return 1;
8673 }
8674
8675 /* Kill any new fork children of process PID that haven't been
8676 processed by follow_fork. */
8677
8678 static void
8679 kill_new_fork_children (int pid, struct remote_state *rs)
8680 {
8681 struct thread_info *thread;
8682 struct notif_client *notif = &notif_client_stop;
8683 struct queue_iter_param param;
8684
8685 /* Kill the fork child threads of any threads in process PID
8686 that are stopped at a fork event. */
8687 ALL_NON_EXITED_THREADS (thread)
8688 {
8689 struct target_waitstatus *ws = &thread->pending_follow;
8690
8691 if (is_pending_fork_parent (ws, pid, thread->ptid))
8692 {
8693 struct remote_state *rs = get_remote_state ();
8694 int child_pid = ptid_get_pid (ws->value.related_pid);
8695 int res;
8696
8697 res = remote_vkill (child_pid, rs);
8698 if (res != 0)
8699 error (_("Can't kill fork child process %d"), child_pid);
8700 }
8701 }
8702
8703 /* Check for any pending fork events (not reported or processed yet)
8704 in process PID and kill those fork child threads as well. */
8705 remote_notif_get_pending_events (notif);
8706 param.input = &pid;
8707 param.output = NULL;
8708 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8709 kill_child_of_pending_fork, &param);
8710 }
8711
8712 \f
8713 static void
8714 remote_kill (struct target_ops *ops)
8715 {
8716
8717 /* Catch errors so the user can quit from gdb even when we
8718 aren't on speaking terms with the remote system. */
8719 TRY
8720 {
8721 putpkt ("k");
8722 }
8723 CATCH (ex, RETURN_MASK_ERROR)
8724 {
8725 if (ex.error == TARGET_CLOSE_ERROR)
8726 {
8727 /* If we got an (EOF) error that caused the target
8728 to go away, then we're done, that's what we wanted.
8729 "k" is susceptible to cause a premature EOF, given
8730 that the remote server isn't actually required to
8731 reply to "k", and it can happen that it doesn't
8732 even get to reply ACK to the "k". */
8733 return;
8734 }
8735
8736 /* Otherwise, something went wrong. We didn't actually kill
8737 the target. Just propagate the exception, and let the
8738 user or higher layers decide what to do. */
8739 throw_exception (ex);
8740 }
8741 END_CATCH
8742
8743 /* We've killed the remote end, we get to mourn it. Since this is
8744 target remote, single-process, mourning the inferior also
8745 unpushes remote_ops. */
8746 target_mourn_inferior ();
8747 }
8748
8749 static int
8750 remote_vkill (int pid, struct remote_state *rs)
8751 {
8752 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8753 return -1;
8754
8755 /* Tell the remote target to detach. */
8756 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8757 putpkt (rs->buf);
8758 getpkt (&rs->buf, &rs->buf_size, 0);
8759
8760 switch (packet_ok (rs->buf,
8761 &remote_protocol_packets[PACKET_vKill]))
8762 {
8763 case PACKET_OK:
8764 return 0;
8765 case PACKET_ERROR:
8766 return 1;
8767 case PACKET_UNKNOWN:
8768 return -1;
8769 default:
8770 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8771 }
8772 }
8773
8774 static void
8775 extended_remote_kill (struct target_ops *ops)
8776 {
8777 int res;
8778 int pid = ptid_get_pid (inferior_ptid);
8779 struct remote_state *rs = get_remote_state ();
8780
8781 /* If we're stopped while forking and we haven't followed yet, kill the
8782 child task. We need to do this before killing the parent task
8783 because if this is a vfork then the parent will be sleeping. */
8784 kill_new_fork_children (pid, rs);
8785
8786 res = remote_vkill (pid, rs);
8787 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8788 {
8789 /* Don't try 'k' on a multi-process aware stub -- it has no way
8790 to specify the pid. */
8791
8792 putpkt ("k");
8793 #if 0
8794 getpkt (&rs->buf, &rs->buf_size, 0);
8795 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8796 res = 1;
8797 #else
8798 /* Don't wait for it to die. I'm not really sure it matters whether
8799 we do or not. For the existing stubs, kill is a noop. */
8800 res = 0;
8801 #endif
8802 }
8803
8804 if (res != 0)
8805 error (_("Can't kill process"));
8806
8807 target_mourn_inferior ();
8808 }
8809
8810 static void
8811 remote_mourn (struct target_ops *target)
8812 {
8813 unpush_target (target);
8814
8815 /* remote_close takes care of doing most of the clean up. */
8816 generic_mourn_inferior ();
8817 }
8818
8819 static void
8820 extended_remote_mourn (struct target_ops *target)
8821 {
8822 struct remote_state *rs = get_remote_state ();
8823
8824 /* In case we got here due to an error, but we're going to stay
8825 connected. */
8826 rs->waiting_for_stop_reply = 0;
8827
8828 /* If the current general thread belonged to the process we just
8829 detached from or has exited, the remote side current general
8830 thread becomes undefined. Considering a case like this:
8831
8832 - We just got here due to a detach.
8833 - The process that we're detaching from happens to immediately
8834 report a global breakpoint being hit in non-stop mode, in the
8835 same thread we had selected before.
8836 - GDB attaches to this process again.
8837 - This event happens to be the next event we handle.
8838
8839 GDB would consider that the current general thread didn't need to
8840 be set on the stub side (with Hg), since for all it knew,
8841 GENERAL_THREAD hadn't changed.
8842
8843 Notice that although in all-stop mode, the remote server always
8844 sets the current thread to the thread reporting the stop event,
8845 that doesn't happen in non-stop mode; in non-stop, the stub *must
8846 not* change the current thread when reporting a breakpoint hit,
8847 due to the decoupling of event reporting and event handling.
8848
8849 To keep things simple, we always invalidate our notion of the
8850 current thread. */
8851 record_currthread (rs, minus_one_ptid);
8852
8853 /* Unlike "target remote", we do not want to unpush the target; then
8854 the next time the user says "run", we won't be connected. */
8855
8856 /* Call common code to mark the inferior as not running. */
8857 generic_mourn_inferior ();
8858
8859 if (!have_inferiors ())
8860 {
8861 if (!remote_multi_process_p (rs))
8862 {
8863 /* Check whether the target is running now - some remote stubs
8864 automatically restart after kill. */
8865 putpkt ("?");
8866 getpkt (&rs->buf, &rs->buf_size, 0);
8867
8868 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8869 {
8870 /* Assume that the target has been restarted. Set
8871 inferior_ptid so that bits of core GDB realizes
8872 there's something here, e.g., so that the user can
8873 say "kill" again. */
8874 inferior_ptid = magic_null_ptid;
8875 }
8876 }
8877 }
8878 }
8879
8880 static int
8881 extended_remote_supports_disable_randomization (struct target_ops *self)
8882 {
8883 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8884 }
8885
8886 static void
8887 extended_remote_disable_randomization (int val)
8888 {
8889 struct remote_state *rs = get_remote_state ();
8890 char *reply;
8891
8892 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8893 val);
8894 putpkt (rs->buf);
8895 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8896 if (*reply == '\0')
8897 error (_("Target does not support QDisableRandomization."));
8898 if (strcmp (reply, "OK") != 0)
8899 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8900 }
8901
8902 static int
8903 extended_remote_run (char *args)
8904 {
8905 struct remote_state *rs = get_remote_state ();
8906 int len;
8907 const char *remote_exec_file = get_remote_exec_file ();
8908
8909 /* If the user has disabled vRun support, or we have detected that
8910 support is not available, do not try it. */
8911 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8912 return -1;
8913
8914 strcpy (rs->buf, "vRun;");
8915 len = strlen (rs->buf);
8916
8917 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8918 error (_("Remote file name too long for run packet"));
8919 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8920 strlen (remote_exec_file));
8921
8922 gdb_assert (args != NULL);
8923 if (*args)
8924 {
8925 struct cleanup *back_to;
8926 int i;
8927 char **argv;
8928
8929 argv = gdb_buildargv (args);
8930 back_to = make_cleanup_freeargv (argv);
8931 for (i = 0; argv[i] != NULL; i++)
8932 {
8933 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8934 error (_("Argument list too long for run packet"));
8935 rs->buf[len++] = ';';
8936 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8937 strlen (argv[i]));
8938 }
8939 do_cleanups (back_to);
8940 }
8941
8942 rs->buf[len++] = '\0';
8943
8944 putpkt (rs->buf);
8945 getpkt (&rs->buf, &rs->buf_size, 0);
8946
8947 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8948 {
8949 case PACKET_OK:
8950 /* We have a wait response. All is well. */
8951 return 0;
8952 case PACKET_UNKNOWN:
8953 return -1;
8954 case PACKET_ERROR:
8955 if (remote_exec_file[0] == '\0')
8956 error (_("Running the default executable on the remote target failed; "
8957 "try \"set remote exec-file\"?"));
8958 else
8959 error (_("Running \"%s\" on the remote target failed"),
8960 remote_exec_file);
8961 default:
8962 gdb_assert_not_reached (_("bad switch"));
8963 }
8964 }
8965
8966 /* In the extended protocol we want to be able to do things like
8967 "run" and have them basically work as expected. So we need
8968 a special create_inferior function. We support changing the
8969 executable file and the command line arguments, but not the
8970 environment. */
8971
8972 static void
8973 extended_remote_create_inferior (struct target_ops *ops,
8974 char *exec_file, char *args,
8975 char **env, int from_tty)
8976 {
8977 int run_worked;
8978 char *stop_reply;
8979 struct remote_state *rs = get_remote_state ();
8980 const char *remote_exec_file = get_remote_exec_file ();
8981
8982 /* If running asynchronously, register the target file descriptor
8983 with the event loop. */
8984 if (target_can_async_p ())
8985 target_async (1);
8986
8987 /* Disable address space randomization if requested (and supported). */
8988 if (extended_remote_supports_disable_randomization (ops))
8989 extended_remote_disable_randomization (disable_randomization);
8990
8991 /* Now restart the remote server. */
8992 run_worked = extended_remote_run (args) != -1;
8993 if (!run_worked)
8994 {
8995 /* vRun was not supported. Fail if we need it to do what the
8996 user requested. */
8997 if (remote_exec_file[0])
8998 error (_("Remote target does not support \"set remote exec-file\""));
8999 if (args[0])
9000 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9001
9002 /* Fall back to "R". */
9003 extended_remote_restart ();
9004 }
9005
9006 if (!have_inferiors ())
9007 {
9008 /* Clean up from the last time we ran, before we mark the target
9009 running again. This will mark breakpoints uninserted, and
9010 get_offsets may insert breakpoints. */
9011 init_thread_list ();
9012 init_wait_for_inferior ();
9013 }
9014
9015 /* vRun's success return is a stop reply. */
9016 stop_reply = run_worked ? rs->buf : NULL;
9017 add_current_inferior_and_thread (stop_reply);
9018
9019 /* Get updated offsets, if the stub uses qOffsets. */
9020 get_offsets ();
9021 }
9022 \f
9023
9024 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9025 the list of conditions (in agent expression bytecode format), if any, the
9026 target needs to evaluate. The output is placed into the packet buffer
9027 started from BUF and ended at BUF_END. */
9028
9029 static int
9030 remote_add_target_side_condition (struct gdbarch *gdbarch,
9031 struct bp_target_info *bp_tgt, char *buf,
9032 char *buf_end)
9033 {
9034 struct agent_expr *aexpr = NULL;
9035 int i, ix;
9036 char *pkt;
9037 char *buf_start = buf;
9038
9039 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9040 return 0;
9041
9042 buf += strlen (buf);
9043 xsnprintf (buf, buf_end - buf, "%s", ";");
9044 buf++;
9045
9046 /* Send conditions to the target and free the vector. */
9047 for (ix = 0;
9048 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9049 ix++)
9050 {
9051 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9052 buf += strlen (buf);
9053 for (i = 0; i < aexpr->len; ++i)
9054 buf = pack_hex_byte (buf, aexpr->buf[i]);
9055 *buf = '\0';
9056 }
9057 return 0;
9058 }
9059
9060 static void
9061 remote_add_target_side_commands (struct gdbarch *gdbarch,
9062 struct bp_target_info *bp_tgt, char *buf)
9063 {
9064 struct agent_expr *aexpr = NULL;
9065 int i, ix;
9066
9067 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9068 return;
9069
9070 buf += strlen (buf);
9071
9072 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9073 buf += strlen (buf);
9074
9075 /* Concatenate all the agent expressions that are commands into the
9076 cmds parameter. */
9077 for (ix = 0;
9078 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9079 ix++)
9080 {
9081 sprintf (buf, "X%x,", aexpr->len);
9082 buf += strlen (buf);
9083 for (i = 0; i < aexpr->len; ++i)
9084 buf = pack_hex_byte (buf, aexpr->buf[i]);
9085 *buf = '\0';
9086 }
9087 }
9088
9089 /* Insert a breakpoint. On targets that have software breakpoint
9090 support, we ask the remote target to do the work; on targets
9091 which don't, we insert a traditional memory breakpoint. */
9092
9093 static int
9094 remote_insert_breakpoint (struct target_ops *ops,
9095 struct gdbarch *gdbarch,
9096 struct bp_target_info *bp_tgt)
9097 {
9098 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9099 If it succeeds, then set the support to PACKET_ENABLE. If it
9100 fails, and the user has explicitly requested the Z support then
9101 report an error, otherwise, mark it disabled and go on. */
9102
9103 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9104 {
9105 CORE_ADDR addr = bp_tgt->reqstd_address;
9106 struct remote_state *rs;
9107 char *p, *endbuf;
9108 int bpsize;
9109 struct condition_list *cond = NULL;
9110
9111 /* Make sure the remote is pointing at the right process, if
9112 necessary. */
9113 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9114 set_general_process ();
9115
9116 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9117
9118 rs = get_remote_state ();
9119 p = rs->buf;
9120 endbuf = rs->buf + get_remote_packet_size ();
9121
9122 *(p++) = 'Z';
9123 *(p++) = '0';
9124 *(p++) = ',';
9125 addr = (ULONGEST) remote_address_masked (addr);
9126 p += hexnumstr (p, addr);
9127 xsnprintf (p, endbuf - p, ",%d", bpsize);
9128
9129 if (remote_supports_cond_breakpoints (ops))
9130 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9131
9132 if (remote_can_run_breakpoint_commands (ops))
9133 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9134
9135 putpkt (rs->buf);
9136 getpkt (&rs->buf, &rs->buf_size, 0);
9137
9138 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9139 {
9140 case PACKET_ERROR:
9141 return -1;
9142 case PACKET_OK:
9143 bp_tgt->placed_address = addr;
9144 bp_tgt->placed_size = bpsize;
9145 return 0;
9146 case PACKET_UNKNOWN:
9147 break;
9148 }
9149 }
9150
9151 /* If this breakpoint has target-side commands but this stub doesn't
9152 support Z0 packets, throw error. */
9153 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9154 throw_error (NOT_SUPPORTED_ERROR, _("\
9155 Target doesn't support breakpoints that have target side commands."));
9156
9157 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9158 }
9159
9160 static int
9161 remote_remove_breakpoint (struct target_ops *ops,
9162 struct gdbarch *gdbarch,
9163 struct bp_target_info *bp_tgt)
9164 {
9165 CORE_ADDR addr = bp_tgt->placed_address;
9166 struct remote_state *rs = get_remote_state ();
9167
9168 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9169 {
9170 char *p = rs->buf;
9171 char *endbuf = rs->buf + get_remote_packet_size ();
9172
9173 /* Make sure the remote is pointing at the right process, if
9174 necessary. */
9175 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9176 set_general_process ();
9177
9178 *(p++) = 'z';
9179 *(p++) = '0';
9180 *(p++) = ',';
9181
9182 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9183 p += hexnumstr (p, addr);
9184 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9185
9186 putpkt (rs->buf);
9187 getpkt (&rs->buf, &rs->buf_size, 0);
9188
9189 return (rs->buf[0] == 'E');
9190 }
9191
9192 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9193 }
9194
9195 static enum Z_packet_type
9196 watchpoint_to_Z_packet (int type)
9197 {
9198 switch (type)
9199 {
9200 case hw_write:
9201 return Z_PACKET_WRITE_WP;
9202 break;
9203 case hw_read:
9204 return Z_PACKET_READ_WP;
9205 break;
9206 case hw_access:
9207 return Z_PACKET_ACCESS_WP;
9208 break;
9209 default:
9210 internal_error (__FILE__, __LINE__,
9211 _("hw_bp_to_z: bad watchpoint type %d"), type);
9212 }
9213 }
9214
9215 static int
9216 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9217 enum target_hw_bp_type type, struct expression *cond)
9218 {
9219 struct remote_state *rs = get_remote_state ();
9220 char *endbuf = rs->buf + get_remote_packet_size ();
9221 char *p;
9222 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9223
9224 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9225 return 1;
9226
9227 /* Make sure the remote is pointing at the right process, if
9228 necessary. */
9229 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9230 set_general_process ();
9231
9232 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9233 p = strchr (rs->buf, '\0');
9234 addr = remote_address_masked (addr);
9235 p += hexnumstr (p, (ULONGEST) addr);
9236 xsnprintf (p, endbuf - p, ",%x", len);
9237
9238 putpkt (rs->buf);
9239 getpkt (&rs->buf, &rs->buf_size, 0);
9240
9241 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9242 {
9243 case PACKET_ERROR:
9244 return -1;
9245 case PACKET_UNKNOWN:
9246 return 1;
9247 case PACKET_OK:
9248 return 0;
9249 }
9250 internal_error (__FILE__, __LINE__,
9251 _("remote_insert_watchpoint: reached end of function"));
9252 }
9253
9254 static int
9255 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9256 CORE_ADDR start, int length)
9257 {
9258 CORE_ADDR diff = remote_address_masked (addr - start);
9259
9260 return diff < length;
9261 }
9262
9263
9264 static int
9265 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9266 enum target_hw_bp_type type, struct expression *cond)
9267 {
9268 struct remote_state *rs = get_remote_state ();
9269 char *endbuf = rs->buf + get_remote_packet_size ();
9270 char *p;
9271 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9272
9273 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9274 return -1;
9275
9276 /* Make sure the remote is pointing at the right process, if
9277 necessary. */
9278 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9279 set_general_process ();
9280
9281 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9282 p = strchr (rs->buf, '\0');
9283 addr = remote_address_masked (addr);
9284 p += hexnumstr (p, (ULONGEST) addr);
9285 xsnprintf (p, endbuf - p, ",%x", len);
9286 putpkt (rs->buf);
9287 getpkt (&rs->buf, &rs->buf_size, 0);
9288
9289 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9290 {
9291 case PACKET_ERROR:
9292 case PACKET_UNKNOWN:
9293 return -1;
9294 case PACKET_OK:
9295 return 0;
9296 }
9297 internal_error (__FILE__, __LINE__,
9298 _("remote_remove_watchpoint: reached end of function"));
9299 }
9300
9301
9302 int remote_hw_watchpoint_limit = -1;
9303 int remote_hw_watchpoint_length_limit = -1;
9304 int remote_hw_breakpoint_limit = -1;
9305
9306 static int
9307 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9308 CORE_ADDR addr, int len)
9309 {
9310 if (remote_hw_watchpoint_length_limit == 0)
9311 return 0;
9312 else if (remote_hw_watchpoint_length_limit < 0)
9313 return 1;
9314 else if (len <= remote_hw_watchpoint_length_limit)
9315 return 1;
9316 else
9317 return 0;
9318 }
9319
9320 static int
9321 remote_check_watch_resources (struct target_ops *self,
9322 enum bptype type, int cnt, int ot)
9323 {
9324 if (type == bp_hardware_breakpoint)
9325 {
9326 if (remote_hw_breakpoint_limit == 0)
9327 return 0;
9328 else if (remote_hw_breakpoint_limit < 0)
9329 return 1;
9330 else if (cnt <= remote_hw_breakpoint_limit)
9331 return 1;
9332 }
9333 else
9334 {
9335 if (remote_hw_watchpoint_limit == 0)
9336 return 0;
9337 else if (remote_hw_watchpoint_limit < 0)
9338 return 1;
9339 else if (ot)
9340 return -1;
9341 else if (cnt <= remote_hw_watchpoint_limit)
9342 return 1;
9343 }
9344 return -1;
9345 }
9346
9347 /* The to_stopped_by_sw_breakpoint method of target remote. */
9348
9349 static int
9350 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9351 {
9352 struct thread_info *thread = inferior_thread ();
9353
9354 return (thread->priv != NULL
9355 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9356 }
9357
9358 /* The to_supports_stopped_by_sw_breakpoint method of target
9359 remote. */
9360
9361 static int
9362 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9363 {
9364 struct remote_state *rs = get_remote_state ();
9365
9366 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9367 }
9368
9369 /* The to_stopped_by_hw_breakpoint method of target remote. */
9370
9371 static int
9372 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9373 {
9374 struct thread_info *thread = inferior_thread ();
9375
9376 return (thread->priv != NULL
9377 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9378 }
9379
9380 /* The to_supports_stopped_by_hw_breakpoint method of target
9381 remote. */
9382
9383 static int
9384 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9385 {
9386 struct remote_state *rs = get_remote_state ();
9387
9388 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9389 }
9390
9391 static int
9392 remote_stopped_by_watchpoint (struct target_ops *ops)
9393 {
9394 struct thread_info *thread = inferior_thread ();
9395
9396 return (thread->priv != NULL
9397 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9398 }
9399
9400 static int
9401 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9402 {
9403 struct thread_info *thread = inferior_thread ();
9404
9405 if (thread->priv != NULL
9406 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9407 {
9408 *addr_p = thread->priv->watch_data_address;
9409 return 1;
9410 }
9411
9412 return 0;
9413 }
9414
9415
9416 static int
9417 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9418 struct bp_target_info *bp_tgt)
9419 {
9420 CORE_ADDR addr = bp_tgt->reqstd_address;
9421 struct remote_state *rs;
9422 char *p, *endbuf;
9423 char *message;
9424 int bpsize;
9425
9426 /* The length field should be set to the size of a breakpoint
9427 instruction, even though we aren't inserting one ourselves. */
9428
9429 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9430
9431 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9432 return -1;
9433
9434 /* Make sure the remote is pointing at the right process, if
9435 necessary. */
9436 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9437 set_general_process ();
9438
9439 rs = get_remote_state ();
9440 p = rs->buf;
9441 endbuf = rs->buf + get_remote_packet_size ();
9442
9443 *(p++) = 'Z';
9444 *(p++) = '1';
9445 *(p++) = ',';
9446
9447 addr = remote_address_masked (addr);
9448 p += hexnumstr (p, (ULONGEST) addr);
9449 xsnprintf (p, endbuf - p, ",%x", bpsize);
9450
9451 if (remote_supports_cond_breakpoints (self))
9452 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9453
9454 if (remote_can_run_breakpoint_commands (self))
9455 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9456
9457 putpkt (rs->buf);
9458 getpkt (&rs->buf, &rs->buf_size, 0);
9459
9460 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9461 {
9462 case PACKET_ERROR:
9463 if (rs->buf[1] == '.')
9464 {
9465 message = strchr (rs->buf + 2, '.');
9466 if (message)
9467 error (_("Remote failure reply: %s"), message + 1);
9468 }
9469 return -1;
9470 case PACKET_UNKNOWN:
9471 return -1;
9472 case PACKET_OK:
9473 bp_tgt->placed_address = addr;
9474 bp_tgt->placed_size = bpsize;
9475 return 0;
9476 }
9477 internal_error (__FILE__, __LINE__,
9478 _("remote_insert_hw_breakpoint: reached end of function"));
9479 }
9480
9481
9482 static int
9483 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9484 struct bp_target_info *bp_tgt)
9485 {
9486 CORE_ADDR addr;
9487 struct remote_state *rs = get_remote_state ();
9488 char *p = rs->buf;
9489 char *endbuf = rs->buf + get_remote_packet_size ();
9490
9491 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9492 return -1;
9493
9494 /* Make sure the remote is pointing at the right process, if
9495 necessary. */
9496 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9497 set_general_process ();
9498
9499 *(p++) = 'z';
9500 *(p++) = '1';
9501 *(p++) = ',';
9502
9503 addr = remote_address_masked (bp_tgt->placed_address);
9504 p += hexnumstr (p, (ULONGEST) addr);
9505 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9506
9507 putpkt (rs->buf);
9508 getpkt (&rs->buf, &rs->buf_size, 0);
9509
9510 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9511 {
9512 case PACKET_ERROR:
9513 case PACKET_UNKNOWN:
9514 return -1;
9515 case PACKET_OK:
9516 return 0;
9517 }
9518 internal_error (__FILE__, __LINE__,
9519 _("remote_remove_hw_breakpoint: reached end of function"));
9520 }
9521
9522 /* Verify memory using the "qCRC:" request. */
9523
9524 static int
9525 remote_verify_memory (struct target_ops *ops,
9526 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9527 {
9528 struct remote_state *rs = get_remote_state ();
9529 unsigned long host_crc, target_crc;
9530 char *tmp;
9531
9532 /* It doesn't make sense to use qCRC if the remote target is
9533 connected but not running. */
9534 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9535 {
9536 enum packet_result result;
9537
9538 /* Make sure the remote is pointing at the right process. */
9539 set_general_process ();
9540
9541 /* FIXME: assumes lma can fit into long. */
9542 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9543 (long) lma, (long) size);
9544 putpkt (rs->buf);
9545
9546 /* Be clever; compute the host_crc before waiting for target
9547 reply. */
9548 host_crc = xcrc32 (data, size, 0xffffffff);
9549
9550 getpkt (&rs->buf, &rs->buf_size, 0);
9551
9552 result = packet_ok (rs->buf,
9553 &remote_protocol_packets[PACKET_qCRC]);
9554 if (result == PACKET_ERROR)
9555 return -1;
9556 else if (result == PACKET_OK)
9557 {
9558 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9559 target_crc = target_crc * 16 + fromhex (*tmp);
9560
9561 return (host_crc == target_crc);
9562 }
9563 }
9564
9565 return simple_verify_memory (ops, data, lma, size);
9566 }
9567
9568 /* compare-sections command
9569
9570 With no arguments, compares each loadable section in the exec bfd
9571 with the same memory range on the target, and reports mismatches.
9572 Useful for verifying the image on the target against the exec file. */
9573
9574 static void
9575 compare_sections_command (char *args, int from_tty)
9576 {
9577 asection *s;
9578 struct cleanup *old_chain;
9579 gdb_byte *sectdata;
9580 const char *sectname;
9581 bfd_size_type size;
9582 bfd_vma lma;
9583 int matched = 0;
9584 int mismatched = 0;
9585 int res;
9586 int read_only = 0;
9587
9588 if (!exec_bfd)
9589 error (_("command cannot be used without an exec file"));
9590
9591 /* Make sure the remote is pointing at the right process. */
9592 set_general_process ();
9593
9594 if (args != NULL && strcmp (args, "-r") == 0)
9595 {
9596 read_only = 1;
9597 args = NULL;
9598 }
9599
9600 for (s = exec_bfd->sections; s; s = s->next)
9601 {
9602 if (!(s->flags & SEC_LOAD))
9603 continue; /* Skip non-loadable section. */
9604
9605 if (read_only && (s->flags & SEC_READONLY) == 0)
9606 continue; /* Skip writeable sections */
9607
9608 size = bfd_get_section_size (s);
9609 if (size == 0)
9610 continue; /* Skip zero-length section. */
9611
9612 sectname = bfd_get_section_name (exec_bfd, s);
9613 if (args && strcmp (args, sectname) != 0)
9614 continue; /* Not the section selected by user. */
9615
9616 matched = 1; /* Do this section. */
9617 lma = s->lma;
9618
9619 sectdata = (gdb_byte *) xmalloc (size);
9620 old_chain = make_cleanup (xfree, sectdata);
9621 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9622
9623 res = target_verify_memory (sectdata, lma, size);
9624
9625 if (res == -1)
9626 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9627 paddress (target_gdbarch (), lma),
9628 paddress (target_gdbarch (), lma + size));
9629
9630 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9631 paddress (target_gdbarch (), lma),
9632 paddress (target_gdbarch (), lma + size));
9633 if (res)
9634 printf_filtered ("matched.\n");
9635 else
9636 {
9637 printf_filtered ("MIS-MATCHED!\n");
9638 mismatched++;
9639 }
9640
9641 do_cleanups (old_chain);
9642 }
9643 if (mismatched > 0)
9644 warning (_("One or more sections of the target image does not match\n\
9645 the loaded file\n"));
9646 if (args && !matched)
9647 printf_filtered (_("No loaded section named '%s'.\n"), args);
9648 }
9649
9650 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9651 into remote target. The number of bytes written to the remote
9652 target is returned, or -1 for error. */
9653
9654 static enum target_xfer_status
9655 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9656 const char *annex, const gdb_byte *writebuf,
9657 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9658 struct packet_config *packet)
9659 {
9660 int i, buf_len;
9661 ULONGEST n;
9662 struct remote_state *rs = get_remote_state ();
9663 int max_size = get_memory_write_packet_size ();
9664
9665 if (packet->support == PACKET_DISABLE)
9666 return TARGET_XFER_E_IO;
9667
9668 /* Insert header. */
9669 i = snprintf (rs->buf, max_size,
9670 "qXfer:%s:write:%s:%s:",
9671 object_name, annex ? annex : "",
9672 phex_nz (offset, sizeof offset));
9673 max_size -= (i + 1);
9674
9675 /* Escape as much data as fits into rs->buf. */
9676 buf_len = remote_escape_output
9677 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9678
9679 if (putpkt_binary (rs->buf, i + buf_len) < 0
9680 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9681 || packet_ok (rs->buf, packet) != PACKET_OK)
9682 return TARGET_XFER_E_IO;
9683
9684 unpack_varlen_hex (rs->buf, &n);
9685
9686 *xfered_len = n;
9687 return TARGET_XFER_OK;
9688 }
9689
9690 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9691 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9692 number of bytes read is returned, or 0 for EOF, or -1 for error.
9693 The number of bytes read may be less than LEN without indicating an
9694 EOF. PACKET is checked and updated to indicate whether the remote
9695 target supports this object. */
9696
9697 static enum target_xfer_status
9698 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9699 const char *annex,
9700 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9701 ULONGEST *xfered_len,
9702 struct packet_config *packet)
9703 {
9704 struct remote_state *rs = get_remote_state ();
9705 LONGEST i, n, packet_len;
9706
9707 if (packet->support == PACKET_DISABLE)
9708 return TARGET_XFER_E_IO;
9709
9710 /* Check whether we've cached an end-of-object packet that matches
9711 this request. */
9712 if (rs->finished_object)
9713 {
9714 if (strcmp (object_name, rs->finished_object) == 0
9715 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9716 && offset == rs->finished_offset)
9717 return TARGET_XFER_EOF;
9718
9719
9720 /* Otherwise, we're now reading something different. Discard
9721 the cache. */
9722 xfree (rs->finished_object);
9723 xfree (rs->finished_annex);
9724 rs->finished_object = NULL;
9725 rs->finished_annex = NULL;
9726 }
9727
9728 /* Request only enough to fit in a single packet. The actual data
9729 may not, since we don't know how much of it will need to be escaped;
9730 the target is free to respond with slightly less data. We subtract
9731 five to account for the response type and the protocol frame. */
9732 n = min (get_remote_packet_size () - 5, len);
9733 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9734 object_name, annex ? annex : "",
9735 phex_nz (offset, sizeof offset),
9736 phex_nz (n, sizeof n));
9737 i = putpkt (rs->buf);
9738 if (i < 0)
9739 return TARGET_XFER_E_IO;
9740
9741 rs->buf[0] = '\0';
9742 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9743 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9744 return TARGET_XFER_E_IO;
9745
9746 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9747 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9748
9749 /* 'm' means there is (or at least might be) more data after this
9750 batch. That does not make sense unless there's at least one byte
9751 of data in this reply. */
9752 if (rs->buf[0] == 'm' && packet_len == 1)
9753 error (_("Remote qXfer reply contained no data."));
9754
9755 /* Got some data. */
9756 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9757 packet_len - 1, readbuf, n);
9758
9759 /* 'l' is an EOF marker, possibly including a final block of data,
9760 or possibly empty. If we have the final block of a non-empty
9761 object, record this fact to bypass a subsequent partial read. */
9762 if (rs->buf[0] == 'l' && offset + i > 0)
9763 {
9764 rs->finished_object = xstrdup (object_name);
9765 rs->finished_annex = xstrdup (annex ? annex : "");
9766 rs->finished_offset = offset + i;
9767 }
9768
9769 if (i == 0)
9770 return TARGET_XFER_EOF;
9771 else
9772 {
9773 *xfered_len = i;
9774 return TARGET_XFER_OK;
9775 }
9776 }
9777
9778 static enum target_xfer_status
9779 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9780 const char *annex, gdb_byte *readbuf,
9781 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9782 ULONGEST *xfered_len)
9783 {
9784 struct remote_state *rs;
9785 int i;
9786 char *p2;
9787 char query_type;
9788 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9789
9790 set_remote_traceframe ();
9791 set_general_thread (inferior_ptid);
9792
9793 rs = get_remote_state ();
9794
9795 /* Handle memory using the standard memory routines. */
9796 if (object == TARGET_OBJECT_MEMORY)
9797 {
9798 /* If the remote target is connected but not running, we should
9799 pass this request down to a lower stratum (e.g. the executable
9800 file). */
9801 if (!target_has_execution)
9802 return TARGET_XFER_EOF;
9803
9804 if (writebuf != NULL)
9805 return remote_write_bytes (offset, writebuf, len, unit_size,
9806 xfered_len);
9807 else
9808 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9809 xfered_len);
9810 }
9811
9812 /* Handle SPU memory using qxfer packets. */
9813 if (object == TARGET_OBJECT_SPU)
9814 {
9815 if (readbuf)
9816 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9817 xfered_len, &remote_protocol_packets
9818 [PACKET_qXfer_spu_read]);
9819 else
9820 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9821 xfered_len, &remote_protocol_packets
9822 [PACKET_qXfer_spu_write]);
9823 }
9824
9825 /* Handle extra signal info using qxfer packets. */
9826 if (object == TARGET_OBJECT_SIGNAL_INFO)
9827 {
9828 if (readbuf)
9829 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9830 xfered_len, &remote_protocol_packets
9831 [PACKET_qXfer_siginfo_read]);
9832 else
9833 return remote_write_qxfer (ops, "siginfo", annex,
9834 writebuf, offset, len, xfered_len,
9835 &remote_protocol_packets
9836 [PACKET_qXfer_siginfo_write]);
9837 }
9838
9839 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9840 {
9841 if (readbuf)
9842 return remote_read_qxfer (ops, "statictrace", annex,
9843 readbuf, offset, len, xfered_len,
9844 &remote_protocol_packets
9845 [PACKET_qXfer_statictrace_read]);
9846 else
9847 return TARGET_XFER_E_IO;
9848 }
9849
9850 /* Only handle flash writes. */
9851 if (writebuf != NULL)
9852 {
9853 LONGEST xfered;
9854
9855 switch (object)
9856 {
9857 case TARGET_OBJECT_FLASH:
9858 return remote_flash_write (ops, offset, len, xfered_len,
9859 writebuf);
9860
9861 default:
9862 return TARGET_XFER_E_IO;
9863 }
9864 }
9865
9866 /* Map pre-existing objects onto letters. DO NOT do this for new
9867 objects!!! Instead specify new query packets. */
9868 switch (object)
9869 {
9870 case TARGET_OBJECT_AVR:
9871 query_type = 'R';
9872 break;
9873
9874 case TARGET_OBJECT_AUXV:
9875 gdb_assert (annex == NULL);
9876 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9877 xfered_len,
9878 &remote_protocol_packets[PACKET_qXfer_auxv]);
9879
9880 case TARGET_OBJECT_AVAILABLE_FEATURES:
9881 return remote_read_qxfer
9882 (ops, "features", annex, readbuf, offset, len, xfered_len,
9883 &remote_protocol_packets[PACKET_qXfer_features]);
9884
9885 case TARGET_OBJECT_LIBRARIES:
9886 return remote_read_qxfer
9887 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9888 &remote_protocol_packets[PACKET_qXfer_libraries]);
9889
9890 case TARGET_OBJECT_LIBRARIES_SVR4:
9891 return remote_read_qxfer
9892 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9893 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9894
9895 case TARGET_OBJECT_MEMORY_MAP:
9896 gdb_assert (annex == NULL);
9897 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9898 xfered_len,
9899 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9900
9901 case TARGET_OBJECT_OSDATA:
9902 /* Should only get here if we're connected. */
9903 gdb_assert (rs->remote_desc);
9904 return remote_read_qxfer
9905 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9906 &remote_protocol_packets[PACKET_qXfer_osdata]);
9907
9908 case TARGET_OBJECT_THREADS:
9909 gdb_assert (annex == NULL);
9910 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9911 xfered_len,
9912 &remote_protocol_packets[PACKET_qXfer_threads]);
9913
9914 case TARGET_OBJECT_TRACEFRAME_INFO:
9915 gdb_assert (annex == NULL);
9916 return remote_read_qxfer
9917 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9918 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9919
9920 case TARGET_OBJECT_FDPIC:
9921 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9922 xfered_len,
9923 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9924
9925 case TARGET_OBJECT_OPENVMS_UIB:
9926 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9927 xfered_len,
9928 &remote_protocol_packets[PACKET_qXfer_uib]);
9929
9930 case TARGET_OBJECT_BTRACE:
9931 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9932 xfered_len,
9933 &remote_protocol_packets[PACKET_qXfer_btrace]);
9934
9935 case TARGET_OBJECT_BTRACE_CONF:
9936 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9937 len, xfered_len,
9938 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9939
9940 case TARGET_OBJECT_EXEC_FILE:
9941 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9942 len, xfered_len,
9943 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9944
9945 default:
9946 return TARGET_XFER_E_IO;
9947 }
9948
9949 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9950 large enough let the caller deal with it. */
9951 if (len < get_remote_packet_size ())
9952 return TARGET_XFER_E_IO;
9953 len = get_remote_packet_size ();
9954
9955 /* Except for querying the minimum buffer size, target must be open. */
9956 if (!rs->remote_desc)
9957 error (_("remote query is only available after target open"));
9958
9959 gdb_assert (annex != NULL);
9960 gdb_assert (readbuf != NULL);
9961
9962 p2 = rs->buf;
9963 *p2++ = 'q';
9964 *p2++ = query_type;
9965
9966 /* We used one buffer char for the remote protocol q command and
9967 another for the query type. As the remote protocol encapsulation
9968 uses 4 chars plus one extra in case we are debugging
9969 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9970 string. */
9971 i = 0;
9972 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9973 {
9974 /* Bad caller may have sent forbidden characters. */
9975 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9976 *p2++ = annex[i];
9977 i++;
9978 }
9979 *p2 = '\0';
9980 gdb_assert (annex[i] == '\0');
9981
9982 i = putpkt (rs->buf);
9983 if (i < 0)
9984 return TARGET_XFER_E_IO;
9985
9986 getpkt (&rs->buf, &rs->buf_size, 0);
9987 strcpy ((char *) readbuf, rs->buf);
9988
9989 *xfered_len = strlen ((char *) readbuf);
9990 return TARGET_XFER_OK;
9991 }
9992
9993 static int
9994 remote_search_memory (struct target_ops* ops,
9995 CORE_ADDR start_addr, ULONGEST search_space_len,
9996 const gdb_byte *pattern, ULONGEST pattern_len,
9997 CORE_ADDR *found_addrp)
9998 {
9999 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10000 struct remote_state *rs = get_remote_state ();
10001 int max_size = get_memory_write_packet_size ();
10002 struct packet_config *packet =
10003 &remote_protocol_packets[PACKET_qSearch_memory];
10004 /* Number of packet bytes used to encode the pattern;
10005 this could be more than PATTERN_LEN due to escape characters. */
10006 int escaped_pattern_len;
10007 /* Amount of pattern that was encodable in the packet. */
10008 int used_pattern_len;
10009 int i;
10010 int found;
10011 ULONGEST found_addr;
10012
10013 /* Don't go to the target if we don't have to.
10014 This is done before checking packet->support to avoid the possibility that
10015 a success for this edge case means the facility works in general. */
10016 if (pattern_len > search_space_len)
10017 return 0;
10018 if (pattern_len == 0)
10019 {
10020 *found_addrp = start_addr;
10021 return 1;
10022 }
10023
10024 /* If we already know the packet isn't supported, fall back to the simple
10025 way of searching memory. */
10026
10027 if (packet_config_support (packet) == PACKET_DISABLE)
10028 {
10029 /* Target doesn't provided special support, fall back and use the
10030 standard support (copy memory and do the search here). */
10031 return simple_search_memory (ops, start_addr, search_space_len,
10032 pattern, pattern_len, found_addrp);
10033 }
10034
10035 /* Make sure the remote is pointing at the right process. */
10036 set_general_process ();
10037
10038 /* Insert header. */
10039 i = snprintf (rs->buf, max_size,
10040 "qSearch:memory:%s;%s;",
10041 phex_nz (start_addr, addr_size),
10042 phex_nz (search_space_len, sizeof (search_space_len)));
10043 max_size -= (i + 1);
10044
10045 /* Escape as much data as fits into rs->buf. */
10046 escaped_pattern_len =
10047 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10048 &used_pattern_len, max_size);
10049
10050 /* Bail if the pattern is too large. */
10051 if (used_pattern_len != pattern_len)
10052 error (_("Pattern is too large to transmit to remote target."));
10053
10054 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10055 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10056 || packet_ok (rs->buf, packet) != PACKET_OK)
10057 {
10058 /* The request may not have worked because the command is not
10059 supported. If so, fall back to the simple way. */
10060 if (packet->support == PACKET_DISABLE)
10061 {
10062 return simple_search_memory (ops, start_addr, search_space_len,
10063 pattern, pattern_len, found_addrp);
10064 }
10065 return -1;
10066 }
10067
10068 if (rs->buf[0] == '0')
10069 found = 0;
10070 else if (rs->buf[0] == '1')
10071 {
10072 found = 1;
10073 if (rs->buf[1] != ',')
10074 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10075 unpack_varlen_hex (rs->buf + 2, &found_addr);
10076 *found_addrp = found_addr;
10077 }
10078 else
10079 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10080
10081 return found;
10082 }
10083
10084 static void
10085 remote_rcmd (struct target_ops *self, const char *command,
10086 struct ui_file *outbuf)
10087 {
10088 struct remote_state *rs = get_remote_state ();
10089 char *p = rs->buf;
10090
10091 if (!rs->remote_desc)
10092 error (_("remote rcmd is only available after target open"));
10093
10094 /* Send a NULL command across as an empty command. */
10095 if (command == NULL)
10096 command = "";
10097
10098 /* The query prefix. */
10099 strcpy (rs->buf, "qRcmd,");
10100 p = strchr (rs->buf, '\0');
10101
10102 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10103 > get_remote_packet_size ())
10104 error (_("\"monitor\" command ``%s'' is too long."), command);
10105
10106 /* Encode the actual command. */
10107 bin2hex ((const gdb_byte *) command, p, strlen (command));
10108
10109 if (putpkt (rs->buf) < 0)
10110 error (_("Communication problem with target."));
10111
10112 /* get/display the response */
10113 while (1)
10114 {
10115 char *buf;
10116
10117 /* XXX - see also remote_get_noisy_reply(). */
10118 QUIT; /* Allow user to bail out with ^C. */
10119 rs->buf[0] = '\0';
10120 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10121 {
10122 /* Timeout. Continue to (try to) read responses.
10123 This is better than stopping with an error, assuming the stub
10124 is still executing the (long) monitor command.
10125 If needed, the user can interrupt gdb using C-c, obtaining
10126 an effect similar to stop on timeout. */
10127 continue;
10128 }
10129 buf = rs->buf;
10130 if (buf[0] == '\0')
10131 error (_("Target does not support this command."));
10132 if (buf[0] == 'O' && buf[1] != 'K')
10133 {
10134 remote_console_output (buf + 1); /* 'O' message from stub. */
10135 continue;
10136 }
10137 if (strcmp (buf, "OK") == 0)
10138 break;
10139 if (strlen (buf) == 3 && buf[0] == 'E'
10140 && isdigit (buf[1]) && isdigit (buf[2]))
10141 {
10142 error (_("Protocol error with Rcmd"));
10143 }
10144 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10145 {
10146 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10147
10148 fputc_unfiltered (c, outbuf);
10149 }
10150 break;
10151 }
10152 }
10153
10154 static VEC(mem_region_s) *
10155 remote_memory_map (struct target_ops *ops)
10156 {
10157 VEC(mem_region_s) *result = NULL;
10158 char *text = target_read_stralloc (&current_target,
10159 TARGET_OBJECT_MEMORY_MAP, NULL);
10160
10161 if (text)
10162 {
10163 struct cleanup *back_to = make_cleanup (xfree, text);
10164
10165 result = parse_memory_map (text);
10166 do_cleanups (back_to);
10167 }
10168
10169 return result;
10170 }
10171
10172 static void
10173 packet_command (char *args, int from_tty)
10174 {
10175 struct remote_state *rs = get_remote_state ();
10176
10177 if (!rs->remote_desc)
10178 error (_("command can only be used with remote target"));
10179
10180 if (!args)
10181 error (_("remote-packet command requires packet text as argument"));
10182
10183 puts_filtered ("sending: ");
10184 print_packet (args);
10185 puts_filtered ("\n");
10186 putpkt (args);
10187
10188 getpkt (&rs->buf, &rs->buf_size, 0);
10189 puts_filtered ("received: ");
10190 print_packet (rs->buf);
10191 puts_filtered ("\n");
10192 }
10193
10194 #if 0
10195 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10196
10197 static void display_thread_info (struct gdb_ext_thread_info *info);
10198
10199 static void threadset_test_cmd (char *cmd, int tty);
10200
10201 static void threadalive_test (char *cmd, int tty);
10202
10203 static void threadlist_test_cmd (char *cmd, int tty);
10204
10205 int get_and_display_threadinfo (threadref *ref);
10206
10207 static void threadinfo_test_cmd (char *cmd, int tty);
10208
10209 static int thread_display_step (threadref *ref, void *context);
10210
10211 static void threadlist_update_test_cmd (char *cmd, int tty);
10212
10213 static void init_remote_threadtests (void);
10214
10215 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10216
10217 static void
10218 threadset_test_cmd (char *cmd, int tty)
10219 {
10220 int sample_thread = SAMPLE_THREAD;
10221
10222 printf_filtered (_("Remote threadset test\n"));
10223 set_general_thread (sample_thread);
10224 }
10225
10226
10227 static void
10228 threadalive_test (char *cmd, int tty)
10229 {
10230 int sample_thread = SAMPLE_THREAD;
10231 int pid = ptid_get_pid (inferior_ptid);
10232 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10233
10234 if (remote_thread_alive (ptid))
10235 printf_filtered ("PASS: Thread alive test\n");
10236 else
10237 printf_filtered ("FAIL: Thread alive test\n");
10238 }
10239
10240 void output_threadid (char *title, threadref *ref);
10241
10242 void
10243 output_threadid (char *title, threadref *ref)
10244 {
10245 char hexid[20];
10246
10247 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10248 hexid[16] = 0;
10249 printf_filtered ("%s %s\n", title, (&hexid[0]));
10250 }
10251
10252 static void
10253 threadlist_test_cmd (char *cmd, int tty)
10254 {
10255 int startflag = 1;
10256 threadref nextthread;
10257 int done, result_count;
10258 threadref threadlist[3];
10259
10260 printf_filtered ("Remote Threadlist test\n");
10261 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10262 &result_count, &threadlist[0]))
10263 printf_filtered ("FAIL: threadlist test\n");
10264 else
10265 {
10266 threadref *scan = threadlist;
10267 threadref *limit = scan + result_count;
10268
10269 while (scan < limit)
10270 output_threadid (" thread ", scan++);
10271 }
10272 }
10273
10274 void
10275 display_thread_info (struct gdb_ext_thread_info *info)
10276 {
10277 output_threadid ("Threadid: ", &info->threadid);
10278 printf_filtered ("Name: %s\n ", info->shortname);
10279 printf_filtered ("State: %s\n", info->display);
10280 printf_filtered ("other: %s\n\n", info->more_display);
10281 }
10282
10283 int
10284 get_and_display_threadinfo (threadref *ref)
10285 {
10286 int result;
10287 int set;
10288 struct gdb_ext_thread_info threadinfo;
10289
10290 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10291 | TAG_MOREDISPLAY | TAG_DISPLAY;
10292 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10293 display_thread_info (&threadinfo);
10294 return result;
10295 }
10296
10297 static void
10298 threadinfo_test_cmd (char *cmd, int tty)
10299 {
10300 int athread = SAMPLE_THREAD;
10301 threadref thread;
10302 int set;
10303
10304 int_to_threadref (&thread, athread);
10305 printf_filtered ("Remote Threadinfo test\n");
10306 if (!get_and_display_threadinfo (&thread))
10307 printf_filtered ("FAIL cannot get thread info\n");
10308 }
10309
10310 static int
10311 thread_display_step (threadref *ref, void *context)
10312 {
10313 /* output_threadid(" threadstep ",ref); *//* simple test */
10314 return get_and_display_threadinfo (ref);
10315 }
10316
10317 static void
10318 threadlist_update_test_cmd (char *cmd, int tty)
10319 {
10320 printf_filtered ("Remote Threadlist update test\n");
10321 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10322 }
10323
10324 static void
10325 init_remote_threadtests (void)
10326 {
10327 add_com ("tlist", class_obscure, threadlist_test_cmd,
10328 _("Fetch and print the remote list of "
10329 "thread identifiers, one pkt only"));
10330 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10331 _("Fetch and display info about one thread"));
10332 add_com ("tset", class_obscure, threadset_test_cmd,
10333 _("Test setting to a different thread"));
10334 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10335 _("Iterate through updating all remote thread info"));
10336 add_com ("talive", class_obscure, threadalive_test,
10337 _(" Remote thread alive test "));
10338 }
10339
10340 #endif /* 0 */
10341
10342 /* Convert a thread ID to a string. Returns the string in a static
10343 buffer. */
10344
10345 static char *
10346 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10347 {
10348 static char buf[64];
10349 struct remote_state *rs = get_remote_state ();
10350
10351 if (ptid_equal (ptid, null_ptid))
10352 return normal_pid_to_str (ptid);
10353 else if (ptid_is_pid (ptid))
10354 {
10355 /* Printing an inferior target id. */
10356
10357 /* When multi-process extensions are off, there's no way in the
10358 remote protocol to know the remote process id, if there's any
10359 at all. There's one exception --- when we're connected with
10360 target extended-remote, and we manually attached to a process
10361 with "attach PID". We don't record anywhere a flag that
10362 allows us to distinguish that case from the case of
10363 connecting with extended-remote and the stub already being
10364 attached to a process, and reporting yes to qAttached, hence
10365 no smart special casing here. */
10366 if (!remote_multi_process_p (rs))
10367 {
10368 xsnprintf (buf, sizeof buf, "Remote target");
10369 return buf;
10370 }
10371
10372 return normal_pid_to_str (ptid);
10373 }
10374 else
10375 {
10376 if (ptid_equal (magic_null_ptid, ptid))
10377 xsnprintf (buf, sizeof buf, "Thread <main>");
10378 else if (rs->extended && remote_multi_process_p (rs))
10379 if (ptid_get_lwp (ptid) == 0)
10380 return normal_pid_to_str (ptid);
10381 else
10382 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10383 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10384 else
10385 xsnprintf (buf, sizeof buf, "Thread %ld",
10386 ptid_get_lwp (ptid));
10387 return buf;
10388 }
10389 }
10390
10391 /* Get the address of the thread local variable in OBJFILE which is
10392 stored at OFFSET within the thread local storage for thread PTID. */
10393
10394 static CORE_ADDR
10395 remote_get_thread_local_address (struct target_ops *ops,
10396 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10397 {
10398 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10399 {
10400 struct remote_state *rs = get_remote_state ();
10401 char *p = rs->buf;
10402 char *endp = rs->buf + get_remote_packet_size ();
10403 enum packet_result result;
10404
10405 strcpy (p, "qGetTLSAddr:");
10406 p += strlen (p);
10407 p = write_ptid (p, endp, ptid);
10408 *p++ = ',';
10409 p += hexnumstr (p, offset);
10410 *p++ = ',';
10411 p += hexnumstr (p, lm);
10412 *p++ = '\0';
10413
10414 putpkt (rs->buf);
10415 getpkt (&rs->buf, &rs->buf_size, 0);
10416 result = packet_ok (rs->buf,
10417 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10418 if (result == PACKET_OK)
10419 {
10420 ULONGEST result;
10421
10422 unpack_varlen_hex (rs->buf, &result);
10423 return result;
10424 }
10425 else if (result == PACKET_UNKNOWN)
10426 throw_error (TLS_GENERIC_ERROR,
10427 _("Remote target doesn't support qGetTLSAddr packet"));
10428 else
10429 throw_error (TLS_GENERIC_ERROR,
10430 _("Remote target failed to process qGetTLSAddr request"));
10431 }
10432 else
10433 throw_error (TLS_GENERIC_ERROR,
10434 _("TLS not supported or disabled on this target"));
10435 /* Not reached. */
10436 return 0;
10437 }
10438
10439 /* Provide thread local base, i.e. Thread Information Block address.
10440 Returns 1 if ptid is found and thread_local_base is non zero. */
10441
10442 static int
10443 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10444 {
10445 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10446 {
10447 struct remote_state *rs = get_remote_state ();
10448 char *p = rs->buf;
10449 char *endp = rs->buf + get_remote_packet_size ();
10450 enum packet_result result;
10451
10452 strcpy (p, "qGetTIBAddr:");
10453 p += strlen (p);
10454 p = write_ptid (p, endp, ptid);
10455 *p++ = '\0';
10456
10457 putpkt (rs->buf);
10458 getpkt (&rs->buf, &rs->buf_size, 0);
10459 result = packet_ok (rs->buf,
10460 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10461 if (result == PACKET_OK)
10462 {
10463 ULONGEST result;
10464
10465 unpack_varlen_hex (rs->buf, &result);
10466 if (addr)
10467 *addr = (CORE_ADDR) result;
10468 return 1;
10469 }
10470 else if (result == PACKET_UNKNOWN)
10471 error (_("Remote target doesn't support qGetTIBAddr packet"));
10472 else
10473 error (_("Remote target failed to process qGetTIBAddr request"));
10474 }
10475 else
10476 error (_("qGetTIBAddr not supported or disabled on this target"));
10477 /* Not reached. */
10478 return 0;
10479 }
10480
10481 /* Support for inferring a target description based on the current
10482 architecture and the size of a 'g' packet. While the 'g' packet
10483 can have any size (since optional registers can be left off the
10484 end), some sizes are easily recognizable given knowledge of the
10485 approximate architecture. */
10486
10487 struct remote_g_packet_guess
10488 {
10489 int bytes;
10490 const struct target_desc *tdesc;
10491 };
10492 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10493 DEF_VEC_O(remote_g_packet_guess_s);
10494
10495 struct remote_g_packet_data
10496 {
10497 VEC(remote_g_packet_guess_s) *guesses;
10498 };
10499
10500 static struct gdbarch_data *remote_g_packet_data_handle;
10501
10502 static void *
10503 remote_g_packet_data_init (struct obstack *obstack)
10504 {
10505 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10506 }
10507
10508 void
10509 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10510 const struct target_desc *tdesc)
10511 {
10512 struct remote_g_packet_data *data
10513 = ((struct remote_g_packet_data *)
10514 gdbarch_data (gdbarch, remote_g_packet_data_handle));
10515 struct remote_g_packet_guess new_guess, *guess;
10516 int ix;
10517
10518 gdb_assert (tdesc != NULL);
10519
10520 for (ix = 0;
10521 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10522 ix++)
10523 if (guess->bytes == bytes)
10524 internal_error (__FILE__, __LINE__,
10525 _("Duplicate g packet description added for size %d"),
10526 bytes);
10527
10528 new_guess.bytes = bytes;
10529 new_guess.tdesc = tdesc;
10530 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10531 }
10532
10533 /* Return 1 if remote_read_description would do anything on this target
10534 and architecture, 0 otherwise. */
10535
10536 static int
10537 remote_read_description_p (struct target_ops *target)
10538 {
10539 struct remote_g_packet_data *data
10540 = ((struct remote_g_packet_data *)
10541 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10542
10543 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10544 return 1;
10545
10546 return 0;
10547 }
10548
10549 static const struct target_desc *
10550 remote_read_description (struct target_ops *target)
10551 {
10552 struct remote_g_packet_data *data
10553 = ((struct remote_g_packet_data *)
10554 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10555
10556 /* Do not try this during initial connection, when we do not know
10557 whether there is a running but stopped thread. */
10558 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10559 return target->beneath->to_read_description (target->beneath);
10560
10561 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10562 {
10563 struct remote_g_packet_guess *guess;
10564 int ix;
10565 int bytes = send_g_packet ();
10566
10567 for (ix = 0;
10568 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10569 ix++)
10570 if (guess->bytes == bytes)
10571 return guess->tdesc;
10572
10573 /* We discard the g packet. A minor optimization would be to
10574 hold on to it, and fill the register cache once we have selected
10575 an architecture, but it's too tricky to do safely. */
10576 }
10577
10578 return target->beneath->to_read_description (target->beneath);
10579 }
10580
10581 /* Remote file transfer support. This is host-initiated I/O, not
10582 target-initiated; for target-initiated, see remote-fileio.c. */
10583
10584 /* If *LEFT is at least the length of STRING, copy STRING to
10585 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10586 decrease *LEFT. Otherwise raise an error. */
10587
10588 static void
10589 remote_buffer_add_string (char **buffer, int *left, char *string)
10590 {
10591 int len = strlen (string);
10592
10593 if (len > *left)
10594 error (_("Packet too long for target."));
10595
10596 memcpy (*buffer, string, len);
10597 *buffer += len;
10598 *left -= len;
10599
10600 /* NUL-terminate the buffer as a convenience, if there is
10601 room. */
10602 if (*left)
10603 **buffer = '\0';
10604 }
10605
10606 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10607 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10608 decrease *LEFT. Otherwise raise an error. */
10609
10610 static void
10611 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10612 int len)
10613 {
10614 if (2 * len > *left)
10615 error (_("Packet too long for target."));
10616
10617 bin2hex (bytes, *buffer, len);
10618 *buffer += 2 * len;
10619 *left -= 2 * len;
10620
10621 /* NUL-terminate the buffer as a convenience, if there is
10622 room. */
10623 if (*left)
10624 **buffer = '\0';
10625 }
10626
10627 /* If *LEFT is large enough, convert VALUE to hex and add it to
10628 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10629 decrease *LEFT. Otherwise raise an error. */
10630
10631 static void
10632 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10633 {
10634 int len = hexnumlen (value);
10635
10636 if (len > *left)
10637 error (_("Packet too long for target."));
10638
10639 hexnumstr (*buffer, value);
10640 *buffer += len;
10641 *left -= len;
10642
10643 /* NUL-terminate the buffer as a convenience, if there is
10644 room. */
10645 if (*left)
10646 **buffer = '\0';
10647 }
10648
10649 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10650 value, *REMOTE_ERRNO to the remote error number or zero if none
10651 was included, and *ATTACHMENT to point to the start of the annex
10652 if any. The length of the packet isn't needed here; there may
10653 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10654
10655 Return 0 if the packet could be parsed, -1 if it could not. If
10656 -1 is returned, the other variables may not be initialized. */
10657
10658 static int
10659 remote_hostio_parse_result (char *buffer, int *retcode,
10660 int *remote_errno, char **attachment)
10661 {
10662 char *p, *p2;
10663
10664 *remote_errno = 0;
10665 *attachment = NULL;
10666
10667 if (buffer[0] != 'F')
10668 return -1;
10669
10670 errno = 0;
10671 *retcode = strtol (&buffer[1], &p, 16);
10672 if (errno != 0 || p == &buffer[1])
10673 return -1;
10674
10675 /* Check for ",errno". */
10676 if (*p == ',')
10677 {
10678 errno = 0;
10679 *remote_errno = strtol (p + 1, &p2, 16);
10680 if (errno != 0 || p + 1 == p2)
10681 return -1;
10682 p = p2;
10683 }
10684
10685 /* Check for ";attachment". If there is no attachment, the
10686 packet should end here. */
10687 if (*p == ';')
10688 {
10689 *attachment = p + 1;
10690 return 0;
10691 }
10692 else if (*p == '\0')
10693 return 0;
10694 else
10695 return -1;
10696 }
10697
10698 /* Send a prepared I/O packet to the target and read its response.
10699 The prepared packet is in the global RS->BUF before this function
10700 is called, and the answer is there when we return.
10701
10702 COMMAND_BYTES is the length of the request to send, which may include
10703 binary data. WHICH_PACKET is the packet configuration to check
10704 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10705 is set to the error number and -1 is returned. Otherwise the value
10706 returned by the function is returned.
10707
10708 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10709 attachment is expected; an error will be reported if there's a
10710 mismatch. If one is found, *ATTACHMENT will be set to point into
10711 the packet buffer and *ATTACHMENT_LEN will be set to the
10712 attachment's length. */
10713
10714 static int
10715 remote_hostio_send_command (int command_bytes, int which_packet,
10716 int *remote_errno, char **attachment,
10717 int *attachment_len)
10718 {
10719 struct remote_state *rs = get_remote_state ();
10720 int ret, bytes_read;
10721 char *attachment_tmp;
10722
10723 if (!rs->remote_desc
10724 || packet_support (which_packet) == PACKET_DISABLE)
10725 {
10726 *remote_errno = FILEIO_ENOSYS;
10727 return -1;
10728 }
10729
10730 putpkt_binary (rs->buf, command_bytes);
10731 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10732
10733 /* If it timed out, something is wrong. Don't try to parse the
10734 buffer. */
10735 if (bytes_read < 0)
10736 {
10737 *remote_errno = FILEIO_EINVAL;
10738 return -1;
10739 }
10740
10741 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10742 {
10743 case PACKET_ERROR:
10744 *remote_errno = FILEIO_EINVAL;
10745 return -1;
10746 case PACKET_UNKNOWN:
10747 *remote_errno = FILEIO_ENOSYS;
10748 return -1;
10749 case PACKET_OK:
10750 break;
10751 }
10752
10753 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10754 &attachment_tmp))
10755 {
10756 *remote_errno = FILEIO_EINVAL;
10757 return -1;
10758 }
10759
10760 /* Make sure we saw an attachment if and only if we expected one. */
10761 if ((attachment_tmp == NULL && attachment != NULL)
10762 || (attachment_tmp != NULL && attachment == NULL))
10763 {
10764 *remote_errno = FILEIO_EINVAL;
10765 return -1;
10766 }
10767
10768 /* If an attachment was found, it must point into the packet buffer;
10769 work out how many bytes there were. */
10770 if (attachment_tmp != NULL)
10771 {
10772 *attachment = attachment_tmp;
10773 *attachment_len = bytes_read - (*attachment - rs->buf);
10774 }
10775
10776 return ret;
10777 }
10778
10779 /* Invalidate the readahead cache. */
10780
10781 static void
10782 readahead_cache_invalidate (void)
10783 {
10784 struct remote_state *rs = get_remote_state ();
10785
10786 rs->readahead_cache.fd = -1;
10787 }
10788
10789 /* Invalidate the readahead cache if it is holding data for FD. */
10790
10791 static void
10792 readahead_cache_invalidate_fd (int fd)
10793 {
10794 struct remote_state *rs = get_remote_state ();
10795
10796 if (rs->readahead_cache.fd == fd)
10797 rs->readahead_cache.fd = -1;
10798 }
10799
10800 /* Set the filesystem remote_hostio functions that take FILENAME
10801 arguments will use. Return 0 on success, or -1 if an error
10802 occurs (and set *REMOTE_ERRNO). */
10803
10804 static int
10805 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10806 {
10807 struct remote_state *rs = get_remote_state ();
10808 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10809 char *p = rs->buf;
10810 int left = get_remote_packet_size () - 1;
10811 char arg[9];
10812 int ret;
10813
10814 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10815 return 0;
10816
10817 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10818 return 0;
10819
10820 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10821
10822 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10823 remote_buffer_add_string (&p, &left, arg);
10824
10825 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10826 remote_errno, NULL, NULL);
10827
10828 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10829 return 0;
10830
10831 if (ret == 0)
10832 rs->fs_pid = required_pid;
10833
10834 return ret;
10835 }
10836
10837 /* Implementation of to_fileio_open. */
10838
10839 static int
10840 remote_hostio_open (struct target_ops *self,
10841 struct inferior *inf, const char *filename,
10842 int flags, int mode, int warn_if_slow,
10843 int *remote_errno)
10844 {
10845 struct remote_state *rs = get_remote_state ();
10846 char *p = rs->buf;
10847 int left = get_remote_packet_size () - 1;
10848
10849 if (warn_if_slow)
10850 {
10851 static int warning_issued = 0;
10852
10853 printf_unfiltered (_("Reading %s from remote target...\n"),
10854 filename);
10855
10856 if (!warning_issued)
10857 {
10858 warning (_("File transfers from remote targets can be slow."
10859 " Use \"set sysroot\" to access files locally"
10860 " instead."));
10861 warning_issued = 1;
10862 }
10863 }
10864
10865 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10866 return -1;
10867
10868 remote_buffer_add_string (&p, &left, "vFile:open:");
10869
10870 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10871 strlen (filename));
10872 remote_buffer_add_string (&p, &left, ",");
10873
10874 remote_buffer_add_int (&p, &left, flags);
10875 remote_buffer_add_string (&p, &left, ",");
10876
10877 remote_buffer_add_int (&p, &left, mode);
10878
10879 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10880 remote_errno, NULL, NULL);
10881 }
10882
10883 /* Implementation of to_fileio_pwrite. */
10884
10885 static int
10886 remote_hostio_pwrite (struct target_ops *self,
10887 int fd, const gdb_byte *write_buf, int len,
10888 ULONGEST offset, int *remote_errno)
10889 {
10890 struct remote_state *rs = get_remote_state ();
10891 char *p = rs->buf;
10892 int left = get_remote_packet_size ();
10893 int out_len;
10894
10895 readahead_cache_invalidate_fd (fd);
10896
10897 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10898
10899 remote_buffer_add_int (&p, &left, fd);
10900 remote_buffer_add_string (&p, &left, ",");
10901
10902 remote_buffer_add_int (&p, &left, offset);
10903 remote_buffer_add_string (&p, &left, ",");
10904
10905 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10906 get_remote_packet_size () - (p - rs->buf));
10907
10908 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10909 remote_errno, NULL, NULL);
10910 }
10911
10912 /* Helper for the implementation of to_fileio_pread. Read the file
10913 from the remote side with vFile:pread. */
10914
10915 static int
10916 remote_hostio_pread_vFile (struct target_ops *self,
10917 int fd, gdb_byte *read_buf, int len,
10918 ULONGEST offset, int *remote_errno)
10919 {
10920 struct remote_state *rs = get_remote_state ();
10921 char *p = rs->buf;
10922 char *attachment;
10923 int left = get_remote_packet_size ();
10924 int ret, attachment_len;
10925 int read_len;
10926
10927 remote_buffer_add_string (&p, &left, "vFile:pread:");
10928
10929 remote_buffer_add_int (&p, &left, fd);
10930 remote_buffer_add_string (&p, &left, ",");
10931
10932 remote_buffer_add_int (&p, &left, len);
10933 remote_buffer_add_string (&p, &left, ",");
10934
10935 remote_buffer_add_int (&p, &left, offset);
10936
10937 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10938 remote_errno, &attachment,
10939 &attachment_len);
10940
10941 if (ret < 0)
10942 return ret;
10943
10944 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10945 read_buf, len);
10946 if (read_len != ret)
10947 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10948
10949 return ret;
10950 }
10951
10952 /* Serve pread from the readahead cache. Returns number of bytes
10953 read, or 0 if the request can't be served from the cache. */
10954
10955 static int
10956 remote_hostio_pread_from_cache (struct remote_state *rs,
10957 int fd, gdb_byte *read_buf, size_t len,
10958 ULONGEST offset)
10959 {
10960 struct readahead_cache *cache = &rs->readahead_cache;
10961
10962 if (cache->fd == fd
10963 && cache->offset <= offset
10964 && offset < cache->offset + cache->bufsize)
10965 {
10966 ULONGEST max = cache->offset + cache->bufsize;
10967
10968 if (offset + len > max)
10969 len = max - offset;
10970
10971 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10972 return len;
10973 }
10974
10975 return 0;
10976 }
10977
10978 /* Implementation of to_fileio_pread. */
10979
10980 static int
10981 remote_hostio_pread (struct target_ops *self,
10982 int fd, gdb_byte *read_buf, int len,
10983 ULONGEST offset, int *remote_errno)
10984 {
10985 int ret;
10986 struct remote_state *rs = get_remote_state ();
10987 struct readahead_cache *cache = &rs->readahead_cache;
10988
10989 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10990 if (ret > 0)
10991 {
10992 cache->hit_count++;
10993
10994 if (remote_debug)
10995 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10996 pulongest (cache->hit_count));
10997 return ret;
10998 }
10999
11000 cache->miss_count++;
11001 if (remote_debug)
11002 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11003 pulongest (cache->miss_count));
11004
11005 cache->fd = fd;
11006 cache->offset = offset;
11007 cache->bufsize = get_remote_packet_size ();
11008 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11009
11010 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11011 cache->offset, remote_errno);
11012 if (ret <= 0)
11013 {
11014 readahead_cache_invalidate_fd (fd);
11015 return ret;
11016 }
11017
11018 cache->bufsize = ret;
11019 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11020 }
11021
11022 /* Implementation of to_fileio_close. */
11023
11024 static int
11025 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11026 {
11027 struct remote_state *rs = get_remote_state ();
11028 char *p = rs->buf;
11029 int left = get_remote_packet_size () - 1;
11030
11031 readahead_cache_invalidate_fd (fd);
11032
11033 remote_buffer_add_string (&p, &left, "vFile:close:");
11034
11035 remote_buffer_add_int (&p, &left, fd);
11036
11037 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11038 remote_errno, NULL, NULL);
11039 }
11040
11041 /* Implementation of to_fileio_unlink. */
11042
11043 static int
11044 remote_hostio_unlink (struct target_ops *self,
11045 struct inferior *inf, const char *filename,
11046 int *remote_errno)
11047 {
11048 struct remote_state *rs = get_remote_state ();
11049 char *p = rs->buf;
11050 int left = get_remote_packet_size () - 1;
11051
11052 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11053 return -1;
11054
11055 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11056
11057 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11058 strlen (filename));
11059
11060 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11061 remote_errno, NULL, NULL);
11062 }
11063
11064 /* Implementation of to_fileio_readlink. */
11065
11066 static char *
11067 remote_hostio_readlink (struct target_ops *self,
11068 struct inferior *inf, const char *filename,
11069 int *remote_errno)
11070 {
11071 struct remote_state *rs = get_remote_state ();
11072 char *p = rs->buf;
11073 char *attachment;
11074 int left = get_remote_packet_size ();
11075 int len, attachment_len;
11076 int read_len;
11077 char *ret;
11078
11079 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11080 return NULL;
11081
11082 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11083
11084 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11085 strlen (filename));
11086
11087 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11088 remote_errno, &attachment,
11089 &attachment_len);
11090
11091 if (len < 0)
11092 return NULL;
11093
11094 ret = (char *) xmalloc (len + 1);
11095
11096 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11097 (gdb_byte *) ret, len);
11098 if (read_len != len)
11099 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11100
11101 ret[len] = '\0';
11102 return ret;
11103 }
11104
11105 /* Implementation of to_fileio_fstat. */
11106
11107 static int
11108 remote_hostio_fstat (struct target_ops *self,
11109 int fd, struct stat *st,
11110 int *remote_errno)
11111 {
11112 struct remote_state *rs = get_remote_state ();
11113 char *p = rs->buf;
11114 int left = get_remote_packet_size ();
11115 int attachment_len, ret;
11116 char *attachment;
11117 struct fio_stat fst;
11118 int read_len;
11119
11120 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11121
11122 remote_buffer_add_int (&p, &left, fd);
11123
11124 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11125 remote_errno, &attachment,
11126 &attachment_len);
11127 if (ret < 0)
11128 {
11129 if (*remote_errno != FILEIO_ENOSYS)
11130 return ret;
11131
11132 /* Strictly we should return -1, ENOSYS here, but when
11133 "set sysroot remote:" was implemented in August 2008
11134 BFD's need for a stat function was sidestepped with
11135 this hack. This was not remedied until March 2015
11136 so we retain the previous behavior to avoid breaking
11137 compatibility.
11138
11139 Note that the memset is a March 2015 addition; older
11140 GDBs set st_size *and nothing else* so the structure
11141 would have garbage in all other fields. This might
11142 break something but retaining the previous behavior
11143 here would be just too wrong. */
11144
11145 memset (st, 0, sizeof (struct stat));
11146 st->st_size = INT_MAX;
11147 return 0;
11148 }
11149
11150 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11151 (gdb_byte *) &fst, sizeof (fst));
11152
11153 if (read_len != ret)
11154 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11155
11156 if (read_len != sizeof (fst))
11157 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11158 read_len, (int) sizeof (fst));
11159
11160 remote_fileio_to_host_stat (&fst, st);
11161
11162 return 0;
11163 }
11164
11165 /* Implementation of to_filesystem_is_local. */
11166
11167 static int
11168 remote_filesystem_is_local (struct target_ops *self)
11169 {
11170 /* Valgrind GDB presents itself as a remote target but works
11171 on the local filesystem: it does not implement remote get
11172 and users are not expected to set a sysroot. To handle
11173 this case we treat the remote filesystem as local if the
11174 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11175 does not support vFile:open. */
11176 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11177 {
11178 enum packet_support ps = packet_support (PACKET_vFile_open);
11179
11180 if (ps == PACKET_SUPPORT_UNKNOWN)
11181 {
11182 int fd, remote_errno;
11183
11184 /* Try opening a file to probe support. The supplied
11185 filename is irrelevant, we only care about whether
11186 the stub recognizes the packet or not. */
11187 fd = remote_hostio_open (self, NULL, "just probing",
11188 FILEIO_O_RDONLY, 0700, 0,
11189 &remote_errno);
11190
11191 if (fd >= 0)
11192 remote_hostio_close (self, fd, &remote_errno);
11193
11194 ps = packet_support (PACKET_vFile_open);
11195 }
11196
11197 if (ps == PACKET_DISABLE)
11198 {
11199 static int warning_issued = 0;
11200
11201 if (!warning_issued)
11202 {
11203 warning (_("remote target does not support file"
11204 " transfer, attempting to access files"
11205 " from local filesystem."));
11206 warning_issued = 1;
11207 }
11208
11209 return 1;
11210 }
11211 }
11212
11213 return 0;
11214 }
11215
11216 static int
11217 remote_fileio_errno_to_host (int errnum)
11218 {
11219 switch (errnum)
11220 {
11221 case FILEIO_EPERM:
11222 return EPERM;
11223 case FILEIO_ENOENT:
11224 return ENOENT;
11225 case FILEIO_EINTR:
11226 return EINTR;
11227 case FILEIO_EIO:
11228 return EIO;
11229 case FILEIO_EBADF:
11230 return EBADF;
11231 case FILEIO_EACCES:
11232 return EACCES;
11233 case FILEIO_EFAULT:
11234 return EFAULT;
11235 case FILEIO_EBUSY:
11236 return EBUSY;
11237 case FILEIO_EEXIST:
11238 return EEXIST;
11239 case FILEIO_ENODEV:
11240 return ENODEV;
11241 case FILEIO_ENOTDIR:
11242 return ENOTDIR;
11243 case FILEIO_EISDIR:
11244 return EISDIR;
11245 case FILEIO_EINVAL:
11246 return EINVAL;
11247 case FILEIO_ENFILE:
11248 return ENFILE;
11249 case FILEIO_EMFILE:
11250 return EMFILE;
11251 case FILEIO_EFBIG:
11252 return EFBIG;
11253 case FILEIO_ENOSPC:
11254 return ENOSPC;
11255 case FILEIO_ESPIPE:
11256 return ESPIPE;
11257 case FILEIO_EROFS:
11258 return EROFS;
11259 case FILEIO_ENOSYS:
11260 return ENOSYS;
11261 case FILEIO_ENAMETOOLONG:
11262 return ENAMETOOLONG;
11263 }
11264 return -1;
11265 }
11266
11267 static char *
11268 remote_hostio_error (int errnum)
11269 {
11270 int host_error = remote_fileio_errno_to_host (errnum);
11271
11272 if (host_error == -1)
11273 error (_("Unknown remote I/O error %d"), errnum);
11274 else
11275 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11276 }
11277
11278 static void
11279 remote_hostio_close_cleanup (void *opaque)
11280 {
11281 int fd = *(int *) opaque;
11282 int remote_errno;
11283
11284 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11285 }
11286
11287 void
11288 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11289 {
11290 struct cleanup *back_to, *close_cleanup;
11291 int retcode, fd, remote_errno, bytes, io_size;
11292 FILE *file;
11293 gdb_byte *buffer;
11294 int bytes_in_buffer;
11295 int saw_eof;
11296 ULONGEST offset;
11297 struct remote_state *rs = get_remote_state ();
11298
11299 if (!rs->remote_desc)
11300 error (_("command can only be used with remote target"));
11301
11302 file = gdb_fopen_cloexec (local_file, "rb");
11303 if (file == NULL)
11304 perror_with_name (local_file);
11305 back_to = make_cleanup_fclose (file);
11306
11307 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11308 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11309 | FILEIO_O_TRUNC),
11310 0700, 0, &remote_errno);
11311 if (fd == -1)
11312 remote_hostio_error (remote_errno);
11313
11314 /* Send up to this many bytes at once. They won't all fit in the
11315 remote packet limit, so we'll transfer slightly fewer. */
11316 io_size = get_remote_packet_size ();
11317 buffer = (gdb_byte *) xmalloc (io_size);
11318 make_cleanup (xfree, buffer);
11319
11320 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11321
11322 bytes_in_buffer = 0;
11323 saw_eof = 0;
11324 offset = 0;
11325 while (bytes_in_buffer || !saw_eof)
11326 {
11327 if (!saw_eof)
11328 {
11329 bytes = fread (buffer + bytes_in_buffer, 1,
11330 io_size - bytes_in_buffer,
11331 file);
11332 if (bytes == 0)
11333 {
11334 if (ferror (file))
11335 error (_("Error reading %s."), local_file);
11336 else
11337 {
11338 /* EOF. Unless there is something still in the
11339 buffer from the last iteration, we are done. */
11340 saw_eof = 1;
11341 if (bytes_in_buffer == 0)
11342 break;
11343 }
11344 }
11345 }
11346 else
11347 bytes = 0;
11348
11349 bytes += bytes_in_buffer;
11350 bytes_in_buffer = 0;
11351
11352 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11353 fd, buffer, bytes,
11354 offset, &remote_errno);
11355
11356 if (retcode < 0)
11357 remote_hostio_error (remote_errno);
11358 else if (retcode == 0)
11359 error (_("Remote write of %d bytes returned 0!"), bytes);
11360 else if (retcode < bytes)
11361 {
11362 /* Short write. Save the rest of the read data for the next
11363 write. */
11364 bytes_in_buffer = bytes - retcode;
11365 memmove (buffer, buffer + retcode, bytes_in_buffer);
11366 }
11367
11368 offset += retcode;
11369 }
11370
11371 discard_cleanups (close_cleanup);
11372 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11373 remote_hostio_error (remote_errno);
11374
11375 if (from_tty)
11376 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11377 do_cleanups (back_to);
11378 }
11379
11380 void
11381 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11382 {
11383 struct cleanup *back_to, *close_cleanup;
11384 int fd, remote_errno, bytes, io_size;
11385 FILE *file;
11386 gdb_byte *buffer;
11387 ULONGEST offset;
11388 struct remote_state *rs = get_remote_state ();
11389
11390 if (!rs->remote_desc)
11391 error (_("command can only be used with remote target"));
11392
11393 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11394 remote_file, FILEIO_O_RDONLY, 0, 0,
11395 &remote_errno);
11396 if (fd == -1)
11397 remote_hostio_error (remote_errno);
11398
11399 file = gdb_fopen_cloexec (local_file, "wb");
11400 if (file == NULL)
11401 perror_with_name (local_file);
11402 back_to = make_cleanup_fclose (file);
11403
11404 /* Send up to this many bytes at once. They won't all fit in the
11405 remote packet limit, so we'll transfer slightly fewer. */
11406 io_size = get_remote_packet_size ();
11407 buffer = (gdb_byte *) xmalloc (io_size);
11408 make_cleanup (xfree, buffer);
11409
11410 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11411
11412 offset = 0;
11413 while (1)
11414 {
11415 bytes = remote_hostio_pread (find_target_at (process_stratum),
11416 fd, buffer, io_size, offset, &remote_errno);
11417 if (bytes == 0)
11418 /* Success, but no bytes, means end-of-file. */
11419 break;
11420 if (bytes == -1)
11421 remote_hostio_error (remote_errno);
11422
11423 offset += bytes;
11424
11425 bytes = fwrite (buffer, 1, bytes, file);
11426 if (bytes == 0)
11427 perror_with_name (local_file);
11428 }
11429
11430 discard_cleanups (close_cleanup);
11431 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11432 remote_hostio_error (remote_errno);
11433
11434 if (from_tty)
11435 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11436 do_cleanups (back_to);
11437 }
11438
11439 void
11440 remote_file_delete (const char *remote_file, int from_tty)
11441 {
11442 int retcode, remote_errno;
11443 struct remote_state *rs = get_remote_state ();
11444
11445 if (!rs->remote_desc)
11446 error (_("command can only be used with remote target"));
11447
11448 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11449 NULL, remote_file, &remote_errno);
11450 if (retcode == -1)
11451 remote_hostio_error (remote_errno);
11452
11453 if (from_tty)
11454 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11455 }
11456
11457 static void
11458 remote_put_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 put"));
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 put"));
11470
11471 remote_file_put (argv[0], argv[1], from_tty);
11472
11473 do_cleanups (back_to);
11474 }
11475
11476 static void
11477 remote_get_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 get"));
11484
11485 argv = gdb_buildargv (args);
11486 back_to = make_cleanup_freeargv (argv);
11487 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11488 error (_("Invalid parameters to remote get"));
11489
11490 remote_file_get (argv[0], argv[1], from_tty);
11491
11492 do_cleanups (back_to);
11493 }
11494
11495 static void
11496 remote_delete_command (char *args, int from_tty)
11497 {
11498 struct cleanup *back_to;
11499 char **argv;
11500
11501 if (args == NULL)
11502 error_no_arg (_("file to delete"));
11503
11504 argv = gdb_buildargv (args);
11505 back_to = make_cleanup_freeargv (argv);
11506 if (argv[0] == NULL || argv[1] != NULL)
11507 error (_("Invalid parameters to remote delete"));
11508
11509 remote_file_delete (argv[0], from_tty);
11510
11511 do_cleanups (back_to);
11512 }
11513
11514 static void
11515 remote_command (char *args, int from_tty)
11516 {
11517 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11518 }
11519
11520 static int
11521 remote_can_execute_reverse (struct target_ops *self)
11522 {
11523 if (packet_support (PACKET_bs) == PACKET_ENABLE
11524 || packet_support (PACKET_bc) == PACKET_ENABLE)
11525 return 1;
11526 else
11527 return 0;
11528 }
11529
11530 static int
11531 remote_supports_non_stop (struct target_ops *self)
11532 {
11533 return 1;
11534 }
11535
11536 static int
11537 remote_supports_disable_randomization (struct target_ops *self)
11538 {
11539 /* Only supported in extended mode. */
11540 return 0;
11541 }
11542
11543 static int
11544 remote_supports_multi_process (struct target_ops *self)
11545 {
11546 struct remote_state *rs = get_remote_state ();
11547
11548 /* Only extended-remote handles being attached to multiple
11549 processes, even though plain remote can use the multi-process
11550 thread id extensions, so that GDB knows the target process's
11551 PID. */
11552 return rs->extended && remote_multi_process_p (rs);
11553 }
11554
11555 static int
11556 remote_supports_cond_tracepoints (void)
11557 {
11558 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11559 }
11560
11561 static int
11562 remote_supports_cond_breakpoints (struct target_ops *self)
11563 {
11564 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11565 }
11566
11567 static int
11568 remote_supports_fast_tracepoints (void)
11569 {
11570 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11571 }
11572
11573 static int
11574 remote_supports_static_tracepoints (void)
11575 {
11576 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11577 }
11578
11579 static int
11580 remote_supports_install_in_trace (void)
11581 {
11582 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11583 }
11584
11585 static int
11586 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11587 {
11588 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11589 == PACKET_ENABLE);
11590 }
11591
11592 static int
11593 remote_supports_string_tracing (struct target_ops *self)
11594 {
11595 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11596 }
11597
11598 static int
11599 remote_can_run_breakpoint_commands (struct target_ops *self)
11600 {
11601 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11602 }
11603
11604 static void
11605 remote_trace_init (struct target_ops *self)
11606 {
11607 putpkt ("QTinit");
11608 remote_get_noisy_reply (&target_buf, &target_buf_size);
11609 if (strcmp (target_buf, "OK") != 0)
11610 error (_("Target does not support this command."));
11611 }
11612
11613 static void free_actions_list (char **actions_list);
11614 static void free_actions_list_cleanup_wrapper (void *);
11615 static void
11616 free_actions_list_cleanup_wrapper (void *al)
11617 {
11618 free_actions_list ((char **) al);
11619 }
11620
11621 static void
11622 free_actions_list (char **actions_list)
11623 {
11624 int ndx;
11625
11626 if (actions_list == 0)
11627 return;
11628
11629 for (ndx = 0; actions_list[ndx]; ndx++)
11630 xfree (actions_list[ndx]);
11631
11632 xfree (actions_list);
11633 }
11634
11635 /* Recursive routine to walk through command list including loops, and
11636 download packets for each command. */
11637
11638 static void
11639 remote_download_command_source (int num, ULONGEST addr,
11640 struct command_line *cmds)
11641 {
11642 struct remote_state *rs = get_remote_state ();
11643 struct command_line *cmd;
11644
11645 for (cmd = cmds; cmd; cmd = cmd->next)
11646 {
11647 QUIT; /* Allow user to bail out with ^C. */
11648 strcpy (rs->buf, "QTDPsrc:");
11649 encode_source_string (num, addr, "cmd", cmd->line,
11650 rs->buf + strlen (rs->buf),
11651 rs->buf_size - strlen (rs->buf));
11652 putpkt (rs->buf);
11653 remote_get_noisy_reply (&target_buf, &target_buf_size);
11654 if (strcmp (target_buf, "OK"))
11655 warning (_("Target does not support source download."));
11656
11657 if (cmd->control_type == while_control
11658 || cmd->control_type == while_stepping_control)
11659 {
11660 remote_download_command_source (num, addr, *cmd->body_list);
11661
11662 QUIT; /* Allow user to bail out with ^C. */
11663 strcpy (rs->buf, "QTDPsrc:");
11664 encode_source_string (num, addr, "cmd", "end",
11665 rs->buf + strlen (rs->buf),
11666 rs->buf_size - strlen (rs->buf));
11667 putpkt (rs->buf);
11668 remote_get_noisy_reply (&target_buf, &target_buf_size);
11669 if (strcmp (target_buf, "OK"))
11670 warning (_("Target does not support source download."));
11671 }
11672 }
11673 }
11674
11675 static void
11676 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11677 {
11678 #define BUF_SIZE 2048
11679
11680 CORE_ADDR tpaddr;
11681 char addrbuf[40];
11682 char buf[BUF_SIZE];
11683 char **tdp_actions;
11684 char **stepping_actions;
11685 int ndx;
11686 struct cleanup *old_chain = NULL;
11687 struct agent_expr *aexpr;
11688 struct cleanup *aexpr_chain = NULL;
11689 char *pkt;
11690 struct breakpoint *b = loc->owner;
11691 struct tracepoint *t = (struct tracepoint *) b;
11692
11693 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11694 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11695 tdp_actions);
11696 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11697 stepping_actions);
11698
11699 tpaddr = loc->address;
11700 sprintf_vma (addrbuf, tpaddr);
11701 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11702 addrbuf, /* address */
11703 (b->enable_state == bp_enabled ? 'E' : 'D'),
11704 t->step_count, t->pass_count);
11705 /* Fast tracepoints are mostly handled by the target, but we can
11706 tell the target how big of an instruction block should be moved
11707 around. */
11708 if (b->type == bp_fast_tracepoint)
11709 {
11710 /* Only test for support at download time; we may not know
11711 target capabilities at definition time. */
11712 if (remote_supports_fast_tracepoints ())
11713 {
11714 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11715 NULL))
11716 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11717 gdb_insn_length (loc->gdbarch, tpaddr));
11718 else
11719 /* If it passed validation at definition but fails now,
11720 something is very wrong. */
11721 internal_error (__FILE__, __LINE__,
11722 _("Fast tracepoint not "
11723 "valid during download"));
11724 }
11725 else
11726 /* Fast tracepoints are functionally identical to regular
11727 tracepoints, so don't take lack of support as a reason to
11728 give up on the trace run. */
11729 warning (_("Target does not support fast tracepoints, "
11730 "downloading %d as regular tracepoint"), b->number);
11731 }
11732 else if (b->type == bp_static_tracepoint)
11733 {
11734 /* Only test for support at download time; we may not know
11735 target capabilities at definition time. */
11736 if (remote_supports_static_tracepoints ())
11737 {
11738 struct static_tracepoint_marker marker;
11739
11740 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11741 strcat (buf, ":S");
11742 else
11743 error (_("Static tracepoint not valid during download"));
11744 }
11745 else
11746 /* Fast tracepoints are functionally identical to regular
11747 tracepoints, so don't take lack of support as a reason
11748 to give up on the trace run. */
11749 error (_("Target does not support static tracepoints"));
11750 }
11751 /* If the tracepoint has a conditional, make it into an agent
11752 expression and append to the definition. */
11753 if (loc->cond)
11754 {
11755 /* Only test support at download time, we may not know target
11756 capabilities at definition time. */
11757 if (remote_supports_cond_tracepoints ())
11758 {
11759 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11760 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11761 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11762 aexpr->len);
11763 pkt = buf + strlen (buf);
11764 for (ndx = 0; ndx < aexpr->len; ++ndx)
11765 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11766 *pkt = '\0';
11767 do_cleanups (aexpr_chain);
11768 }
11769 else
11770 warning (_("Target does not support conditional tracepoints, "
11771 "ignoring tp %d cond"), b->number);
11772 }
11773
11774 if (b->commands || *default_collect)
11775 strcat (buf, "-");
11776 putpkt (buf);
11777 remote_get_noisy_reply (&target_buf, &target_buf_size);
11778 if (strcmp (target_buf, "OK"))
11779 error (_("Target does not support tracepoints."));
11780
11781 /* do_single_steps (t); */
11782 if (tdp_actions)
11783 {
11784 for (ndx = 0; tdp_actions[ndx]; ndx++)
11785 {
11786 QUIT; /* Allow user to bail out with ^C. */
11787 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11788 b->number, addrbuf, /* address */
11789 tdp_actions[ndx],
11790 ((tdp_actions[ndx + 1] || stepping_actions)
11791 ? '-' : 0));
11792 putpkt (buf);
11793 remote_get_noisy_reply (&target_buf,
11794 &target_buf_size);
11795 if (strcmp (target_buf, "OK"))
11796 error (_("Error on target while setting tracepoints."));
11797 }
11798 }
11799 if (stepping_actions)
11800 {
11801 for (ndx = 0; stepping_actions[ndx]; ndx++)
11802 {
11803 QUIT; /* Allow user to bail out with ^C. */
11804 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11805 b->number, addrbuf, /* address */
11806 ((ndx == 0) ? "S" : ""),
11807 stepping_actions[ndx],
11808 (stepping_actions[ndx + 1] ? "-" : ""));
11809 putpkt (buf);
11810 remote_get_noisy_reply (&target_buf,
11811 &target_buf_size);
11812 if (strcmp (target_buf, "OK"))
11813 error (_("Error on target while setting tracepoints."));
11814 }
11815 }
11816
11817 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11818 {
11819 if (b->location != NULL)
11820 {
11821 strcpy (buf, "QTDPsrc:");
11822 encode_source_string (b->number, loc->address, "at",
11823 event_location_to_string (b->location),
11824 buf + strlen (buf), 2048 - strlen (buf));
11825 putpkt (buf);
11826 remote_get_noisy_reply (&target_buf, &target_buf_size);
11827 if (strcmp (target_buf, "OK"))
11828 warning (_("Target does not support source download."));
11829 }
11830 if (b->cond_string)
11831 {
11832 strcpy (buf, "QTDPsrc:");
11833 encode_source_string (b->number, loc->address,
11834 "cond", b->cond_string, buf + strlen (buf),
11835 2048 - strlen (buf));
11836 putpkt (buf);
11837 remote_get_noisy_reply (&target_buf, &target_buf_size);
11838 if (strcmp (target_buf, "OK"))
11839 warning (_("Target does not support source download."));
11840 }
11841 remote_download_command_source (b->number, loc->address,
11842 breakpoint_commands (b));
11843 }
11844
11845 do_cleanups (old_chain);
11846 }
11847
11848 static int
11849 remote_can_download_tracepoint (struct target_ops *self)
11850 {
11851 struct remote_state *rs = get_remote_state ();
11852 struct trace_status *ts;
11853 int status;
11854
11855 /* Don't try to install tracepoints until we've relocated our
11856 symbols, and fetched and merged the target's tracepoint list with
11857 ours. */
11858 if (rs->starting_up)
11859 return 0;
11860
11861 ts = current_trace_status ();
11862 status = remote_get_trace_status (self, ts);
11863
11864 if (status == -1 || !ts->running_known || !ts->running)
11865 return 0;
11866
11867 /* If we are in a tracing experiment, but remote stub doesn't support
11868 installing tracepoint in trace, we have to return. */
11869 if (!remote_supports_install_in_trace ())
11870 return 0;
11871
11872 return 1;
11873 }
11874
11875
11876 static void
11877 remote_download_trace_state_variable (struct target_ops *self,
11878 struct trace_state_variable *tsv)
11879 {
11880 struct remote_state *rs = get_remote_state ();
11881 char *p;
11882
11883 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11884 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11885 tsv->builtin);
11886 p = rs->buf + strlen (rs->buf);
11887 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11888 error (_("Trace state variable name too long for tsv definition packet"));
11889 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11890 *p++ = '\0';
11891 putpkt (rs->buf);
11892 remote_get_noisy_reply (&target_buf, &target_buf_size);
11893 if (*target_buf == '\0')
11894 error (_("Target does not support this command."));
11895 if (strcmp (target_buf, "OK") != 0)
11896 error (_("Error on target while downloading trace state variable."));
11897 }
11898
11899 static void
11900 remote_enable_tracepoint (struct target_ops *self,
11901 struct bp_location *location)
11902 {
11903 struct remote_state *rs = get_remote_state ();
11904 char addr_buf[40];
11905
11906 sprintf_vma (addr_buf, location->address);
11907 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11908 location->owner->number, addr_buf);
11909 putpkt (rs->buf);
11910 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11911 if (*rs->buf == '\0')
11912 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11913 if (strcmp (rs->buf, "OK") != 0)
11914 error (_("Error on target while enabling tracepoint."));
11915 }
11916
11917 static void
11918 remote_disable_tracepoint (struct target_ops *self,
11919 struct bp_location *location)
11920 {
11921 struct remote_state *rs = get_remote_state ();
11922 char addr_buf[40];
11923
11924 sprintf_vma (addr_buf, location->address);
11925 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11926 location->owner->number, addr_buf);
11927 putpkt (rs->buf);
11928 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11929 if (*rs->buf == '\0')
11930 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11931 if (strcmp (rs->buf, "OK") != 0)
11932 error (_("Error on target while disabling tracepoint."));
11933 }
11934
11935 static void
11936 remote_trace_set_readonly_regions (struct target_ops *self)
11937 {
11938 asection *s;
11939 bfd *abfd = NULL;
11940 bfd_size_type size;
11941 bfd_vma vma;
11942 int anysecs = 0;
11943 int offset = 0;
11944
11945 if (!exec_bfd)
11946 return; /* No information to give. */
11947
11948 strcpy (target_buf, "QTro");
11949 offset = strlen (target_buf);
11950 for (s = exec_bfd->sections; s; s = s->next)
11951 {
11952 char tmp1[40], tmp2[40];
11953 int sec_length;
11954
11955 if ((s->flags & SEC_LOAD) == 0 ||
11956 /* (s->flags & SEC_CODE) == 0 || */
11957 (s->flags & SEC_READONLY) == 0)
11958 continue;
11959
11960 anysecs = 1;
11961 vma = bfd_get_section_vma (abfd, s);
11962 size = bfd_get_section_size (s);
11963 sprintf_vma (tmp1, vma);
11964 sprintf_vma (tmp2, vma + size);
11965 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11966 if (offset + sec_length + 1 > target_buf_size)
11967 {
11968 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
11969 warning (_("\
11970 Too many sections for read-only sections definition packet."));
11971 break;
11972 }
11973 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11974 tmp1, tmp2);
11975 offset += sec_length;
11976 }
11977 if (anysecs)
11978 {
11979 putpkt (target_buf);
11980 getpkt (&target_buf, &target_buf_size, 0);
11981 }
11982 }
11983
11984 static void
11985 remote_trace_start (struct target_ops *self)
11986 {
11987 putpkt ("QTStart");
11988 remote_get_noisy_reply (&target_buf, &target_buf_size);
11989 if (*target_buf == '\0')
11990 error (_("Target does not support this command."));
11991 if (strcmp (target_buf, "OK") != 0)
11992 error (_("Bogus reply from target: %s"), target_buf);
11993 }
11994
11995 static int
11996 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11997 {
11998 /* Initialize it just to avoid a GCC false warning. */
11999 char *p = NULL;
12000 /* FIXME we need to get register block size some other way. */
12001 extern int trace_regblock_size;
12002 enum packet_result result;
12003
12004 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12005 return -1;
12006
12007 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12008
12009 putpkt ("qTStatus");
12010
12011 TRY
12012 {
12013 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12014 }
12015 CATCH (ex, RETURN_MASK_ERROR)
12016 {
12017 if (ex.error != TARGET_CLOSE_ERROR)
12018 {
12019 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12020 return -1;
12021 }
12022 throw_exception (ex);
12023 }
12024 END_CATCH
12025
12026 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12027
12028 /* If the remote target doesn't do tracing, flag it. */
12029 if (result == PACKET_UNKNOWN)
12030 return -1;
12031
12032 /* We're working with a live target. */
12033 ts->filename = NULL;
12034
12035 if (*p++ != 'T')
12036 error (_("Bogus trace status reply from target: %s"), target_buf);
12037
12038 /* Function 'parse_trace_status' sets default value of each field of
12039 'ts' at first, so we don't have to do it here. */
12040 parse_trace_status (p, ts);
12041
12042 return ts->running;
12043 }
12044
12045 static void
12046 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12047 struct uploaded_tp *utp)
12048 {
12049 struct remote_state *rs = get_remote_state ();
12050 char *reply;
12051 struct bp_location *loc;
12052 struct tracepoint *tp = (struct tracepoint *) bp;
12053 size_t size = get_remote_packet_size ();
12054
12055 if (tp)
12056 {
12057 tp->base.hit_count = 0;
12058 tp->traceframe_usage = 0;
12059 for (loc = tp->base.loc; loc; loc = loc->next)
12060 {
12061 /* If the tracepoint was never downloaded, don't go asking for
12062 any status. */
12063 if (tp->number_on_target == 0)
12064 continue;
12065 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12066 phex_nz (loc->address, 0));
12067 putpkt (rs->buf);
12068 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12069 if (reply && *reply)
12070 {
12071 if (*reply == 'V')
12072 parse_tracepoint_status (reply + 1, bp, utp);
12073 }
12074 }
12075 }
12076 else if (utp)
12077 {
12078 utp->hit_count = 0;
12079 utp->traceframe_usage = 0;
12080 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12081 phex_nz (utp->addr, 0));
12082 putpkt (rs->buf);
12083 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12084 if (reply && *reply)
12085 {
12086 if (*reply == 'V')
12087 parse_tracepoint_status (reply + 1, bp, utp);
12088 }
12089 }
12090 }
12091
12092 static void
12093 remote_trace_stop (struct target_ops *self)
12094 {
12095 putpkt ("QTStop");
12096 remote_get_noisy_reply (&target_buf, &target_buf_size);
12097 if (*target_buf == '\0')
12098 error (_("Target does not support this command."));
12099 if (strcmp (target_buf, "OK") != 0)
12100 error (_("Bogus reply from target: %s"), target_buf);
12101 }
12102
12103 static int
12104 remote_trace_find (struct target_ops *self,
12105 enum trace_find_type type, int num,
12106 CORE_ADDR addr1, CORE_ADDR addr2,
12107 int *tpp)
12108 {
12109 struct remote_state *rs = get_remote_state ();
12110 char *endbuf = rs->buf + get_remote_packet_size ();
12111 char *p, *reply;
12112 int target_frameno = -1, target_tracept = -1;
12113
12114 /* Lookups other than by absolute frame number depend on the current
12115 trace selected, so make sure it is correct on the remote end
12116 first. */
12117 if (type != tfind_number)
12118 set_remote_traceframe ();
12119
12120 p = rs->buf;
12121 strcpy (p, "QTFrame:");
12122 p = strchr (p, '\0');
12123 switch (type)
12124 {
12125 case tfind_number:
12126 xsnprintf (p, endbuf - p, "%x", num);
12127 break;
12128 case tfind_pc:
12129 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12130 break;
12131 case tfind_tp:
12132 xsnprintf (p, endbuf - p, "tdp:%x", num);
12133 break;
12134 case tfind_range:
12135 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12136 phex_nz (addr2, 0));
12137 break;
12138 case tfind_outside:
12139 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12140 phex_nz (addr2, 0));
12141 break;
12142 default:
12143 error (_("Unknown trace find type %d"), type);
12144 }
12145
12146 putpkt (rs->buf);
12147 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12148 if (*reply == '\0')
12149 error (_("Target does not support this command."));
12150
12151 while (reply && *reply)
12152 switch (*reply)
12153 {
12154 case 'F':
12155 p = ++reply;
12156 target_frameno = (int) strtol (p, &reply, 16);
12157 if (reply == p)
12158 error (_("Unable to parse trace frame number"));
12159 /* Don't update our remote traceframe number cache on failure
12160 to select a remote traceframe. */
12161 if (target_frameno == -1)
12162 return -1;
12163 break;
12164 case 'T':
12165 p = ++reply;
12166 target_tracept = (int) strtol (p, &reply, 16);
12167 if (reply == p)
12168 error (_("Unable to parse tracepoint number"));
12169 break;
12170 case 'O': /* "OK"? */
12171 if (reply[1] == 'K' && reply[2] == '\0')
12172 reply += 2;
12173 else
12174 error (_("Bogus reply from target: %s"), reply);
12175 break;
12176 default:
12177 error (_("Bogus reply from target: %s"), reply);
12178 }
12179 if (tpp)
12180 *tpp = target_tracept;
12181
12182 rs->remote_traceframe_number = target_frameno;
12183 return target_frameno;
12184 }
12185
12186 static int
12187 remote_get_trace_state_variable_value (struct target_ops *self,
12188 int tsvnum, LONGEST *val)
12189 {
12190 struct remote_state *rs = get_remote_state ();
12191 char *reply;
12192 ULONGEST uval;
12193
12194 set_remote_traceframe ();
12195
12196 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12197 putpkt (rs->buf);
12198 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12199 if (reply && *reply)
12200 {
12201 if (*reply == 'V')
12202 {
12203 unpack_varlen_hex (reply + 1, &uval);
12204 *val = (LONGEST) uval;
12205 return 1;
12206 }
12207 }
12208 return 0;
12209 }
12210
12211 static int
12212 remote_save_trace_data (struct target_ops *self, const char *filename)
12213 {
12214 struct remote_state *rs = get_remote_state ();
12215 char *p, *reply;
12216
12217 p = rs->buf;
12218 strcpy (p, "QTSave:");
12219 p += strlen (p);
12220 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12221 error (_("Remote file name too long for trace save packet"));
12222 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12223 *p++ = '\0';
12224 putpkt (rs->buf);
12225 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12226 if (*reply == '\0')
12227 error (_("Target does not support this command."));
12228 if (strcmp (reply, "OK") != 0)
12229 error (_("Bogus reply from target: %s"), reply);
12230 return 0;
12231 }
12232
12233 /* This is basically a memory transfer, but needs to be its own packet
12234 because we don't know how the target actually organizes its trace
12235 memory, plus we want to be able to ask for as much as possible, but
12236 not be unhappy if we don't get as much as we ask for. */
12237
12238 static LONGEST
12239 remote_get_raw_trace_data (struct target_ops *self,
12240 gdb_byte *buf, ULONGEST offset, LONGEST len)
12241 {
12242 struct remote_state *rs = get_remote_state ();
12243 char *reply;
12244 char *p;
12245 int rslt;
12246
12247 p = rs->buf;
12248 strcpy (p, "qTBuffer:");
12249 p += strlen (p);
12250 p += hexnumstr (p, offset);
12251 *p++ = ',';
12252 p += hexnumstr (p, len);
12253 *p++ = '\0';
12254
12255 putpkt (rs->buf);
12256 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12257 if (reply && *reply)
12258 {
12259 /* 'l' by itself means we're at the end of the buffer and
12260 there is nothing more to get. */
12261 if (*reply == 'l')
12262 return 0;
12263
12264 /* Convert the reply into binary. Limit the number of bytes to
12265 convert according to our passed-in buffer size, rather than
12266 what was returned in the packet; if the target is
12267 unexpectedly generous and gives us a bigger reply than we
12268 asked for, we don't want to crash. */
12269 rslt = hex2bin (target_buf, buf, len);
12270 return rslt;
12271 }
12272
12273 /* Something went wrong, flag as an error. */
12274 return -1;
12275 }
12276
12277 static void
12278 remote_set_disconnected_tracing (struct target_ops *self, int val)
12279 {
12280 struct remote_state *rs = get_remote_state ();
12281
12282 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12283 {
12284 char *reply;
12285
12286 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12287 putpkt (rs->buf);
12288 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12289 if (*reply == '\0')
12290 error (_("Target does not support this command."));
12291 if (strcmp (reply, "OK") != 0)
12292 error (_("Bogus reply from target: %s"), reply);
12293 }
12294 else if (val)
12295 warning (_("Target does not support disconnected tracing."));
12296 }
12297
12298 static int
12299 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12300 {
12301 struct thread_info *info = find_thread_ptid (ptid);
12302
12303 if (info && info->priv)
12304 return info->priv->core;
12305 return -1;
12306 }
12307
12308 static void
12309 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12310 {
12311 struct remote_state *rs = get_remote_state ();
12312 char *reply;
12313
12314 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12315 putpkt (rs->buf);
12316 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12317 if (*reply == '\0')
12318 error (_("Target does not support this command."));
12319 if (strcmp (reply, "OK") != 0)
12320 error (_("Bogus reply from target: %s"), reply);
12321 }
12322
12323 static struct traceframe_info *
12324 remote_traceframe_info (struct target_ops *self)
12325 {
12326 char *text;
12327
12328 text = target_read_stralloc (&current_target,
12329 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12330 if (text != NULL)
12331 {
12332 struct traceframe_info *info;
12333 struct cleanup *back_to = make_cleanup (xfree, text);
12334
12335 info = parse_traceframe_info (text);
12336 do_cleanups (back_to);
12337 return info;
12338 }
12339
12340 return NULL;
12341 }
12342
12343 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12344 instruction on which a fast tracepoint may be placed. Returns -1
12345 if the packet is not supported, and 0 if the minimum instruction
12346 length is unknown. */
12347
12348 static int
12349 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12350 {
12351 struct remote_state *rs = get_remote_state ();
12352 char *reply;
12353
12354 /* If we're not debugging a process yet, the IPA can't be
12355 loaded. */
12356 if (!target_has_execution)
12357 return 0;
12358
12359 /* Make sure the remote is pointing at the right process. */
12360 set_general_process ();
12361
12362 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12363 putpkt (rs->buf);
12364 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12365 if (*reply == '\0')
12366 return -1;
12367 else
12368 {
12369 ULONGEST min_insn_len;
12370
12371 unpack_varlen_hex (reply, &min_insn_len);
12372
12373 return (int) min_insn_len;
12374 }
12375 }
12376
12377 static void
12378 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12379 {
12380 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12381 {
12382 struct remote_state *rs = get_remote_state ();
12383 char *buf = rs->buf;
12384 char *endbuf = rs->buf + get_remote_packet_size ();
12385 enum packet_result result;
12386
12387 gdb_assert (val >= 0 || val == -1);
12388 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12389 /* Send -1 as literal "-1" to avoid host size dependency. */
12390 if (val < 0)
12391 {
12392 *buf++ = '-';
12393 buf += hexnumstr (buf, (ULONGEST) -val);
12394 }
12395 else
12396 buf += hexnumstr (buf, (ULONGEST) val);
12397
12398 putpkt (rs->buf);
12399 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12400 result = packet_ok (rs->buf,
12401 &remote_protocol_packets[PACKET_QTBuffer_size]);
12402
12403 if (result != PACKET_OK)
12404 warning (_("Bogus reply from target: %s"), rs->buf);
12405 }
12406 }
12407
12408 static int
12409 remote_set_trace_notes (struct target_ops *self,
12410 const char *user, const char *notes,
12411 const char *stop_notes)
12412 {
12413 struct remote_state *rs = get_remote_state ();
12414 char *reply;
12415 char *buf = rs->buf;
12416 char *endbuf = rs->buf + get_remote_packet_size ();
12417 int nbytes;
12418
12419 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12420 if (user)
12421 {
12422 buf += xsnprintf (buf, endbuf - buf, "user:");
12423 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12424 buf += 2 * nbytes;
12425 *buf++ = ';';
12426 }
12427 if (notes)
12428 {
12429 buf += xsnprintf (buf, endbuf - buf, "notes:");
12430 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12431 buf += 2 * nbytes;
12432 *buf++ = ';';
12433 }
12434 if (stop_notes)
12435 {
12436 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12437 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12438 buf += 2 * nbytes;
12439 *buf++ = ';';
12440 }
12441 /* Ensure the buffer is terminated. */
12442 *buf = '\0';
12443
12444 putpkt (rs->buf);
12445 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12446 if (*reply == '\0')
12447 return 0;
12448
12449 if (strcmp (reply, "OK") != 0)
12450 error (_("Bogus reply from target: %s"), reply);
12451
12452 return 1;
12453 }
12454
12455 static int
12456 remote_use_agent (struct target_ops *self, int use)
12457 {
12458 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12459 {
12460 struct remote_state *rs = get_remote_state ();
12461
12462 /* If the stub supports QAgent. */
12463 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12464 putpkt (rs->buf);
12465 getpkt (&rs->buf, &rs->buf_size, 0);
12466
12467 if (strcmp (rs->buf, "OK") == 0)
12468 {
12469 use_agent = use;
12470 return 1;
12471 }
12472 }
12473
12474 return 0;
12475 }
12476
12477 static int
12478 remote_can_use_agent (struct target_ops *self)
12479 {
12480 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12481 }
12482
12483 struct btrace_target_info
12484 {
12485 /* The ptid of the traced thread. */
12486 ptid_t ptid;
12487
12488 /* The obtained branch trace configuration. */
12489 struct btrace_config conf;
12490 };
12491
12492 /* Reset our idea of our target's btrace configuration. */
12493
12494 static void
12495 remote_btrace_reset (void)
12496 {
12497 struct remote_state *rs = get_remote_state ();
12498
12499 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12500 }
12501
12502 /* Check whether the target supports branch tracing. */
12503
12504 static int
12505 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12506 {
12507 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12508 return 0;
12509 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12510 return 0;
12511
12512 switch (format)
12513 {
12514 case BTRACE_FORMAT_NONE:
12515 return 0;
12516
12517 case BTRACE_FORMAT_BTS:
12518 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12519
12520 case BTRACE_FORMAT_PT:
12521 /* The trace is decoded on the host. Even if our target supports it,
12522 we still need to have libipt to decode the trace. */
12523 #if defined (HAVE_LIBIPT)
12524 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12525 #else /* !defined (HAVE_LIBIPT) */
12526 return 0;
12527 #endif /* !defined (HAVE_LIBIPT) */
12528 }
12529
12530 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12531 }
12532
12533 /* Synchronize the configuration with the target. */
12534
12535 static void
12536 btrace_sync_conf (const struct btrace_config *conf)
12537 {
12538 struct packet_config *packet;
12539 struct remote_state *rs;
12540 char *buf, *pos, *endbuf;
12541
12542 rs = get_remote_state ();
12543 buf = rs->buf;
12544 endbuf = buf + get_remote_packet_size ();
12545
12546 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12547 if (packet_config_support (packet) == PACKET_ENABLE
12548 && conf->bts.size != rs->btrace_config.bts.size)
12549 {
12550 pos = buf;
12551 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12552 conf->bts.size);
12553
12554 putpkt (buf);
12555 getpkt (&buf, &rs->buf_size, 0);
12556
12557 if (packet_ok (buf, packet) == PACKET_ERROR)
12558 {
12559 if (buf[0] == 'E' && buf[1] == '.')
12560 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12561 else
12562 error (_("Failed to configure the BTS buffer size."));
12563 }
12564
12565 rs->btrace_config.bts.size = conf->bts.size;
12566 }
12567
12568 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12569 if (packet_config_support (packet) == PACKET_ENABLE
12570 && conf->pt.size != rs->btrace_config.pt.size)
12571 {
12572 pos = buf;
12573 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12574 conf->pt.size);
12575
12576 putpkt (buf);
12577 getpkt (&buf, &rs->buf_size, 0);
12578
12579 if (packet_ok (buf, packet) == PACKET_ERROR)
12580 {
12581 if (buf[0] == 'E' && buf[1] == '.')
12582 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12583 else
12584 error (_("Failed to configure the trace buffer size."));
12585 }
12586
12587 rs->btrace_config.pt.size = conf->pt.size;
12588 }
12589 }
12590
12591 /* Read the current thread's btrace configuration from the target and
12592 store it into CONF. */
12593
12594 static void
12595 btrace_read_config (struct btrace_config *conf)
12596 {
12597 char *xml;
12598
12599 xml = target_read_stralloc (&current_target,
12600 TARGET_OBJECT_BTRACE_CONF, "");
12601 if (xml != NULL)
12602 {
12603 struct cleanup *cleanup;
12604
12605 cleanup = make_cleanup (xfree, xml);
12606 parse_xml_btrace_conf (conf, xml);
12607 do_cleanups (cleanup);
12608 }
12609 }
12610
12611 /* Enable branch tracing. */
12612
12613 static struct btrace_target_info *
12614 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12615 const struct btrace_config *conf)
12616 {
12617 struct btrace_target_info *tinfo = NULL;
12618 struct packet_config *packet = NULL;
12619 struct remote_state *rs = get_remote_state ();
12620 char *buf = rs->buf;
12621 char *endbuf = rs->buf + get_remote_packet_size ();
12622
12623 switch (conf->format)
12624 {
12625 case BTRACE_FORMAT_BTS:
12626 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12627 break;
12628
12629 case BTRACE_FORMAT_PT:
12630 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12631 break;
12632 }
12633
12634 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12635 error (_("Target does not support branch tracing."));
12636
12637 btrace_sync_conf (conf);
12638
12639 set_general_thread (ptid);
12640
12641 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12642 putpkt (rs->buf);
12643 getpkt (&rs->buf, &rs->buf_size, 0);
12644
12645 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12646 {
12647 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12648 error (_("Could not enable branch tracing for %s: %s"),
12649 target_pid_to_str (ptid), rs->buf + 2);
12650 else
12651 error (_("Could not enable branch tracing for %s."),
12652 target_pid_to_str (ptid));
12653 }
12654
12655 tinfo = XCNEW (struct btrace_target_info);
12656 tinfo->ptid = ptid;
12657
12658 /* If we fail to read the configuration, we lose some information, but the
12659 tracing itself is not impacted. */
12660 TRY
12661 {
12662 btrace_read_config (&tinfo->conf);
12663 }
12664 CATCH (err, RETURN_MASK_ERROR)
12665 {
12666 if (err.message != NULL)
12667 warning ("%s", err.message);
12668 }
12669 END_CATCH
12670
12671 return tinfo;
12672 }
12673
12674 /* Disable branch tracing. */
12675
12676 static void
12677 remote_disable_btrace (struct target_ops *self,
12678 struct btrace_target_info *tinfo)
12679 {
12680 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12681 struct remote_state *rs = get_remote_state ();
12682 char *buf = rs->buf;
12683 char *endbuf = rs->buf + get_remote_packet_size ();
12684
12685 if (packet_config_support (packet) != PACKET_ENABLE)
12686 error (_("Target does not support branch tracing."));
12687
12688 set_general_thread (tinfo->ptid);
12689
12690 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12691 putpkt (rs->buf);
12692 getpkt (&rs->buf, &rs->buf_size, 0);
12693
12694 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12695 {
12696 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12697 error (_("Could not disable branch tracing for %s: %s"),
12698 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12699 else
12700 error (_("Could not disable branch tracing for %s."),
12701 target_pid_to_str (tinfo->ptid));
12702 }
12703
12704 xfree (tinfo);
12705 }
12706
12707 /* Teardown branch tracing. */
12708
12709 static void
12710 remote_teardown_btrace (struct target_ops *self,
12711 struct btrace_target_info *tinfo)
12712 {
12713 /* We must not talk to the target during teardown. */
12714 xfree (tinfo);
12715 }
12716
12717 /* Read the branch trace. */
12718
12719 static enum btrace_error
12720 remote_read_btrace (struct target_ops *self,
12721 struct btrace_data *btrace,
12722 struct btrace_target_info *tinfo,
12723 enum btrace_read_type type)
12724 {
12725 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12726 struct remote_state *rs = get_remote_state ();
12727 struct cleanup *cleanup;
12728 const char *annex;
12729 char *xml;
12730
12731 if (packet_config_support (packet) != PACKET_ENABLE)
12732 error (_("Target does not support branch tracing."));
12733
12734 #if !defined(HAVE_LIBEXPAT)
12735 error (_("Cannot process branch tracing result. XML parsing not supported."));
12736 #endif
12737
12738 switch (type)
12739 {
12740 case BTRACE_READ_ALL:
12741 annex = "all";
12742 break;
12743 case BTRACE_READ_NEW:
12744 annex = "new";
12745 break;
12746 case BTRACE_READ_DELTA:
12747 annex = "delta";
12748 break;
12749 default:
12750 internal_error (__FILE__, __LINE__,
12751 _("Bad branch tracing read type: %u."),
12752 (unsigned int) type);
12753 }
12754
12755 xml = target_read_stralloc (&current_target,
12756 TARGET_OBJECT_BTRACE, annex);
12757 if (xml == NULL)
12758 return BTRACE_ERR_UNKNOWN;
12759
12760 cleanup = make_cleanup (xfree, xml);
12761 parse_xml_btrace (btrace, xml);
12762 do_cleanups (cleanup);
12763
12764 return BTRACE_ERR_NONE;
12765 }
12766
12767 static const struct btrace_config *
12768 remote_btrace_conf (struct target_ops *self,
12769 const struct btrace_target_info *tinfo)
12770 {
12771 return &tinfo->conf;
12772 }
12773
12774 static int
12775 remote_augmented_libraries_svr4_read (struct target_ops *self)
12776 {
12777 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12778 == PACKET_ENABLE);
12779 }
12780
12781 /* Implementation of to_load. */
12782
12783 static void
12784 remote_load (struct target_ops *self, const char *name, int from_tty)
12785 {
12786 generic_load (name, from_tty);
12787 }
12788
12789 /* Accepts an integer PID; returns a string representing a file that
12790 can be opened on the remote side to get the symbols for the child
12791 process. Returns NULL if the operation is not supported. */
12792
12793 static char *
12794 remote_pid_to_exec_file (struct target_ops *self, int pid)
12795 {
12796 static char *filename = NULL;
12797 struct inferior *inf;
12798 char *annex = NULL;
12799
12800 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12801 return NULL;
12802
12803 if (filename != NULL)
12804 xfree (filename);
12805
12806 inf = find_inferior_pid (pid);
12807 if (inf == NULL)
12808 internal_error (__FILE__, __LINE__,
12809 _("not currently attached to process %d"), pid);
12810
12811 if (!inf->fake_pid_p)
12812 {
12813 const int annex_size = 9;
12814
12815 annex = (char *) alloca (annex_size);
12816 xsnprintf (annex, annex_size, "%x", pid);
12817 }
12818
12819 filename = target_read_stralloc (&current_target,
12820 TARGET_OBJECT_EXEC_FILE, annex);
12821
12822 return filename;
12823 }
12824
12825 /* Implement the to_can_do_single_step target_ops method. */
12826
12827 static int
12828 remote_can_do_single_step (struct target_ops *ops)
12829 {
12830 /* We can only tell whether target supports single step or not by
12831 supported s and S vCont actions if the stub supports vContSupported
12832 feature. If the stub doesn't support vContSupported feature,
12833 we have conservatively to think target doesn't supports single
12834 step. */
12835 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12836 {
12837 struct remote_state *rs = get_remote_state ();
12838
12839 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12840 remote_vcont_probe (rs);
12841
12842 return rs->supports_vCont.s && rs->supports_vCont.S;
12843 }
12844 else
12845 return 0;
12846 }
12847
12848 static void
12849 init_remote_ops (void)
12850 {
12851 remote_ops.to_shortname = "remote";
12852 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12853 remote_ops.to_doc =
12854 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12855 Specify the serial device it is connected to\n\
12856 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12857 remote_ops.to_open = remote_open;
12858 remote_ops.to_close = remote_close;
12859 remote_ops.to_detach = remote_detach;
12860 remote_ops.to_disconnect = remote_disconnect;
12861 remote_ops.to_resume = remote_resume;
12862 remote_ops.to_wait = remote_wait;
12863 remote_ops.to_fetch_registers = remote_fetch_registers;
12864 remote_ops.to_store_registers = remote_store_registers;
12865 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12866 remote_ops.to_files_info = remote_files_info;
12867 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12868 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12869 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12870 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12871 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12872 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12873 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12874 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12875 remote_ops.to_watchpoint_addr_within_range =
12876 remote_watchpoint_addr_within_range;
12877 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12878 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12879 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12880 remote_ops.to_region_ok_for_hw_watchpoint
12881 = remote_region_ok_for_hw_watchpoint;
12882 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12883 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12884 remote_ops.to_kill = remote_kill;
12885 remote_ops.to_load = remote_load;
12886 remote_ops.to_mourn_inferior = remote_mourn;
12887 remote_ops.to_pass_signals = remote_pass_signals;
12888 remote_ops.to_program_signals = remote_program_signals;
12889 remote_ops.to_thread_alive = remote_thread_alive;
12890 remote_ops.to_thread_name = remote_thread_name;
12891 remote_ops.to_update_thread_list = remote_update_thread_list;
12892 remote_ops.to_pid_to_str = remote_pid_to_str;
12893 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12894 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12895 remote_ops.to_stop = remote_stop;
12896 remote_ops.to_interrupt = remote_interrupt;
12897 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12898 remote_ops.to_xfer_partial = remote_xfer_partial;
12899 remote_ops.to_rcmd = remote_rcmd;
12900 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12901 remote_ops.to_log_command = serial_log_command;
12902 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12903 remote_ops.to_stratum = process_stratum;
12904 remote_ops.to_has_all_memory = default_child_has_all_memory;
12905 remote_ops.to_has_memory = default_child_has_memory;
12906 remote_ops.to_has_stack = default_child_has_stack;
12907 remote_ops.to_has_registers = default_child_has_registers;
12908 remote_ops.to_has_execution = default_child_has_execution;
12909 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12910 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12911 remote_ops.to_magic = OPS_MAGIC;
12912 remote_ops.to_memory_map = remote_memory_map;
12913 remote_ops.to_flash_erase = remote_flash_erase;
12914 remote_ops.to_flash_done = remote_flash_done;
12915 remote_ops.to_read_description = remote_read_description;
12916 remote_ops.to_search_memory = remote_search_memory;
12917 remote_ops.to_can_async_p = remote_can_async_p;
12918 remote_ops.to_is_async_p = remote_is_async_p;
12919 remote_ops.to_async = remote_async;
12920 remote_ops.to_can_do_single_step = remote_can_do_single_step;
12921 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12922 remote_ops.to_terminal_ours = remote_terminal_ours;
12923 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12924 remote_ops.to_supports_multi_process = remote_supports_multi_process;
12925 remote_ops.to_supports_disable_randomization
12926 = remote_supports_disable_randomization;
12927 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12928 remote_ops.to_fileio_open = remote_hostio_open;
12929 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12930 remote_ops.to_fileio_pread = remote_hostio_pread;
12931 remote_ops.to_fileio_fstat = remote_hostio_fstat;
12932 remote_ops.to_fileio_close = remote_hostio_close;
12933 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12934 remote_ops.to_fileio_readlink = remote_hostio_readlink;
12935 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12936 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12937 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12938 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12939 remote_ops.to_trace_init = remote_trace_init;
12940 remote_ops.to_download_tracepoint = remote_download_tracepoint;
12941 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12942 remote_ops.to_download_trace_state_variable
12943 = remote_download_trace_state_variable;
12944 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12945 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12946 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12947 remote_ops.to_trace_start = remote_trace_start;
12948 remote_ops.to_get_trace_status = remote_get_trace_status;
12949 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12950 remote_ops.to_trace_stop = remote_trace_stop;
12951 remote_ops.to_trace_find = remote_trace_find;
12952 remote_ops.to_get_trace_state_variable_value
12953 = remote_get_trace_state_variable_value;
12954 remote_ops.to_save_trace_data = remote_save_trace_data;
12955 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
12956 remote_ops.to_upload_trace_state_variables
12957 = remote_upload_trace_state_variables;
12958 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
12959 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
12960 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12961 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
12962 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
12963 remote_ops.to_set_trace_notes = remote_set_trace_notes;
12964 remote_ops.to_core_of_thread = remote_core_of_thread;
12965 remote_ops.to_verify_memory = remote_verify_memory;
12966 remote_ops.to_get_tib_address = remote_get_tib_address;
12967 remote_ops.to_set_permissions = remote_set_permissions;
12968 remote_ops.to_static_tracepoint_marker_at
12969 = remote_static_tracepoint_marker_at;
12970 remote_ops.to_static_tracepoint_markers_by_strid
12971 = remote_static_tracepoint_markers_by_strid;
12972 remote_ops.to_traceframe_info = remote_traceframe_info;
12973 remote_ops.to_use_agent = remote_use_agent;
12974 remote_ops.to_can_use_agent = remote_can_use_agent;
12975 remote_ops.to_supports_btrace = remote_supports_btrace;
12976 remote_ops.to_enable_btrace = remote_enable_btrace;
12977 remote_ops.to_disable_btrace = remote_disable_btrace;
12978 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12979 remote_ops.to_read_btrace = remote_read_btrace;
12980 remote_ops.to_btrace_conf = remote_btrace_conf;
12981 remote_ops.to_augmented_libraries_svr4_read =
12982 remote_augmented_libraries_svr4_read;
12983 }
12984
12985 /* Set up the extended remote vector by making a copy of the standard
12986 remote vector and adding to it. */
12987
12988 static void
12989 init_extended_remote_ops (void)
12990 {
12991 extended_remote_ops = remote_ops;
12992
12993 extended_remote_ops.to_shortname = "extended-remote";
12994 extended_remote_ops.to_longname =
12995 "Extended remote serial target in gdb-specific protocol";
12996 extended_remote_ops.to_doc =
12997 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12998 Specify the serial device it is connected to (e.g. /dev/ttya).";
12999 extended_remote_ops.to_open = extended_remote_open;
13000 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13001 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
13002 extended_remote_ops.to_detach = extended_remote_detach;
13003 extended_remote_ops.to_attach = extended_remote_attach;
13004 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13005 extended_remote_ops.to_kill = extended_remote_kill;
13006 extended_remote_ops.to_supports_disable_randomization
13007 = extended_remote_supports_disable_randomization;
13008 extended_remote_ops.to_follow_fork = remote_follow_fork;
13009 extended_remote_ops.to_follow_exec = remote_follow_exec;
13010 extended_remote_ops.to_insert_fork_catchpoint
13011 = remote_insert_fork_catchpoint;
13012 extended_remote_ops.to_remove_fork_catchpoint
13013 = remote_remove_fork_catchpoint;
13014 extended_remote_ops.to_insert_vfork_catchpoint
13015 = remote_insert_vfork_catchpoint;
13016 extended_remote_ops.to_remove_vfork_catchpoint
13017 = remote_remove_vfork_catchpoint;
13018 extended_remote_ops.to_insert_exec_catchpoint
13019 = remote_insert_exec_catchpoint;
13020 extended_remote_ops.to_remove_exec_catchpoint
13021 = remote_remove_exec_catchpoint;
13022 }
13023
13024 static int
13025 remote_can_async_p (struct target_ops *ops)
13026 {
13027 struct remote_state *rs = get_remote_state ();
13028
13029 if (!target_async_permitted)
13030 /* We only enable async when the user specifically asks for it. */
13031 return 0;
13032
13033 /* We're async whenever the serial device is. */
13034 return serial_can_async_p (rs->remote_desc);
13035 }
13036
13037 static int
13038 remote_is_async_p (struct target_ops *ops)
13039 {
13040 struct remote_state *rs = get_remote_state ();
13041
13042 if (!target_async_permitted)
13043 /* We only enable async when the user specifically asks for it. */
13044 return 0;
13045
13046 /* We're async whenever the serial device is. */
13047 return serial_is_async_p (rs->remote_desc);
13048 }
13049
13050 /* Pass the SERIAL event on and up to the client. One day this code
13051 will be able to delay notifying the client of an event until the
13052 point where an entire packet has been received. */
13053
13054 static serial_event_ftype remote_async_serial_handler;
13055
13056 static void
13057 remote_async_serial_handler (struct serial *scb, void *context)
13058 {
13059 struct remote_state *rs = (struct remote_state *) context;
13060
13061 /* Don't propogate error information up to the client. Instead let
13062 the client find out about the error by querying the target. */
13063 inferior_event_handler (INF_REG_EVENT, NULL);
13064 }
13065
13066 static void
13067 remote_async_inferior_event_handler (gdb_client_data data)
13068 {
13069 inferior_event_handler (INF_REG_EVENT, NULL);
13070 }
13071
13072 static void
13073 remote_async (struct target_ops *ops, int enable)
13074 {
13075 struct remote_state *rs = get_remote_state ();
13076
13077 if (enable)
13078 {
13079 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13080
13081 /* If there are pending events in the stop reply queue tell the
13082 event loop to process them. */
13083 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13084 mark_async_event_handler (remote_async_inferior_event_token);
13085 /* For simplicity, below we clear the pending events token
13086 without remembering whether it is marked, so here we always
13087 mark it. If there's actually no pending notification to
13088 process, this ends up being a no-op (other than a spurious
13089 event-loop wakeup). */
13090 if (target_is_non_stop_p ())
13091 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13092 }
13093 else
13094 {
13095 serial_async (rs->remote_desc, NULL, NULL);
13096 /* If the core is disabling async, it doesn't want to be
13097 disturbed with target events. Clear all async event sources
13098 too. */
13099 clear_async_event_handler (remote_async_inferior_event_token);
13100 if (target_is_non_stop_p ())
13101 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13102 }
13103 }
13104
13105 static void
13106 set_remote_cmd (char *args, int from_tty)
13107 {
13108 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13109 }
13110
13111 static void
13112 show_remote_cmd (char *args, int from_tty)
13113 {
13114 /* We can't just use cmd_show_list here, because we want to skip
13115 the redundant "show remote Z-packet" and the legacy aliases. */
13116 struct cleanup *showlist_chain;
13117 struct cmd_list_element *list = remote_show_cmdlist;
13118 struct ui_out *uiout = current_uiout;
13119
13120 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13121 for (; list != NULL; list = list->next)
13122 if (strcmp (list->name, "Z-packet") == 0)
13123 continue;
13124 else if (list->type == not_set_cmd)
13125 /* Alias commands are exactly like the original, except they
13126 don't have the normal type. */
13127 continue;
13128 else
13129 {
13130 struct cleanup *option_chain
13131 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13132
13133 ui_out_field_string (uiout, "name", list->name);
13134 ui_out_text (uiout, ": ");
13135 if (list->type == show_cmd)
13136 do_show_command ((char *) NULL, from_tty, list);
13137 else
13138 cmd_func (list, NULL, from_tty);
13139 /* Close the tuple. */
13140 do_cleanups (option_chain);
13141 }
13142
13143 /* Close the tuple. */
13144 do_cleanups (showlist_chain);
13145 }
13146
13147
13148 /* Function to be called whenever a new objfile (shlib) is detected. */
13149 static void
13150 remote_new_objfile (struct objfile *objfile)
13151 {
13152 struct remote_state *rs = get_remote_state ();
13153
13154 if (rs->remote_desc != 0) /* Have a remote connection. */
13155 remote_check_symbols ();
13156 }
13157
13158 /* Pull all the tracepoints defined on the target and create local
13159 data structures representing them. We don't want to create real
13160 tracepoints yet, we don't want to mess up the user's existing
13161 collection. */
13162
13163 static int
13164 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13165 {
13166 struct remote_state *rs = get_remote_state ();
13167 char *p;
13168
13169 /* Ask for a first packet of tracepoint definition. */
13170 putpkt ("qTfP");
13171 getpkt (&rs->buf, &rs->buf_size, 0);
13172 p = rs->buf;
13173 while (*p && *p != 'l')
13174 {
13175 parse_tracepoint_definition (p, utpp);
13176 /* Ask for another packet of tracepoint definition. */
13177 putpkt ("qTsP");
13178 getpkt (&rs->buf, &rs->buf_size, 0);
13179 p = rs->buf;
13180 }
13181 return 0;
13182 }
13183
13184 static int
13185 remote_upload_trace_state_variables (struct target_ops *self,
13186 struct uploaded_tsv **utsvp)
13187 {
13188 struct remote_state *rs = get_remote_state ();
13189 char *p;
13190
13191 /* Ask for a first packet of variable definition. */
13192 putpkt ("qTfV");
13193 getpkt (&rs->buf, &rs->buf_size, 0);
13194 p = rs->buf;
13195 while (*p && *p != 'l')
13196 {
13197 parse_tsv_definition (p, utsvp);
13198 /* Ask for another packet of variable definition. */
13199 putpkt ("qTsV");
13200 getpkt (&rs->buf, &rs->buf_size, 0);
13201 p = rs->buf;
13202 }
13203 return 0;
13204 }
13205
13206 /* The "set/show range-stepping" show hook. */
13207
13208 static void
13209 show_range_stepping (struct ui_file *file, int from_tty,
13210 struct cmd_list_element *c,
13211 const char *value)
13212 {
13213 fprintf_filtered (file,
13214 _("Debugger's willingness to use range stepping "
13215 "is %s.\n"), value);
13216 }
13217
13218 /* The "set/show range-stepping" set hook. */
13219
13220 static void
13221 set_range_stepping (char *ignore_args, int from_tty,
13222 struct cmd_list_element *c)
13223 {
13224 struct remote_state *rs = get_remote_state ();
13225
13226 /* Whene enabling, check whether range stepping is actually
13227 supported by the target, and warn if not. */
13228 if (use_range_stepping)
13229 {
13230 if (rs->remote_desc != NULL)
13231 {
13232 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13233 remote_vcont_probe (rs);
13234
13235 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13236 && rs->supports_vCont.r)
13237 return;
13238 }
13239
13240 warning (_("Range stepping is not supported by the current target"));
13241 }
13242 }
13243
13244 void
13245 _initialize_remote (void)
13246 {
13247 struct remote_state *rs;
13248 struct cmd_list_element *cmd;
13249 const char *cmd_name;
13250
13251 /* architecture specific data */
13252 remote_gdbarch_data_handle =
13253 gdbarch_data_register_post_init (init_remote_state);
13254 remote_g_packet_data_handle =
13255 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13256
13257 remote_pspace_data
13258 = register_program_space_data_with_cleanup (NULL,
13259 remote_pspace_data_cleanup);
13260
13261 /* Initialize the per-target state. At the moment there is only one
13262 of these, not one per target. Only one target is active at a
13263 time. */
13264 remote_state = new_remote_state ();
13265
13266 init_remote_ops ();
13267 add_target (&remote_ops);
13268
13269 init_extended_remote_ops ();
13270 add_target (&extended_remote_ops);
13271
13272 /* Hook into new objfile notification. */
13273 observer_attach_new_objfile (remote_new_objfile);
13274 /* We're no longer interested in notification events of an inferior
13275 when it exits. */
13276 observer_attach_inferior_exit (discard_pending_stop_replies);
13277
13278 /* Set up signal handlers. */
13279 async_sigint_remote_token =
13280 create_async_signal_handler (async_remote_interrupt, NULL);
13281 async_sigint_remote_twice_token =
13282 create_async_signal_handler (async_remote_interrupt_twice, NULL);
13283
13284 #if 0
13285 init_remote_threadtests ();
13286 #endif
13287
13288 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13289 /* set/show remote ... */
13290
13291 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13292 Remote protocol specific variables\n\
13293 Configure various remote-protocol specific variables such as\n\
13294 the packets being used"),
13295 &remote_set_cmdlist, "set remote ",
13296 0 /* allow-unknown */, &setlist);
13297 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13298 Remote protocol specific variables\n\
13299 Configure various remote-protocol specific variables such as\n\
13300 the packets being used"),
13301 &remote_show_cmdlist, "show remote ",
13302 0 /* allow-unknown */, &showlist);
13303
13304 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13305 Compare section data on target to the exec file.\n\
13306 Argument is a single section name (default: all loaded sections).\n\
13307 To compare only read-only loaded sections, specify the -r option."),
13308 &cmdlist);
13309
13310 add_cmd ("packet", class_maintenance, packet_command, _("\
13311 Send an arbitrary packet to a remote target.\n\
13312 maintenance packet TEXT\n\
13313 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13314 this command sends the string TEXT to the inferior, and displays the\n\
13315 response packet. GDB supplies the initial `$' character, and the\n\
13316 terminating `#' character and checksum."),
13317 &maintenancelist);
13318
13319 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13320 Set whether to send break if interrupted."), _("\
13321 Show whether to send break if interrupted."), _("\
13322 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13323 set_remotebreak, show_remotebreak,
13324 &setlist, &showlist);
13325 cmd_name = "remotebreak";
13326 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13327 deprecate_cmd (cmd, "set remote interrupt-sequence");
13328 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13329 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13330 deprecate_cmd (cmd, "show remote interrupt-sequence");
13331
13332 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13333 interrupt_sequence_modes, &interrupt_sequence_mode,
13334 _("\
13335 Set interrupt sequence to remote target."), _("\
13336 Show interrupt sequence to remote target."), _("\
13337 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13338 NULL, show_interrupt_sequence,
13339 &remote_set_cmdlist,
13340 &remote_show_cmdlist);
13341
13342 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13343 &interrupt_on_connect, _("\
13344 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13345 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13346 If set, interrupt sequence is sent to remote target."),
13347 NULL, NULL,
13348 &remote_set_cmdlist, &remote_show_cmdlist);
13349
13350 /* Install commands for configuring memory read/write packets. */
13351
13352 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13353 Set the maximum number of bytes per memory write packet (deprecated)."),
13354 &setlist);
13355 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13356 Show the maximum number of bytes per memory write packet (deprecated)."),
13357 &showlist);
13358 add_cmd ("memory-write-packet-size", no_class,
13359 set_memory_write_packet_size, _("\
13360 Set the maximum number of bytes per memory-write packet.\n\
13361 Specify the number of bytes in a packet or 0 (zero) for the\n\
13362 default packet size. The actual limit is further reduced\n\
13363 dependent on the target. Specify ``fixed'' to disable the\n\
13364 further restriction and ``limit'' to enable that restriction."),
13365 &remote_set_cmdlist);
13366 add_cmd ("memory-read-packet-size", no_class,
13367 set_memory_read_packet_size, _("\
13368 Set the maximum number of bytes per memory-read packet.\n\
13369 Specify the number of bytes in a packet or 0 (zero) for the\n\
13370 default packet size. The actual limit is further reduced\n\
13371 dependent on the target. Specify ``fixed'' to disable the\n\
13372 further restriction and ``limit'' to enable that restriction."),
13373 &remote_set_cmdlist);
13374 add_cmd ("memory-write-packet-size", no_class,
13375 show_memory_write_packet_size,
13376 _("Show the maximum number of bytes per memory-write packet."),
13377 &remote_show_cmdlist);
13378 add_cmd ("memory-read-packet-size", no_class,
13379 show_memory_read_packet_size,
13380 _("Show the maximum number of bytes per memory-read packet."),
13381 &remote_show_cmdlist);
13382
13383 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13384 &remote_hw_watchpoint_limit, _("\
13385 Set the maximum number of target hardware watchpoints."), _("\
13386 Show the maximum number of target hardware watchpoints."), _("\
13387 Specify a negative limit for unlimited."),
13388 NULL, NULL, /* FIXME: i18n: The maximum
13389 number of target hardware
13390 watchpoints is %s. */
13391 &remote_set_cmdlist, &remote_show_cmdlist);
13392 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13393 &remote_hw_watchpoint_length_limit, _("\
13394 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13395 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13396 Specify a negative limit for unlimited."),
13397 NULL, NULL, /* FIXME: i18n: The maximum
13398 length (in bytes) of a target
13399 hardware watchpoint is %s. */
13400 &remote_set_cmdlist, &remote_show_cmdlist);
13401 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13402 &remote_hw_breakpoint_limit, _("\
13403 Set the maximum number of target hardware breakpoints."), _("\
13404 Show the maximum number of target hardware breakpoints."), _("\
13405 Specify a negative limit for unlimited."),
13406 NULL, NULL, /* FIXME: i18n: The maximum
13407 number of target hardware
13408 breakpoints is %s. */
13409 &remote_set_cmdlist, &remote_show_cmdlist);
13410
13411 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13412 &remote_address_size, _("\
13413 Set the maximum size of the address (in bits) in a memory packet."), _("\
13414 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13415 NULL,
13416 NULL, /* FIXME: i18n: */
13417 &setlist, &showlist);
13418
13419 init_all_packet_configs ();
13420
13421 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13422 "X", "binary-download", 1);
13423
13424 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13425 "vCont", "verbose-resume", 0);
13426
13427 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13428 "QPassSignals", "pass-signals", 0);
13429
13430 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13431 "QProgramSignals", "program-signals", 0);
13432
13433 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13434 "qSymbol", "symbol-lookup", 0);
13435
13436 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13437 "P", "set-register", 1);
13438
13439 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13440 "p", "fetch-register", 1);
13441
13442 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13443 "Z0", "software-breakpoint", 0);
13444
13445 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13446 "Z1", "hardware-breakpoint", 0);
13447
13448 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13449 "Z2", "write-watchpoint", 0);
13450
13451 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13452 "Z3", "read-watchpoint", 0);
13453
13454 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13455 "Z4", "access-watchpoint", 0);
13456
13457 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13458 "qXfer:auxv:read", "read-aux-vector", 0);
13459
13460 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13461 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13462
13463 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13464 "qXfer:features:read", "target-features", 0);
13465
13466 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13467 "qXfer:libraries:read", "library-info", 0);
13468
13469 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13470 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13471
13472 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13473 "qXfer:memory-map:read", "memory-map", 0);
13474
13475 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13476 "qXfer:spu:read", "read-spu-object", 0);
13477
13478 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13479 "qXfer:spu:write", "write-spu-object", 0);
13480
13481 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13482 "qXfer:osdata:read", "osdata", 0);
13483
13484 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13485 "qXfer:threads:read", "threads", 0);
13486
13487 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13488 "qXfer:siginfo:read", "read-siginfo-object", 0);
13489
13490 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13491 "qXfer:siginfo:write", "write-siginfo-object", 0);
13492
13493 add_packet_config_cmd
13494 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13495 "qXfer:traceframe-info:read", "traceframe-info", 0);
13496
13497 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13498 "qXfer:uib:read", "unwind-info-block", 0);
13499
13500 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13501 "qGetTLSAddr", "get-thread-local-storage-address",
13502 0);
13503
13504 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13505 "qGetTIBAddr", "get-thread-information-block-address",
13506 0);
13507
13508 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13509 "bc", "reverse-continue", 0);
13510
13511 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13512 "bs", "reverse-step", 0);
13513
13514 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13515 "qSupported", "supported-packets", 0);
13516
13517 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13518 "qSearch:memory", "search-memory", 0);
13519
13520 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13521 "qTStatus", "trace-status", 0);
13522
13523 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13524 "vFile:setfs", "hostio-setfs", 0);
13525
13526 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13527 "vFile:open", "hostio-open", 0);
13528
13529 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13530 "vFile:pread", "hostio-pread", 0);
13531
13532 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13533 "vFile:pwrite", "hostio-pwrite", 0);
13534
13535 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13536 "vFile:close", "hostio-close", 0);
13537
13538 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13539 "vFile:unlink", "hostio-unlink", 0);
13540
13541 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13542 "vFile:readlink", "hostio-readlink", 0);
13543
13544 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13545 "vFile:fstat", "hostio-fstat", 0);
13546
13547 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13548 "vAttach", "attach", 0);
13549
13550 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13551 "vRun", "run", 0);
13552
13553 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13554 "QStartNoAckMode", "noack", 0);
13555
13556 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13557 "vKill", "kill", 0);
13558
13559 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13560 "qAttached", "query-attached", 0);
13561
13562 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13563 "ConditionalTracepoints",
13564 "conditional-tracepoints", 0);
13565
13566 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13567 "ConditionalBreakpoints",
13568 "conditional-breakpoints", 0);
13569
13570 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13571 "BreakpointCommands",
13572 "breakpoint-commands", 0);
13573
13574 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13575 "FastTracepoints", "fast-tracepoints", 0);
13576
13577 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13578 "TracepointSource", "TracepointSource", 0);
13579
13580 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13581 "QAllow", "allow", 0);
13582
13583 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13584 "StaticTracepoints", "static-tracepoints", 0);
13585
13586 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13587 "InstallInTrace", "install-in-trace", 0);
13588
13589 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13590 "qXfer:statictrace:read", "read-sdata-object", 0);
13591
13592 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13593 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13594
13595 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13596 "QDisableRandomization", "disable-randomization", 0);
13597
13598 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13599 "QAgent", "agent", 0);
13600
13601 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13602 "QTBuffer:size", "trace-buffer-size", 0);
13603
13604 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13605 "Qbtrace:off", "disable-btrace", 0);
13606
13607 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13608 "Qbtrace:bts", "enable-btrace-bts", 0);
13609
13610 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13611 "Qbtrace:pt", "enable-btrace-pt", 0);
13612
13613 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13614 "qXfer:btrace", "read-btrace", 0);
13615
13616 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13617 "qXfer:btrace-conf", "read-btrace-conf", 0);
13618
13619 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13620 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13621
13622 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13623 "multiprocess-feature", "multiprocess-feature", 0);
13624
13625 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13626 "swbreak-feature", "swbreak-feature", 0);
13627
13628 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13629 "hwbreak-feature", "hwbreak-feature", 0);
13630
13631 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13632 "fork-event-feature", "fork-event-feature", 0);
13633
13634 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13635 "vfork-event-feature", "vfork-event-feature", 0);
13636
13637 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13638 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13639
13640 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13641 "vContSupported", "verbose-resume-supported", 0);
13642
13643 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13644 "exec-event-feature", "exec-event-feature", 0);
13645
13646 /* Assert that we've registered "set remote foo-packet" commands
13647 for all packet configs. */
13648 {
13649 int i;
13650
13651 for (i = 0; i < PACKET_MAX; i++)
13652 {
13653 /* Ideally all configs would have a command associated. Some
13654 still don't though. */
13655 int excepted;
13656
13657 switch (i)
13658 {
13659 case PACKET_QNonStop:
13660 case PACKET_EnableDisableTracepoints_feature:
13661 case PACKET_tracenz_feature:
13662 case PACKET_DisconnectedTracing_feature:
13663 case PACKET_augmented_libraries_svr4_read_feature:
13664 case PACKET_qCRC:
13665 /* Additions to this list need to be well justified:
13666 pre-existing packets are OK; new packets are not. */
13667 excepted = 1;
13668 break;
13669 default:
13670 excepted = 0;
13671 break;
13672 }
13673
13674 /* This catches both forgetting to add a config command, and
13675 forgetting to remove a packet from the exception list. */
13676 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13677 }
13678 }
13679
13680 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13681 Z sub-packet has its own set and show commands, but users may
13682 have sets to this variable in their .gdbinit files (or in their
13683 documentation). */
13684 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13685 &remote_Z_packet_detect, _("\
13686 Set use of remote protocol `Z' packets"), _("\
13687 Show use of remote protocol `Z' packets "), _("\
13688 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13689 packets."),
13690 set_remote_protocol_Z_packet_cmd,
13691 show_remote_protocol_Z_packet_cmd,
13692 /* FIXME: i18n: Use of remote protocol
13693 `Z' packets is %s. */
13694 &remote_set_cmdlist, &remote_show_cmdlist);
13695
13696 add_prefix_cmd ("remote", class_files, remote_command, _("\
13697 Manipulate files on the remote system\n\
13698 Transfer files to and from the remote target system."),
13699 &remote_cmdlist, "remote ",
13700 0 /* allow-unknown */, &cmdlist);
13701
13702 add_cmd ("put", class_files, remote_put_command,
13703 _("Copy a local file to the remote system."),
13704 &remote_cmdlist);
13705
13706 add_cmd ("get", class_files, remote_get_command,
13707 _("Copy a remote file to the local system."),
13708 &remote_cmdlist);
13709
13710 add_cmd ("delete", class_files, remote_delete_command,
13711 _("Delete a remote file."),
13712 &remote_cmdlist);
13713
13714 add_setshow_string_noescape_cmd ("exec-file", class_files,
13715 &remote_exec_file_var, _("\
13716 Set the remote pathname for \"run\""), _("\
13717 Show the remote pathname for \"run\""), NULL,
13718 set_remote_exec_file,
13719 show_remote_exec_file,
13720 &remote_set_cmdlist,
13721 &remote_show_cmdlist);
13722
13723 add_setshow_boolean_cmd ("range-stepping", class_run,
13724 &use_range_stepping, _("\
13725 Enable or disable range stepping."), _("\
13726 Show whether target-assisted range stepping is enabled."), _("\
13727 If on, and the target supports it, when stepping a source line, GDB\n\
13728 tells the target to step the corresponding range of addresses itself instead\n\
13729 of issuing multiple single-steps. This speeds up source level\n\
13730 stepping. If off, GDB always issues single-steps, even if range\n\
13731 stepping is supported by the target. The default is on."),
13732 set_range_stepping,
13733 show_range_stepping,
13734 &setlist,
13735 &showlist);
13736
13737 /* Eventually initialize fileio. See fileio.c */
13738 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13739
13740 /* Take advantage of the fact that the TID field is not used, to tag
13741 special ptids with it set to != 0. */
13742 magic_null_ptid = ptid_build (42000, -1, 1);
13743 not_sent_ptid = ptid_build (42000, -2, 1);
13744 any_thread_ptid = ptid_build (42000, 0, 1);
13745
13746 target_buf_size = 2048;
13747 target_buf = (char *) xmalloc (target_buf_size);
13748 }
13749
This page took 0.352469 seconds and 4 git commands to generate.