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