Remote thread create/exit events
[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 remote_thread_events (struct target_ops *ops, int enable);
143
144 static void sync_remote_interrupt_twice (int signo);
145
146 static void interrupt_query (void);
147
148 static void set_general_thread (struct ptid ptid);
149 static void set_continue_thread (struct ptid ptid);
150
151 static void get_offsets (void);
152
153 static void skip_frame (void);
154
155 static long read_frame (char **buf_p, long *sizeof_buf);
156
157 static int hexnumlen (ULONGEST num);
158
159 static void init_remote_ops (void);
160
161 static void init_extended_remote_ops (void);
162
163 static void remote_stop (struct target_ops *self, ptid_t);
164
165 static int stubhex (int ch);
166
167 static int hexnumstr (char *, ULONGEST);
168
169 static int hexnumnstr (char *, ULONGEST, int);
170
171 static CORE_ADDR remote_address_masked (CORE_ADDR);
172
173 static void print_packet (const char *);
174
175 static void compare_sections_command (char *, int);
176
177 static void packet_command (char *, int);
178
179 static int stub_unpack_int (char *buff, int fieldlength);
180
181 static ptid_t remote_current_thread (ptid_t oldptid);
182
183 static int putpkt_binary (const char *buf, int cnt);
184
185 static void check_binary_download (CORE_ADDR addr);
186
187 struct packet_config;
188
189 static void show_packet_config_cmd (struct packet_config *config);
190
191 static void show_remote_protocol_packet_cmd (struct ui_file *file,
192 int from_tty,
193 struct cmd_list_element *c,
194 const char *value);
195
196 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197 static ptid_t read_ptid (char *buf, char **obuf);
198
199 static void remote_set_permissions (struct target_ops *self);
200
201 static int remote_get_trace_status (struct target_ops *self,
202 struct trace_status *ts);
203
204 static int remote_upload_tracepoints (struct target_ops *self,
205 struct uploaded_tp **utpp);
206
207 static int remote_upload_trace_state_variables (struct target_ops *self,
208 struct uploaded_tsv **utsvp);
209
210 static void remote_query_supported (void);
211
212 static void remote_check_symbols (void);
213
214 void _initialize_remote (void);
215
216 struct stop_reply;
217 static void stop_reply_xfree (struct stop_reply *);
218 static void remote_parse_stop_reply (char *, struct stop_reply *);
219 static void push_stop_reply (struct stop_reply *);
220 static void discard_pending_stop_replies_in_queue (struct remote_state *);
221 static int peek_stop_reply (ptid_t ptid);
222
223 struct threads_listing_context;
224 static void remove_new_fork_children (struct threads_listing_context *);
225
226 static void remote_async_inferior_event_handler (gdb_client_data);
227
228 static void remote_terminal_ours (struct target_ops *self);
229
230 static int remote_read_description_p (struct target_ops *target);
231
232 static void remote_console_output (char *msg);
233
234 static int remote_supports_cond_breakpoints (struct target_ops *self);
235
236 static int remote_can_run_breakpoint_commands (struct target_ops *self);
237
238 static void remote_btrace_reset (void);
239
240 static int stop_reply_queue_length (void);
241
242 static void readahead_cache_invalidate (void);
243
244 /* For "remote". */
245
246 static struct cmd_list_element *remote_cmdlist;
247
248 /* For "set remote" and "show remote". */
249
250 static struct cmd_list_element *remote_set_cmdlist;
251 static struct cmd_list_element *remote_show_cmdlist;
252
253 /* Stub vCont actions support.
254
255 Each field is a boolean flag indicating whether the stub reports
256 support for the corresponding action. */
257
258 struct vCont_action_support
259 {
260 /* vCont;t */
261 int t;
262
263 /* vCont;r */
264 int r;
265
266 /* vCont;s */
267 int s;
268
269 /* vCont;S */
270 int S;
271 };
272
273 /* Controls whether GDB is willing to use range stepping. */
274
275 static int use_range_stepping = 1;
276
277 #define OPAQUETHREADBYTES 8
278
279 /* a 64 bit opaque identifier */
280 typedef unsigned char threadref[OPAQUETHREADBYTES];
281
282 /* About this many threadisds fit in a packet. */
283
284 #define MAXTHREADLISTRESULTS 32
285
286 /* Data for the vFile:pread readahead cache. */
287
288 struct readahead_cache
289 {
290 /* The file descriptor for the file that is being cached. -1 if the
291 cache is invalid. */
292 int fd;
293
294 /* The offset into the file that the cache buffer corresponds
295 to. */
296 ULONGEST offset;
297
298 /* The buffer holding the cache contents. */
299 gdb_byte *buf;
300 /* The buffer's size. We try to read as much as fits into a packet
301 at a time. */
302 size_t bufsize;
303
304 /* Cache hit and miss counters. */
305 ULONGEST hit_count;
306 ULONGEST miss_count;
307 };
308
309 /* Description of the remote protocol state for the currently
310 connected target. This is per-target state, and independent of the
311 selected architecture. */
312
313 struct remote_state
314 {
315 /* A buffer to use for incoming packets, and its current size. The
316 buffer is grown dynamically for larger incoming packets.
317 Outgoing packets may also be constructed in this buffer.
318 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320 packets. */
321 char *buf;
322 long buf_size;
323
324 /* True if we're going through initial connection setup (finding out
325 about the remote side's threads, relocating symbols, etc.). */
326 int starting_up;
327
328 /* If we negotiated packet size explicitly (and thus can bypass
329 heuristics for the largest packet size that will not overflow
330 a buffer in the stub), this will be set to that packet size.
331 Otherwise zero, meaning to use the guessed size. */
332 long explicit_packet_size;
333
334 /* remote_wait is normally called when the target is running and
335 waits for a stop reply packet. But sometimes we need to call it
336 when the target is already stopped. We can send a "?" packet
337 and have remote_wait read the response. Or, if we already have
338 the response, we can stash it in BUF and tell remote_wait to
339 skip calling getpkt. This flag is set when BUF contains a
340 stop reply packet and the target is not waiting. */
341 int cached_wait_status;
342
343 /* True, if in no ack mode. That is, neither GDB nor the stub will
344 expect acks from each other. The connection is assumed to be
345 reliable. */
346 int noack_mode;
347
348 /* True if we're connected in extended remote mode. */
349 int extended;
350
351 /* True if we resumed the target and we're waiting for the target to
352 stop. In the mean time, we can't start another command/query.
353 The remote server wouldn't be ready to process it, so we'd
354 timeout waiting for a reply that would never come and eventually
355 we'd close the connection. This can happen in asynchronous mode
356 because we allow GDB commands while the target is running. */
357 int waiting_for_stop_reply;
358
359 /* The status of the stub support for the various vCont actions. */
360 struct vCont_action_support supports_vCont;
361
362 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363 responded to that. */
364 int ctrlc_pending_p;
365
366 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
367 remote_open knows that we don't have a file open when the program
368 starts. */
369 struct serial *remote_desc;
370
371 /* These are the threads which we last sent to the remote system. The
372 TID member will be -1 for all or -2 for not sent yet. */
373 ptid_t general_thread;
374 ptid_t continue_thread;
375
376 /* This is the traceframe which we last selected on the remote system.
377 It will be -1 if no traceframe is selected. */
378 int remote_traceframe_number;
379
380 char *last_pass_packet;
381
382 /* The last QProgramSignals packet sent to the target. We bypass
383 sending a new program signals list down to the target if the new
384 packet is exactly the same as the last we sent. IOW, we only let
385 the target know about program signals list changes. */
386 char *last_program_signals_packet;
387
388 enum gdb_signal last_sent_signal;
389
390 int last_sent_step;
391
392 char *finished_object;
393 char *finished_annex;
394 ULONGEST finished_offset;
395
396 /* Should we try the 'ThreadInfo' query packet?
397
398 This variable (NOT available to the user: auto-detect only!)
399 determines whether GDB will use the new, simpler "ThreadInfo"
400 query or the older, more complex syntax for thread queries.
401 This is an auto-detect variable (set to true at each connect,
402 and set to false when the target fails to recognize it). */
403 int use_threadinfo_query;
404 int use_threadextra_query;
405
406 threadref echo_nextthread;
407 threadref nextthread;
408 threadref resultthreadlist[MAXTHREADLISTRESULTS];
409
410 /* The state of remote notification. */
411 struct remote_notif_state *notif_state;
412
413 /* The branch trace configuration. */
414 struct btrace_config btrace_config;
415
416 /* The argument to the last "vFile:setfs:" packet we sent, used
417 to avoid sending repeated unnecessary "vFile:setfs:" packets.
418 Initialized to -1 to indicate that no "vFile:setfs:" packet
419 has yet been sent. */
420 int fs_pid;
421
422 /* A readahead cache for vFile:pread. Often, reading a binary
423 involves a sequence of small reads. E.g., when parsing an ELF
424 file. A readahead cache helps mostly the case of remote
425 debugging on a connection with higher latency, due to the
426 request/reply nature of the RSP. We only cache data for a single
427 file descriptor at a time. */
428 struct readahead_cache readahead_cache;
429 };
430
431 /* Private data that we'll store in (struct thread_info)->private. */
432 struct private_thread_info
433 {
434 char *extra;
435 char *name;
436 int core;
437
438 /* Whether the target stopped for a breakpoint/watchpoint. */
439 enum target_stop_reason stop_reason;
440
441 /* This is set to the data address of the access causing the target
442 to stop for a watchpoint. */
443 CORE_ADDR watch_data_address;
444 };
445
446 static void
447 free_private_thread_info (struct private_thread_info *info)
448 {
449 xfree (info->extra);
450 xfree (info->name);
451 xfree (info);
452 }
453
454 /* This data could be associated with a target, but we do not always
455 have access to the current target when we need it, so for now it is
456 static. This will be fine for as long as only one target is in use
457 at a time. */
458 static struct remote_state *remote_state;
459
460 static struct remote_state *
461 get_remote_state_raw (void)
462 {
463 return remote_state;
464 }
465
466 /* Allocate a new struct remote_state with xmalloc, initialize it, and
467 return it. */
468
469 static struct remote_state *
470 new_remote_state (void)
471 {
472 struct remote_state *result = XCNEW (struct remote_state);
473
474 /* The default buffer size is unimportant; it will be expanded
475 whenever a larger buffer is needed. */
476 result->buf_size = 400;
477 result->buf = (char *) xmalloc (result->buf_size);
478 result->remote_traceframe_number = -1;
479 result->last_sent_signal = GDB_SIGNAL_0;
480 result->fs_pid = -1;
481
482 return result;
483 }
484
485 /* Description of the remote protocol for a given architecture. */
486
487 struct packet_reg
488 {
489 long offset; /* Offset into G packet. */
490 long regnum; /* GDB's internal register number. */
491 LONGEST pnum; /* Remote protocol register number. */
492 int in_g_packet; /* Always part of G packet. */
493 /* long size in bytes; == register_size (target_gdbarch (), regnum);
494 at present. */
495 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
496 at present. */
497 };
498
499 struct remote_arch_state
500 {
501 /* Description of the remote protocol registers. */
502 long sizeof_g_packet;
503
504 /* Description of the remote protocol registers indexed by REGNUM
505 (making an array gdbarch_num_regs in size). */
506 struct packet_reg *regs;
507
508 /* This is the size (in chars) of the first response to the ``g''
509 packet. It is used as a heuristic when determining the maximum
510 size of memory-read and memory-write packets. A target will
511 typically only reserve a buffer large enough to hold the ``g''
512 packet. The size does not include packet overhead (headers and
513 trailers). */
514 long actual_register_packet_size;
515
516 /* This is the maximum size (in chars) of a non read/write packet.
517 It is also used as a cap on the size of read/write packets. */
518 long remote_packet_size;
519 };
520
521 /* Utility: generate error from an incoming stub packet. */
522 static void
523 trace_error (char *buf)
524 {
525 if (*buf++ != 'E')
526 return; /* not an error msg */
527 switch (*buf)
528 {
529 case '1': /* malformed packet error */
530 if (*++buf == '0') /* general case: */
531 error (_("remote.c: error in outgoing packet."));
532 else
533 error (_("remote.c: error in outgoing packet at field #%ld."),
534 strtol (buf, NULL, 16));
535 default:
536 error (_("Target returns error code '%s'."), buf);
537 }
538 }
539
540 /* Utility: wait for reply from stub, while accepting "O" packets. */
541 static char *
542 remote_get_noisy_reply (char **buf_p,
543 long *sizeof_buf)
544 {
545 do /* Loop on reply from remote stub. */
546 {
547 char *buf;
548
549 QUIT; /* Allow user to bail out with ^C. */
550 getpkt (buf_p, sizeof_buf, 0);
551 buf = *buf_p;
552 if (buf[0] == 'E')
553 trace_error (buf);
554 else if (startswith (buf, "qRelocInsn:"))
555 {
556 ULONGEST ul;
557 CORE_ADDR from, to, org_to;
558 char *p, *pp;
559 int adjusted_size = 0;
560 int relocated = 0;
561
562 p = buf + strlen ("qRelocInsn:");
563 pp = unpack_varlen_hex (p, &ul);
564 if (*pp != ';')
565 error (_("invalid qRelocInsn packet: %s"), buf);
566 from = ul;
567
568 p = pp + 1;
569 unpack_varlen_hex (p, &ul);
570 to = ul;
571
572 org_to = to;
573
574 TRY
575 {
576 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
577 relocated = 1;
578 }
579 CATCH (ex, RETURN_MASK_ALL)
580 {
581 if (ex.error == MEMORY_ERROR)
582 {
583 /* Propagate memory errors silently back to the
584 target. The stub may have limited the range of
585 addresses we can write to, for example. */
586 }
587 else
588 {
589 /* Something unexpectedly bad happened. Be verbose
590 so we can tell what, and propagate the error back
591 to the stub, so it doesn't get stuck waiting for
592 a response. */
593 exception_fprintf (gdb_stderr, ex,
594 _("warning: relocating instruction: "));
595 }
596 putpkt ("E01");
597 }
598 END_CATCH
599
600 if (relocated)
601 {
602 adjusted_size = to - org_to;
603
604 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
605 putpkt (buf);
606 }
607 }
608 else if (buf[0] == 'O' && buf[1] != 'K')
609 remote_console_output (buf + 1); /* 'O' message from stub */
610 else
611 return buf; /* Here's the actual reply. */
612 }
613 while (1);
614 }
615
616 /* Handle for retreving the remote protocol data from gdbarch. */
617 static struct gdbarch_data *remote_gdbarch_data_handle;
618
619 static struct remote_arch_state *
620 get_remote_arch_state (void)
621 {
622 gdb_assert (target_gdbarch () != NULL);
623 return ((struct remote_arch_state *)
624 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
625 }
626
627 /* Fetch the global remote target state. */
628
629 static struct remote_state *
630 get_remote_state (void)
631 {
632 /* Make sure that the remote architecture state has been
633 initialized, because doing so might reallocate rs->buf. Any
634 function which calls getpkt also needs to be mindful of changes
635 to rs->buf, but this call limits the number of places which run
636 into trouble. */
637 get_remote_arch_state ();
638
639 return get_remote_state_raw ();
640 }
641
642 /* Cleanup routine for the remote module's pspace data. */
643
644 static void
645 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
646 {
647 char *remote_exec_file = (char *) arg;
648
649 xfree (remote_exec_file);
650 }
651
652 /* Fetch the remote exec-file from the current program space. */
653
654 static const char *
655 get_remote_exec_file (void)
656 {
657 char *remote_exec_file;
658
659 remote_exec_file
660 = (char *) program_space_data (current_program_space,
661 remote_pspace_data);
662 if (remote_exec_file == NULL)
663 return "";
664
665 return remote_exec_file;
666 }
667
668 /* Set the remote exec file for PSPACE. */
669
670 static void
671 set_pspace_remote_exec_file (struct program_space *pspace,
672 char *remote_exec_file)
673 {
674 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
675
676 xfree (old_file);
677 set_program_space_data (pspace, remote_pspace_data,
678 xstrdup (remote_exec_file));
679 }
680
681 /* The "set/show remote exec-file" set command hook. */
682
683 static void
684 set_remote_exec_file (char *ignored, int from_tty,
685 struct cmd_list_element *c)
686 {
687 gdb_assert (remote_exec_file_var != NULL);
688 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
689 }
690
691 /* The "set/show remote exec-file" show command hook. */
692
693 static void
694 show_remote_exec_file (struct ui_file *file, int from_tty,
695 struct cmd_list_element *cmd, const char *value)
696 {
697 fprintf_filtered (file, "%s\n", remote_exec_file_var);
698 }
699
700 static int
701 compare_pnums (const void *lhs_, const void *rhs_)
702 {
703 const struct packet_reg * const *lhs
704 = (const struct packet_reg * const *) lhs_;
705 const struct packet_reg * const *rhs
706 = (const struct packet_reg * const *) rhs_;
707
708 if ((*lhs)->pnum < (*rhs)->pnum)
709 return -1;
710 else if ((*lhs)->pnum == (*rhs)->pnum)
711 return 0;
712 else
713 return 1;
714 }
715
716 static int
717 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
718 {
719 int regnum, num_remote_regs, offset;
720 struct packet_reg **remote_regs;
721
722 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
723 {
724 struct packet_reg *r = &regs[regnum];
725
726 if (register_size (gdbarch, regnum) == 0)
727 /* Do not try to fetch zero-sized (placeholder) registers. */
728 r->pnum = -1;
729 else
730 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
731
732 r->regnum = regnum;
733 }
734
735 /* Define the g/G packet format as the contents of each register
736 with a remote protocol number, in order of ascending protocol
737 number. */
738
739 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
740 for (num_remote_regs = 0, regnum = 0;
741 regnum < gdbarch_num_regs (gdbarch);
742 regnum++)
743 if (regs[regnum].pnum != -1)
744 remote_regs[num_remote_regs++] = &regs[regnum];
745
746 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
747 compare_pnums);
748
749 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
750 {
751 remote_regs[regnum]->in_g_packet = 1;
752 remote_regs[regnum]->offset = offset;
753 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
754 }
755
756 return offset;
757 }
758
759 /* Given the architecture described by GDBARCH, return the remote
760 protocol register's number and the register's offset in the g/G
761 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
762 If the target does not have a mapping for REGNUM, return false,
763 otherwise, return true. */
764
765 int
766 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
767 int *pnum, int *poffset)
768 {
769 int sizeof_g_packet;
770 struct packet_reg *regs;
771 struct cleanup *old_chain;
772
773 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
774
775 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
776 old_chain = make_cleanup (xfree, regs);
777
778 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
779
780 *pnum = regs[regnum].pnum;
781 *poffset = regs[regnum].offset;
782
783 do_cleanups (old_chain);
784
785 return *pnum != -1;
786 }
787
788 static void *
789 init_remote_state (struct gdbarch *gdbarch)
790 {
791 struct remote_state *rs = get_remote_state_raw ();
792 struct remote_arch_state *rsa;
793
794 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
795
796 /* Use the architecture to build a regnum<->pnum table, which will be
797 1:1 unless a feature set specifies otherwise. */
798 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
799 gdbarch_num_regs (gdbarch),
800 struct packet_reg);
801
802 /* Record the maximum possible size of the g packet - it may turn out
803 to be smaller. */
804 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
805
806 /* Default maximum number of characters in a packet body. Many
807 remote stubs have a hardwired buffer size of 400 bytes
808 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
809 as the maximum packet-size to ensure that the packet and an extra
810 NUL character can always fit in the buffer. This stops GDB
811 trashing stubs that try to squeeze an extra NUL into what is
812 already a full buffer (As of 1999-12-04 that was most stubs). */
813 rsa->remote_packet_size = 400 - 1;
814
815 /* This one is filled in when a ``g'' packet is received. */
816 rsa->actual_register_packet_size = 0;
817
818 /* Should rsa->sizeof_g_packet needs more space than the
819 default, adjust the size accordingly. Remember that each byte is
820 encoded as two characters. 32 is the overhead for the packet
821 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
822 (``$NN:G...#NN'') is a better guess, the below has been padded a
823 little. */
824 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
825 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
826
827 /* Make sure that the packet buffer is plenty big enough for
828 this architecture. */
829 if (rs->buf_size < rsa->remote_packet_size)
830 {
831 rs->buf_size = 2 * rsa->remote_packet_size;
832 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
833 }
834
835 return rsa;
836 }
837
838 /* Return the current allowed size of a remote packet. This is
839 inferred from the current architecture, and should be used to
840 limit the length of outgoing packets. */
841 static long
842 get_remote_packet_size (void)
843 {
844 struct remote_state *rs = get_remote_state ();
845 struct remote_arch_state *rsa = get_remote_arch_state ();
846
847 if (rs->explicit_packet_size)
848 return rs->explicit_packet_size;
849
850 return rsa->remote_packet_size;
851 }
852
853 static struct packet_reg *
854 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
855 {
856 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
857 return NULL;
858 else
859 {
860 struct packet_reg *r = &rsa->regs[regnum];
861
862 gdb_assert (r->regnum == regnum);
863 return r;
864 }
865 }
866
867 static struct packet_reg *
868 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
869 {
870 int i;
871
872 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
873 {
874 struct packet_reg *r = &rsa->regs[i];
875
876 if (r->pnum == pnum)
877 return r;
878 }
879 return NULL;
880 }
881
882 static struct target_ops remote_ops;
883
884 static struct target_ops extended_remote_ops;
885
886 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
887 ``forever'' still use the normal timeout mechanism. This is
888 currently used by the ASYNC code to guarentee that target reads
889 during the initial connect always time-out. Once getpkt has been
890 modified to return a timeout indication and, in turn
891 remote_wait()/wait_for_inferior() have gained a timeout parameter
892 this can go away. */
893 static int wait_forever_enabled_p = 1;
894
895 /* Allow the user to specify what sequence to send to the remote
896 when he requests a program interruption: Although ^C is usually
897 what remote systems expect (this is the default, here), it is
898 sometimes preferable to send a break. On other systems such
899 as the Linux kernel, a break followed by g, which is Magic SysRq g
900 is required in order to interrupt the execution. */
901 const char interrupt_sequence_control_c[] = "Ctrl-C";
902 const char interrupt_sequence_break[] = "BREAK";
903 const char interrupt_sequence_break_g[] = "BREAK-g";
904 static const char *const interrupt_sequence_modes[] =
905 {
906 interrupt_sequence_control_c,
907 interrupt_sequence_break,
908 interrupt_sequence_break_g,
909 NULL
910 };
911 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
912
913 static void
914 show_interrupt_sequence (struct ui_file *file, int from_tty,
915 struct cmd_list_element *c,
916 const char *value)
917 {
918 if (interrupt_sequence_mode == interrupt_sequence_control_c)
919 fprintf_filtered (file,
920 _("Send the ASCII ETX character (Ctrl-c) "
921 "to the remote target to interrupt the "
922 "execution of the program.\n"));
923 else if (interrupt_sequence_mode == interrupt_sequence_break)
924 fprintf_filtered (file,
925 _("send a break signal to the remote target "
926 "to interrupt the execution of the program.\n"));
927 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
928 fprintf_filtered (file,
929 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
930 "the remote target to interrupt the execution "
931 "of Linux kernel.\n"));
932 else
933 internal_error (__FILE__, __LINE__,
934 _("Invalid value for interrupt_sequence_mode: %s."),
935 interrupt_sequence_mode);
936 }
937
938 /* This boolean variable specifies whether interrupt_sequence is sent
939 to the remote target when gdb connects to it.
940 This is mostly needed when you debug the Linux kernel: The Linux kernel
941 expects BREAK g which is Magic SysRq g for connecting gdb. */
942 static int interrupt_on_connect = 0;
943
944 /* This variable is used to implement the "set/show remotebreak" commands.
945 Since these commands are now deprecated in favor of "set/show remote
946 interrupt-sequence", it no longer has any effect on the code. */
947 static int remote_break;
948
949 static void
950 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
951 {
952 if (remote_break)
953 interrupt_sequence_mode = interrupt_sequence_break;
954 else
955 interrupt_sequence_mode = interrupt_sequence_control_c;
956 }
957
958 static void
959 show_remotebreak (struct ui_file *file, int from_tty,
960 struct cmd_list_element *c,
961 const char *value)
962 {
963 }
964
965 /* This variable sets the number of bits in an address that are to be
966 sent in a memory ("M" or "m") packet. Normally, after stripping
967 leading zeros, the entire address would be sent. This variable
968 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
969 initial implementation of remote.c restricted the address sent in
970 memory packets to ``host::sizeof long'' bytes - (typically 32
971 bits). Consequently, for 64 bit targets, the upper 32 bits of an
972 address was never sent. Since fixing this bug may cause a break in
973 some remote targets this variable is principly provided to
974 facilitate backward compatibility. */
975
976 static unsigned int remote_address_size;
977
978 /* Temporary to track who currently owns the terminal. See
979 remote_terminal_* for more details. */
980
981 static int remote_async_terminal_ours_p;
982
983 \f
984 /* User configurable variables for the number of characters in a
985 memory read/write packet. MIN (rsa->remote_packet_size,
986 rsa->sizeof_g_packet) is the default. Some targets need smaller
987 values (fifo overruns, et.al.) and some users need larger values
988 (speed up transfers). The variables ``preferred_*'' (the user
989 request), ``current_*'' (what was actually set) and ``forced_*''
990 (Positive - a soft limit, negative - a hard limit). */
991
992 struct memory_packet_config
993 {
994 char *name;
995 long size;
996 int fixed_p;
997 };
998
999 /* The default max memory-write-packet-size. The 16k is historical.
1000 (It came from older GDB's using alloca for buffers and the
1001 knowledge (folklore?) that some hosts don't cope very well with
1002 large alloca calls.) */
1003 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1004
1005 /* The minimum remote packet size for memory transfers. Ensures we
1006 can write at least one byte. */
1007 #define MIN_MEMORY_PACKET_SIZE 20
1008
1009 /* Compute the current size of a read/write packet. Since this makes
1010 use of ``actual_register_packet_size'' the computation is dynamic. */
1011
1012 static long
1013 get_memory_packet_size (struct memory_packet_config *config)
1014 {
1015 struct remote_state *rs = get_remote_state ();
1016 struct remote_arch_state *rsa = get_remote_arch_state ();
1017
1018 long what_they_get;
1019 if (config->fixed_p)
1020 {
1021 if (config->size <= 0)
1022 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1023 else
1024 what_they_get = config->size;
1025 }
1026 else
1027 {
1028 what_they_get = get_remote_packet_size ();
1029 /* Limit the packet to the size specified by the user. */
1030 if (config->size > 0
1031 && what_they_get > config->size)
1032 what_they_get = config->size;
1033
1034 /* Limit it to the size of the targets ``g'' response unless we have
1035 permission from the stub to use a larger packet size. */
1036 if (rs->explicit_packet_size == 0
1037 && rsa->actual_register_packet_size > 0
1038 && what_they_get > rsa->actual_register_packet_size)
1039 what_they_get = rsa->actual_register_packet_size;
1040 }
1041 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1042 what_they_get = MIN_MEMORY_PACKET_SIZE;
1043
1044 /* Make sure there is room in the global buffer for this packet
1045 (including its trailing NUL byte). */
1046 if (rs->buf_size < what_they_get + 1)
1047 {
1048 rs->buf_size = 2 * what_they_get;
1049 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1050 }
1051
1052 return what_they_get;
1053 }
1054
1055 /* Update the size of a read/write packet. If they user wants
1056 something really big then do a sanity check. */
1057
1058 static void
1059 set_memory_packet_size (char *args, struct memory_packet_config *config)
1060 {
1061 int fixed_p = config->fixed_p;
1062 long size = config->size;
1063
1064 if (args == NULL)
1065 error (_("Argument required (integer, `fixed' or `limited')."));
1066 else if (strcmp (args, "hard") == 0
1067 || strcmp (args, "fixed") == 0)
1068 fixed_p = 1;
1069 else if (strcmp (args, "soft") == 0
1070 || strcmp (args, "limit") == 0)
1071 fixed_p = 0;
1072 else
1073 {
1074 char *end;
1075
1076 size = strtoul (args, &end, 0);
1077 if (args == end)
1078 error (_("Invalid %s (bad syntax)."), config->name);
1079
1080 /* Instead of explicitly capping the size of a packet to or
1081 disallowing it, the user is allowed to set the size to
1082 something arbitrarily large. */
1083 }
1084
1085 /* So that the query shows the correct value. */
1086 if (size <= 0)
1087 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1088
1089 /* Extra checks? */
1090 if (fixed_p && !config->fixed_p)
1091 {
1092 if (! query (_("The target may not be able to correctly handle a %s\n"
1093 "of %ld bytes. Change the packet size? "),
1094 config->name, size))
1095 error (_("Packet size not changed."));
1096 }
1097 /* Update the config. */
1098 config->fixed_p = fixed_p;
1099 config->size = size;
1100 }
1101
1102 static void
1103 show_memory_packet_size (struct memory_packet_config *config)
1104 {
1105 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1106 if (config->fixed_p)
1107 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1108 get_memory_packet_size (config));
1109 else
1110 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1111 get_memory_packet_size (config));
1112 }
1113
1114 static struct memory_packet_config memory_write_packet_config =
1115 {
1116 "memory-write-packet-size",
1117 };
1118
1119 static void
1120 set_memory_write_packet_size (char *args, int from_tty)
1121 {
1122 set_memory_packet_size (args, &memory_write_packet_config);
1123 }
1124
1125 static void
1126 show_memory_write_packet_size (char *args, int from_tty)
1127 {
1128 show_memory_packet_size (&memory_write_packet_config);
1129 }
1130
1131 static long
1132 get_memory_write_packet_size (void)
1133 {
1134 return get_memory_packet_size (&memory_write_packet_config);
1135 }
1136
1137 static struct memory_packet_config memory_read_packet_config =
1138 {
1139 "memory-read-packet-size",
1140 };
1141
1142 static void
1143 set_memory_read_packet_size (char *args, int from_tty)
1144 {
1145 set_memory_packet_size (args, &memory_read_packet_config);
1146 }
1147
1148 static void
1149 show_memory_read_packet_size (char *args, int from_tty)
1150 {
1151 show_memory_packet_size (&memory_read_packet_config);
1152 }
1153
1154 static long
1155 get_memory_read_packet_size (void)
1156 {
1157 long size = get_memory_packet_size (&memory_read_packet_config);
1158
1159 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1160 extra buffer size argument before the memory read size can be
1161 increased beyond this. */
1162 if (size > get_remote_packet_size ())
1163 size = get_remote_packet_size ();
1164 return size;
1165 }
1166
1167 \f
1168 /* Generic configuration support for packets the stub optionally
1169 supports. Allows the user to specify the use of the packet as well
1170 as allowing GDB to auto-detect support in the remote stub. */
1171
1172 enum packet_support
1173 {
1174 PACKET_SUPPORT_UNKNOWN = 0,
1175 PACKET_ENABLE,
1176 PACKET_DISABLE
1177 };
1178
1179 struct packet_config
1180 {
1181 const char *name;
1182 const char *title;
1183
1184 /* If auto, GDB auto-detects support for this packet or feature,
1185 either through qSupported, or by trying the packet and looking
1186 at the response. If true, GDB assumes the target supports this
1187 packet. If false, the packet is disabled. Configs that don't
1188 have an associated command always have this set to auto. */
1189 enum auto_boolean detect;
1190
1191 /* Does the target support this packet? */
1192 enum packet_support support;
1193 };
1194
1195 /* Analyze a packet's return value and update the packet config
1196 accordingly. */
1197
1198 enum packet_result
1199 {
1200 PACKET_ERROR,
1201 PACKET_OK,
1202 PACKET_UNKNOWN
1203 };
1204
1205 static enum packet_support packet_config_support (struct packet_config *config);
1206 static enum packet_support packet_support (int packet);
1207
1208 static void
1209 show_packet_config_cmd (struct packet_config *config)
1210 {
1211 char *support = "internal-error";
1212
1213 switch (packet_config_support (config))
1214 {
1215 case PACKET_ENABLE:
1216 support = "enabled";
1217 break;
1218 case PACKET_DISABLE:
1219 support = "disabled";
1220 break;
1221 case PACKET_SUPPORT_UNKNOWN:
1222 support = "unknown";
1223 break;
1224 }
1225 switch (config->detect)
1226 {
1227 case AUTO_BOOLEAN_AUTO:
1228 printf_filtered (_("Support for the `%s' packet "
1229 "is auto-detected, currently %s.\n"),
1230 config->name, support);
1231 break;
1232 case AUTO_BOOLEAN_TRUE:
1233 case AUTO_BOOLEAN_FALSE:
1234 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1235 config->name, support);
1236 break;
1237 }
1238 }
1239
1240 static void
1241 add_packet_config_cmd (struct packet_config *config, const char *name,
1242 const char *title, int legacy)
1243 {
1244 char *set_doc;
1245 char *show_doc;
1246 char *cmd_name;
1247
1248 config->name = name;
1249 config->title = title;
1250 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1251 name, title);
1252 show_doc = xstrprintf ("Show current use of remote "
1253 "protocol `%s' (%s) packet",
1254 name, title);
1255 /* set/show TITLE-packet {auto,on,off} */
1256 cmd_name = xstrprintf ("%s-packet", title);
1257 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1258 &config->detect, set_doc,
1259 show_doc, NULL, /* help_doc */
1260 NULL,
1261 show_remote_protocol_packet_cmd,
1262 &remote_set_cmdlist, &remote_show_cmdlist);
1263 /* The command code copies the documentation strings. */
1264 xfree (set_doc);
1265 xfree (show_doc);
1266 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1267 if (legacy)
1268 {
1269 char *legacy_name;
1270
1271 legacy_name = xstrprintf ("%s-packet", name);
1272 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1273 &remote_set_cmdlist);
1274 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1275 &remote_show_cmdlist);
1276 }
1277 }
1278
1279 static enum packet_result
1280 packet_check_result (const char *buf)
1281 {
1282 if (buf[0] != '\0')
1283 {
1284 /* The stub recognized the packet request. Check that the
1285 operation succeeded. */
1286 if (buf[0] == 'E'
1287 && isxdigit (buf[1]) && isxdigit (buf[2])
1288 && buf[3] == '\0')
1289 /* "Enn" - definitly an error. */
1290 return PACKET_ERROR;
1291
1292 /* Always treat "E." as an error. This will be used for
1293 more verbose error messages, such as E.memtypes. */
1294 if (buf[0] == 'E' && buf[1] == '.')
1295 return PACKET_ERROR;
1296
1297 /* The packet may or may not be OK. Just assume it is. */
1298 return PACKET_OK;
1299 }
1300 else
1301 /* The stub does not support the packet. */
1302 return PACKET_UNKNOWN;
1303 }
1304
1305 static enum packet_result
1306 packet_ok (const char *buf, struct packet_config *config)
1307 {
1308 enum packet_result result;
1309
1310 if (config->detect != AUTO_BOOLEAN_TRUE
1311 && config->support == PACKET_DISABLE)
1312 internal_error (__FILE__, __LINE__,
1313 _("packet_ok: attempt to use a disabled packet"));
1314
1315 result = packet_check_result (buf);
1316 switch (result)
1317 {
1318 case PACKET_OK:
1319 case PACKET_ERROR:
1320 /* The stub recognized the packet request. */
1321 if (config->support == PACKET_SUPPORT_UNKNOWN)
1322 {
1323 if (remote_debug)
1324 fprintf_unfiltered (gdb_stdlog,
1325 "Packet %s (%s) is supported\n",
1326 config->name, config->title);
1327 config->support = PACKET_ENABLE;
1328 }
1329 break;
1330 case PACKET_UNKNOWN:
1331 /* The stub does not support the packet. */
1332 if (config->detect == AUTO_BOOLEAN_AUTO
1333 && config->support == PACKET_ENABLE)
1334 {
1335 /* If the stub previously indicated that the packet was
1336 supported then there is a protocol error. */
1337 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1338 config->name, config->title);
1339 }
1340 else if (config->detect == AUTO_BOOLEAN_TRUE)
1341 {
1342 /* The user set it wrong. */
1343 error (_("Enabled packet %s (%s) not recognized by stub"),
1344 config->name, config->title);
1345 }
1346
1347 if (remote_debug)
1348 fprintf_unfiltered (gdb_stdlog,
1349 "Packet %s (%s) is NOT supported\n",
1350 config->name, config->title);
1351 config->support = PACKET_DISABLE;
1352 break;
1353 }
1354
1355 return result;
1356 }
1357
1358 enum {
1359 PACKET_vCont = 0,
1360 PACKET_X,
1361 PACKET_qSymbol,
1362 PACKET_P,
1363 PACKET_p,
1364 PACKET_Z0,
1365 PACKET_Z1,
1366 PACKET_Z2,
1367 PACKET_Z3,
1368 PACKET_Z4,
1369 PACKET_vFile_setfs,
1370 PACKET_vFile_open,
1371 PACKET_vFile_pread,
1372 PACKET_vFile_pwrite,
1373 PACKET_vFile_close,
1374 PACKET_vFile_unlink,
1375 PACKET_vFile_readlink,
1376 PACKET_vFile_fstat,
1377 PACKET_qXfer_auxv,
1378 PACKET_qXfer_features,
1379 PACKET_qXfer_exec_file,
1380 PACKET_qXfer_libraries,
1381 PACKET_qXfer_libraries_svr4,
1382 PACKET_qXfer_memory_map,
1383 PACKET_qXfer_spu_read,
1384 PACKET_qXfer_spu_write,
1385 PACKET_qXfer_osdata,
1386 PACKET_qXfer_threads,
1387 PACKET_qXfer_statictrace_read,
1388 PACKET_qXfer_traceframe_info,
1389 PACKET_qXfer_uib,
1390 PACKET_qGetTIBAddr,
1391 PACKET_qGetTLSAddr,
1392 PACKET_qSupported,
1393 PACKET_qTStatus,
1394 PACKET_QPassSignals,
1395 PACKET_QProgramSignals,
1396 PACKET_qCRC,
1397 PACKET_qSearch_memory,
1398 PACKET_vAttach,
1399 PACKET_vRun,
1400 PACKET_QStartNoAckMode,
1401 PACKET_vKill,
1402 PACKET_qXfer_siginfo_read,
1403 PACKET_qXfer_siginfo_write,
1404 PACKET_qAttached,
1405
1406 /* Support for conditional tracepoints. */
1407 PACKET_ConditionalTracepoints,
1408
1409 /* Support for target-side breakpoint conditions. */
1410 PACKET_ConditionalBreakpoints,
1411
1412 /* Support for target-side breakpoint commands. */
1413 PACKET_BreakpointCommands,
1414
1415 /* Support for fast tracepoints. */
1416 PACKET_FastTracepoints,
1417
1418 /* Support for static tracepoints. */
1419 PACKET_StaticTracepoints,
1420
1421 /* Support for installing tracepoints while a trace experiment is
1422 running. */
1423 PACKET_InstallInTrace,
1424
1425 PACKET_bc,
1426 PACKET_bs,
1427 PACKET_TracepointSource,
1428 PACKET_QAllow,
1429 PACKET_qXfer_fdpic,
1430 PACKET_QDisableRandomization,
1431 PACKET_QAgent,
1432 PACKET_QTBuffer_size,
1433 PACKET_Qbtrace_off,
1434 PACKET_Qbtrace_bts,
1435 PACKET_Qbtrace_pt,
1436 PACKET_qXfer_btrace,
1437
1438 /* Support for the QNonStop packet. */
1439 PACKET_QNonStop,
1440
1441 /* Support for the QThreadEvents packet. */
1442 PACKET_QThreadEvents,
1443
1444 /* Support for multi-process extensions. */
1445 PACKET_multiprocess_feature,
1446
1447 /* Support for enabling and disabling tracepoints while a trace
1448 experiment is running. */
1449 PACKET_EnableDisableTracepoints_feature,
1450
1451 /* Support for collecting strings using the tracenz bytecode. */
1452 PACKET_tracenz_feature,
1453
1454 /* Support for continuing to run a trace experiment while GDB is
1455 disconnected. */
1456 PACKET_DisconnectedTracing_feature,
1457
1458 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1459 PACKET_augmented_libraries_svr4_read_feature,
1460
1461 /* Support for the qXfer:btrace-conf:read packet. */
1462 PACKET_qXfer_btrace_conf,
1463
1464 /* Support for the Qbtrace-conf:bts:size packet. */
1465 PACKET_Qbtrace_conf_bts_size,
1466
1467 /* Support for swbreak+ feature. */
1468 PACKET_swbreak_feature,
1469
1470 /* Support for hwbreak+ feature. */
1471 PACKET_hwbreak_feature,
1472
1473 /* Support for fork events. */
1474 PACKET_fork_event_feature,
1475
1476 /* Support for vfork events. */
1477 PACKET_vfork_event_feature,
1478
1479 /* Support for the Qbtrace-conf:pt:size packet. */
1480 PACKET_Qbtrace_conf_pt_size,
1481
1482 /* Support for exec events. */
1483 PACKET_exec_event_feature,
1484
1485 /* Support for query supported vCont actions. */
1486 PACKET_vContSupported,
1487
1488 /* Support remote CTRL-C. */
1489 PACKET_vCtrlC,
1490
1491 PACKET_MAX
1492 };
1493
1494 static struct packet_config remote_protocol_packets[PACKET_MAX];
1495
1496 /* Returns the packet's corresponding "set remote foo-packet" command
1497 state. See struct packet_config for more details. */
1498
1499 static enum auto_boolean
1500 packet_set_cmd_state (int packet)
1501 {
1502 return remote_protocol_packets[packet].detect;
1503 }
1504
1505 /* Returns whether a given packet or feature is supported. This takes
1506 into account the state of the corresponding "set remote foo-packet"
1507 command, which may be used to bypass auto-detection. */
1508
1509 static enum packet_support
1510 packet_config_support (struct packet_config *config)
1511 {
1512 switch (config->detect)
1513 {
1514 case AUTO_BOOLEAN_TRUE:
1515 return PACKET_ENABLE;
1516 case AUTO_BOOLEAN_FALSE:
1517 return PACKET_DISABLE;
1518 case AUTO_BOOLEAN_AUTO:
1519 return config->support;
1520 default:
1521 gdb_assert_not_reached (_("bad switch"));
1522 }
1523 }
1524
1525 /* Same as packet_config_support, but takes the packet's enum value as
1526 argument. */
1527
1528 static enum packet_support
1529 packet_support (int packet)
1530 {
1531 struct packet_config *config = &remote_protocol_packets[packet];
1532
1533 return packet_config_support (config);
1534 }
1535
1536 static void
1537 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1538 struct cmd_list_element *c,
1539 const char *value)
1540 {
1541 struct packet_config *packet;
1542
1543 for (packet = remote_protocol_packets;
1544 packet < &remote_protocol_packets[PACKET_MAX];
1545 packet++)
1546 {
1547 if (&packet->detect == c->var)
1548 {
1549 show_packet_config_cmd (packet);
1550 return;
1551 }
1552 }
1553 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1554 c->name);
1555 }
1556
1557 /* Should we try one of the 'Z' requests? */
1558
1559 enum Z_packet_type
1560 {
1561 Z_PACKET_SOFTWARE_BP,
1562 Z_PACKET_HARDWARE_BP,
1563 Z_PACKET_WRITE_WP,
1564 Z_PACKET_READ_WP,
1565 Z_PACKET_ACCESS_WP,
1566 NR_Z_PACKET_TYPES
1567 };
1568
1569 /* For compatibility with older distributions. Provide a ``set remote
1570 Z-packet ...'' command that updates all the Z packet types. */
1571
1572 static enum auto_boolean remote_Z_packet_detect;
1573
1574 static void
1575 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1576 struct cmd_list_element *c)
1577 {
1578 int i;
1579
1580 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1581 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1582 }
1583
1584 static void
1585 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1586 struct cmd_list_element *c,
1587 const char *value)
1588 {
1589 int i;
1590
1591 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1592 {
1593 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1594 }
1595 }
1596
1597 /* Returns true if the multi-process extensions are in effect. */
1598
1599 static int
1600 remote_multi_process_p (struct remote_state *rs)
1601 {
1602 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1603 }
1604
1605 /* Returns true if fork events are supported. */
1606
1607 static int
1608 remote_fork_event_p (struct remote_state *rs)
1609 {
1610 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1611 }
1612
1613 /* Returns true if vfork events are supported. */
1614
1615 static int
1616 remote_vfork_event_p (struct remote_state *rs)
1617 {
1618 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1619 }
1620
1621 /* Returns true if exec events are supported. */
1622
1623 static int
1624 remote_exec_event_p (struct remote_state *rs)
1625 {
1626 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1627 }
1628
1629 /* Insert fork catchpoint target routine. If fork events are enabled
1630 then return success, nothing more to do. */
1631
1632 static int
1633 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1634 {
1635 struct remote_state *rs = get_remote_state ();
1636
1637 return !remote_fork_event_p (rs);
1638 }
1639
1640 /* Remove fork catchpoint target routine. Nothing to do, just
1641 return success. */
1642
1643 static int
1644 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1645 {
1646 return 0;
1647 }
1648
1649 /* Insert vfork catchpoint target routine. If vfork events are enabled
1650 then return success, nothing more to do. */
1651
1652 static int
1653 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1654 {
1655 struct remote_state *rs = get_remote_state ();
1656
1657 return !remote_vfork_event_p (rs);
1658 }
1659
1660 /* Remove vfork catchpoint target routine. Nothing to do, just
1661 return success. */
1662
1663 static int
1664 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1665 {
1666 return 0;
1667 }
1668
1669 /* Insert exec catchpoint target routine. If exec events are
1670 enabled, just return success. */
1671
1672 static int
1673 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1674 {
1675 struct remote_state *rs = get_remote_state ();
1676
1677 return !remote_exec_event_p (rs);
1678 }
1679
1680 /* Remove exec catchpoint target routine. Nothing to do, just
1681 return success. */
1682
1683 static int
1684 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1685 {
1686 return 0;
1687 }
1688
1689 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1690 static struct async_signal_handler *async_sigint_remote_twice_token;
1691 static struct async_signal_handler *async_sigint_remote_token;
1692
1693 \f
1694 /* Asynchronous signal handle registered as event loop source for
1695 when we have pending events ready to be passed to the core. */
1696
1697 static struct async_event_handler *remote_async_inferior_event_token;
1698
1699 \f
1700
1701 static ptid_t magic_null_ptid;
1702 static ptid_t not_sent_ptid;
1703 static ptid_t any_thread_ptid;
1704
1705 /* Find out if the stub attached to PID (and hence GDB should offer to
1706 detach instead of killing it when bailing out). */
1707
1708 static int
1709 remote_query_attached (int pid)
1710 {
1711 struct remote_state *rs = get_remote_state ();
1712 size_t size = get_remote_packet_size ();
1713
1714 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1715 return 0;
1716
1717 if (remote_multi_process_p (rs))
1718 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1719 else
1720 xsnprintf (rs->buf, size, "qAttached");
1721
1722 putpkt (rs->buf);
1723 getpkt (&rs->buf, &rs->buf_size, 0);
1724
1725 switch (packet_ok (rs->buf,
1726 &remote_protocol_packets[PACKET_qAttached]))
1727 {
1728 case PACKET_OK:
1729 if (strcmp (rs->buf, "1") == 0)
1730 return 1;
1731 break;
1732 case PACKET_ERROR:
1733 warning (_("Remote failure reply: %s"), rs->buf);
1734 break;
1735 case PACKET_UNKNOWN:
1736 break;
1737 }
1738
1739 return 0;
1740 }
1741
1742 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1743 has been invented by GDB, instead of reported by the target. Since
1744 we can be connected to a remote system before before knowing about
1745 any inferior, mark the target with execution when we find the first
1746 inferior. If ATTACHED is 1, then we had just attached to this
1747 inferior. If it is 0, then we just created this inferior. If it
1748 is -1, then try querying the remote stub to find out if it had
1749 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1750 attempt to open this inferior's executable as the main executable
1751 if no main executable is open already. */
1752
1753 static struct inferior *
1754 remote_add_inferior (int fake_pid_p, int pid, int attached,
1755 int try_open_exec)
1756 {
1757 struct inferior *inf;
1758
1759 /* Check whether this process we're learning about is to be
1760 considered attached, or if is to be considered to have been
1761 spawned by the stub. */
1762 if (attached == -1)
1763 attached = remote_query_attached (pid);
1764
1765 if (gdbarch_has_global_solist (target_gdbarch ()))
1766 {
1767 /* If the target shares code across all inferiors, then every
1768 attach adds a new inferior. */
1769 inf = add_inferior (pid);
1770
1771 /* ... and every inferior is bound to the same program space.
1772 However, each inferior may still have its own address
1773 space. */
1774 inf->aspace = maybe_new_address_space ();
1775 inf->pspace = current_program_space;
1776 }
1777 else
1778 {
1779 /* In the traditional debugging scenario, there's a 1-1 match
1780 between program/address spaces. We simply bind the inferior
1781 to the program space's address space. */
1782 inf = current_inferior ();
1783 inferior_appeared (inf, pid);
1784 }
1785
1786 inf->attach_flag = attached;
1787 inf->fake_pid_p = fake_pid_p;
1788
1789 /* If no main executable is currently open then attempt to
1790 open the file that was executed to create this inferior. */
1791 if (try_open_exec && get_exec_file (0) == NULL)
1792 exec_file_locate_attach (pid, 1);
1793
1794 return inf;
1795 }
1796
1797 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1798 according to RUNNING. */
1799
1800 static void
1801 remote_add_thread (ptid_t ptid, int running)
1802 {
1803 struct remote_state *rs = get_remote_state ();
1804
1805 /* GDB historically didn't pull threads in the initial connection
1806 setup. If the remote target doesn't even have a concept of
1807 threads (e.g., a bare-metal target), even if internally we
1808 consider that a single-threaded target, mentioning a new thread
1809 might be confusing to the user. Be silent then, preserving the
1810 age old behavior. */
1811 if (rs->starting_up)
1812 add_thread_silent (ptid);
1813 else
1814 add_thread (ptid);
1815
1816 set_executing (ptid, running);
1817 set_running (ptid, running);
1818 }
1819
1820 /* Come here when we learn about a thread id from the remote target.
1821 It may be the first time we hear about such thread, so take the
1822 opportunity to add it to GDB's thread list. In case this is the
1823 first time we're noticing its corresponding inferior, add it to
1824 GDB's inferior list as well. */
1825
1826 static void
1827 remote_notice_new_inferior (ptid_t currthread, int running)
1828 {
1829 /* If this is a new thread, add it to GDB's thread list.
1830 If we leave it up to WFI to do this, bad things will happen. */
1831
1832 if (in_thread_list (currthread) && is_exited (currthread))
1833 {
1834 /* We're seeing an event on a thread id we knew had exited.
1835 This has to be a new thread reusing the old id. Add it. */
1836 remote_add_thread (currthread, running);
1837 return;
1838 }
1839
1840 if (!in_thread_list (currthread))
1841 {
1842 struct inferior *inf = NULL;
1843 int pid = ptid_get_pid (currthread);
1844
1845 if (ptid_is_pid (inferior_ptid)
1846 && pid == ptid_get_pid (inferior_ptid))
1847 {
1848 /* inferior_ptid has no thread member yet. This can happen
1849 with the vAttach -> remote_wait,"TAAthread:" path if the
1850 stub doesn't support qC. This is the first stop reported
1851 after an attach, so this is the main thread. Update the
1852 ptid in the thread list. */
1853 if (in_thread_list (pid_to_ptid (pid)))
1854 thread_change_ptid (inferior_ptid, currthread);
1855 else
1856 {
1857 remote_add_thread (currthread, running);
1858 inferior_ptid = currthread;
1859 }
1860 return;
1861 }
1862
1863 if (ptid_equal (magic_null_ptid, inferior_ptid))
1864 {
1865 /* inferior_ptid is not set yet. This can happen with the
1866 vRun -> remote_wait,"TAAthread:" path if the stub
1867 doesn't support qC. This is the first stop reported
1868 after an attach, so this is the main thread. Update the
1869 ptid in the thread list. */
1870 thread_change_ptid (inferior_ptid, currthread);
1871 return;
1872 }
1873
1874 /* When connecting to a target remote, or to a target
1875 extended-remote which already was debugging an inferior, we
1876 may not know about it yet. Add it before adding its child
1877 thread, so notifications are emitted in a sensible order. */
1878 if (!in_inferior_list (ptid_get_pid (currthread)))
1879 {
1880 struct remote_state *rs = get_remote_state ();
1881 int fake_pid_p = !remote_multi_process_p (rs);
1882
1883 inf = remote_add_inferior (fake_pid_p,
1884 ptid_get_pid (currthread), -1, 1);
1885 }
1886
1887 /* This is really a new thread. Add it. */
1888 remote_add_thread (currthread, running);
1889
1890 /* If we found a new inferior, let the common code do whatever
1891 it needs to with it (e.g., read shared libraries, insert
1892 breakpoints), unless we're just setting up an all-stop
1893 connection. */
1894 if (inf != NULL)
1895 {
1896 struct remote_state *rs = get_remote_state ();
1897
1898 if (!rs->starting_up)
1899 notice_new_inferior (currthread, running, 0);
1900 }
1901 }
1902 }
1903
1904 /* Return the private thread data, creating it if necessary. */
1905
1906 static struct private_thread_info *
1907 demand_private_info (ptid_t ptid)
1908 {
1909 struct thread_info *info = find_thread_ptid (ptid);
1910
1911 gdb_assert (info);
1912
1913 if (!info->priv)
1914 {
1915 info->priv = XNEW (struct private_thread_info);
1916 info->private_dtor = free_private_thread_info;
1917 info->priv->core = -1;
1918 info->priv->extra = 0;
1919 }
1920
1921 return info->priv;
1922 }
1923
1924 /* Call this function as a result of
1925 1) A halt indication (T packet) containing a thread id
1926 2) A direct query of currthread
1927 3) Successful execution of set thread */
1928
1929 static void
1930 record_currthread (struct remote_state *rs, ptid_t currthread)
1931 {
1932 rs->general_thread = currthread;
1933 }
1934
1935 /* If 'QPassSignals' is supported, tell the remote stub what signals
1936 it can simply pass through to the inferior without reporting. */
1937
1938 static void
1939 remote_pass_signals (struct target_ops *self,
1940 int numsigs, unsigned char *pass_signals)
1941 {
1942 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1943 {
1944 char *pass_packet, *p;
1945 int count = 0, i;
1946 struct remote_state *rs = get_remote_state ();
1947
1948 gdb_assert (numsigs < 256);
1949 for (i = 0; i < numsigs; i++)
1950 {
1951 if (pass_signals[i])
1952 count++;
1953 }
1954 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1955 strcpy (pass_packet, "QPassSignals:");
1956 p = pass_packet + strlen (pass_packet);
1957 for (i = 0; i < numsigs; i++)
1958 {
1959 if (pass_signals[i])
1960 {
1961 if (i >= 16)
1962 *p++ = tohex (i >> 4);
1963 *p++ = tohex (i & 15);
1964 if (count)
1965 *p++ = ';';
1966 else
1967 break;
1968 count--;
1969 }
1970 }
1971 *p = 0;
1972 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1973 {
1974 putpkt (pass_packet);
1975 getpkt (&rs->buf, &rs->buf_size, 0);
1976 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1977 if (rs->last_pass_packet)
1978 xfree (rs->last_pass_packet);
1979 rs->last_pass_packet = pass_packet;
1980 }
1981 else
1982 xfree (pass_packet);
1983 }
1984 }
1985
1986 /* If 'QProgramSignals' is supported, tell the remote stub what
1987 signals it should pass through to the inferior when detaching. */
1988
1989 static void
1990 remote_program_signals (struct target_ops *self,
1991 int numsigs, unsigned char *signals)
1992 {
1993 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1994 {
1995 char *packet, *p;
1996 int count = 0, i;
1997 struct remote_state *rs = get_remote_state ();
1998
1999 gdb_assert (numsigs < 256);
2000 for (i = 0; i < numsigs; i++)
2001 {
2002 if (signals[i])
2003 count++;
2004 }
2005 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2006 strcpy (packet, "QProgramSignals:");
2007 p = packet + strlen (packet);
2008 for (i = 0; i < numsigs; i++)
2009 {
2010 if (signal_pass_state (i))
2011 {
2012 if (i >= 16)
2013 *p++ = tohex (i >> 4);
2014 *p++ = tohex (i & 15);
2015 if (count)
2016 *p++ = ';';
2017 else
2018 break;
2019 count--;
2020 }
2021 }
2022 *p = 0;
2023 if (!rs->last_program_signals_packet
2024 || strcmp (rs->last_program_signals_packet, packet) != 0)
2025 {
2026 putpkt (packet);
2027 getpkt (&rs->buf, &rs->buf_size, 0);
2028 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2029 xfree (rs->last_program_signals_packet);
2030 rs->last_program_signals_packet = packet;
2031 }
2032 else
2033 xfree (packet);
2034 }
2035 }
2036
2037 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2038 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2039 thread. If GEN is set, set the general thread, if not, then set
2040 the step/continue thread. */
2041 static void
2042 set_thread (struct ptid ptid, int gen)
2043 {
2044 struct remote_state *rs = get_remote_state ();
2045 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2046 char *buf = rs->buf;
2047 char *endbuf = rs->buf + get_remote_packet_size ();
2048
2049 if (ptid_equal (state, ptid))
2050 return;
2051
2052 *buf++ = 'H';
2053 *buf++ = gen ? 'g' : 'c';
2054 if (ptid_equal (ptid, magic_null_ptid))
2055 xsnprintf (buf, endbuf - buf, "0");
2056 else if (ptid_equal (ptid, any_thread_ptid))
2057 xsnprintf (buf, endbuf - buf, "0");
2058 else if (ptid_equal (ptid, minus_one_ptid))
2059 xsnprintf (buf, endbuf - buf, "-1");
2060 else
2061 write_ptid (buf, endbuf, ptid);
2062 putpkt (rs->buf);
2063 getpkt (&rs->buf, &rs->buf_size, 0);
2064 if (gen)
2065 rs->general_thread = ptid;
2066 else
2067 rs->continue_thread = ptid;
2068 }
2069
2070 static void
2071 set_general_thread (struct ptid ptid)
2072 {
2073 set_thread (ptid, 1);
2074 }
2075
2076 static void
2077 set_continue_thread (struct ptid ptid)
2078 {
2079 set_thread (ptid, 0);
2080 }
2081
2082 /* Change the remote current process. Which thread within the process
2083 ends up selected isn't important, as long as it is the same process
2084 as what INFERIOR_PTID points to.
2085
2086 This comes from that fact that there is no explicit notion of
2087 "selected process" in the protocol. The selected process for
2088 general operations is the process the selected general thread
2089 belongs to. */
2090
2091 static void
2092 set_general_process (void)
2093 {
2094 struct remote_state *rs = get_remote_state ();
2095
2096 /* If the remote can't handle multiple processes, don't bother. */
2097 if (!rs->extended || !remote_multi_process_p (rs))
2098 return;
2099
2100 /* We only need to change the remote current thread if it's pointing
2101 at some other process. */
2102 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2103 set_general_thread (inferior_ptid);
2104 }
2105
2106 \f
2107 /* Return nonzero if this is the main thread that we made up ourselves
2108 to model non-threaded targets as single-threaded. */
2109
2110 static int
2111 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2112 {
2113 struct remote_state *rs = get_remote_state ();
2114 char *p, *endp;
2115
2116 if (ptid_equal (ptid, magic_null_ptid))
2117 /* The main thread is always alive. */
2118 return 1;
2119
2120 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2121 /* The main thread is always alive. This can happen after a
2122 vAttach, if the remote side doesn't support
2123 multi-threading. */
2124 return 1;
2125
2126 return 0;
2127 }
2128
2129 /* Return nonzero if the thread PTID is still alive on the remote
2130 system. */
2131
2132 static int
2133 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2134 {
2135 struct remote_state *rs = get_remote_state ();
2136 char *p, *endp;
2137
2138 /* Check if this is a thread that we made up ourselves to model
2139 non-threaded targets as single-threaded. */
2140 if (remote_thread_always_alive (ops, ptid))
2141 return 1;
2142
2143 p = rs->buf;
2144 endp = rs->buf + get_remote_packet_size ();
2145
2146 *p++ = 'T';
2147 write_ptid (p, endp, ptid);
2148
2149 putpkt (rs->buf);
2150 getpkt (&rs->buf, &rs->buf_size, 0);
2151 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2152 }
2153
2154 /* Return a pointer to a thread name if we know it and NULL otherwise.
2155 The thread_info object owns the memory for the name. */
2156
2157 static const char *
2158 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2159 {
2160 if (info->priv != NULL)
2161 return info->priv->name;
2162
2163 return NULL;
2164 }
2165
2166 /* About these extended threadlist and threadinfo packets. They are
2167 variable length packets but, the fields within them are often fixed
2168 length. They are redundent enough to send over UDP as is the
2169 remote protocol in general. There is a matching unit test module
2170 in libstub. */
2171
2172 /* WARNING: This threadref data structure comes from the remote O.S.,
2173 libstub protocol encoding, and remote.c. It is not particularly
2174 changable. */
2175
2176 /* Right now, the internal structure is int. We want it to be bigger.
2177 Plan to fix this. */
2178
2179 typedef int gdb_threadref; /* Internal GDB thread reference. */
2180
2181 /* gdb_ext_thread_info is an internal GDB data structure which is
2182 equivalent to the reply of the remote threadinfo packet. */
2183
2184 struct gdb_ext_thread_info
2185 {
2186 threadref threadid; /* External form of thread reference. */
2187 int active; /* Has state interesting to GDB?
2188 regs, stack. */
2189 char display[256]; /* Brief state display, name,
2190 blocked/suspended. */
2191 char shortname[32]; /* To be used to name threads. */
2192 char more_display[256]; /* Long info, statistics, queue depth,
2193 whatever. */
2194 };
2195
2196 /* The volume of remote transfers can be limited by submitting
2197 a mask containing bits specifying the desired information.
2198 Use a union of these values as the 'selection' parameter to
2199 get_thread_info. FIXME: Make these TAG names more thread specific. */
2200
2201 #define TAG_THREADID 1
2202 #define TAG_EXISTS 2
2203 #define TAG_DISPLAY 4
2204 #define TAG_THREADNAME 8
2205 #define TAG_MOREDISPLAY 16
2206
2207 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2208
2209 static char *unpack_nibble (char *buf, int *val);
2210
2211 static char *unpack_byte (char *buf, int *value);
2212
2213 static char *pack_int (char *buf, int value);
2214
2215 static char *unpack_int (char *buf, int *value);
2216
2217 static char *unpack_string (char *src, char *dest, int length);
2218
2219 static char *pack_threadid (char *pkt, threadref *id);
2220
2221 static char *unpack_threadid (char *inbuf, threadref *id);
2222
2223 void int_to_threadref (threadref *id, int value);
2224
2225 static int threadref_to_int (threadref *ref);
2226
2227 static void copy_threadref (threadref *dest, threadref *src);
2228
2229 static int threadmatch (threadref *dest, threadref *src);
2230
2231 static char *pack_threadinfo_request (char *pkt, int mode,
2232 threadref *id);
2233
2234 static int remote_unpack_thread_info_response (char *pkt,
2235 threadref *expectedref,
2236 struct gdb_ext_thread_info
2237 *info);
2238
2239
2240 static int remote_get_threadinfo (threadref *threadid,
2241 int fieldset, /*TAG mask */
2242 struct gdb_ext_thread_info *info);
2243
2244 static char *pack_threadlist_request (char *pkt, int startflag,
2245 int threadcount,
2246 threadref *nextthread);
2247
2248 static int parse_threadlist_response (char *pkt,
2249 int result_limit,
2250 threadref *original_echo,
2251 threadref *resultlist,
2252 int *doneflag);
2253
2254 static int remote_get_threadlist (int startflag,
2255 threadref *nextthread,
2256 int result_limit,
2257 int *done,
2258 int *result_count,
2259 threadref *threadlist);
2260
2261 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2262
2263 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2264 void *context, int looplimit);
2265
2266 static int remote_newthread_step (threadref *ref, void *context);
2267
2268
2269 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2270 buffer we're allowed to write to. Returns
2271 BUF+CHARACTERS_WRITTEN. */
2272
2273 static char *
2274 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2275 {
2276 int pid, tid;
2277 struct remote_state *rs = get_remote_state ();
2278
2279 if (remote_multi_process_p (rs))
2280 {
2281 pid = ptid_get_pid (ptid);
2282 if (pid < 0)
2283 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2284 else
2285 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2286 }
2287 tid = ptid_get_lwp (ptid);
2288 if (tid < 0)
2289 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2290 else
2291 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2292
2293 return buf;
2294 }
2295
2296 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2297 passed the last parsed char. Returns null_ptid on error. */
2298
2299 static ptid_t
2300 read_ptid (char *buf, char **obuf)
2301 {
2302 char *p = buf;
2303 char *pp;
2304 ULONGEST pid = 0, tid = 0;
2305
2306 if (*p == 'p')
2307 {
2308 /* Multi-process ptid. */
2309 pp = unpack_varlen_hex (p + 1, &pid);
2310 if (*pp != '.')
2311 error (_("invalid remote ptid: %s"), p);
2312
2313 p = pp;
2314 pp = unpack_varlen_hex (p + 1, &tid);
2315 if (obuf)
2316 *obuf = pp;
2317 return ptid_build (pid, tid, 0);
2318 }
2319
2320 /* No multi-process. Just a tid. */
2321 pp = unpack_varlen_hex (p, &tid);
2322
2323 /* Return null_ptid when no thread id is found. */
2324 if (p == pp)
2325 {
2326 if (obuf)
2327 *obuf = pp;
2328 return null_ptid;
2329 }
2330
2331 /* Since the stub is not sending a process id, then default to
2332 what's in inferior_ptid, unless it's null at this point. If so,
2333 then since there's no way to know the pid of the reported
2334 threads, use the magic number. */
2335 if (ptid_equal (inferior_ptid, null_ptid))
2336 pid = ptid_get_pid (magic_null_ptid);
2337 else
2338 pid = ptid_get_pid (inferior_ptid);
2339
2340 if (obuf)
2341 *obuf = pp;
2342 return ptid_build (pid, tid, 0);
2343 }
2344
2345 static int
2346 stubhex (int ch)
2347 {
2348 if (ch >= 'a' && ch <= 'f')
2349 return ch - 'a' + 10;
2350 if (ch >= '0' && ch <= '9')
2351 return ch - '0';
2352 if (ch >= 'A' && ch <= 'F')
2353 return ch - 'A' + 10;
2354 return -1;
2355 }
2356
2357 static int
2358 stub_unpack_int (char *buff, int fieldlength)
2359 {
2360 int nibble;
2361 int retval = 0;
2362
2363 while (fieldlength)
2364 {
2365 nibble = stubhex (*buff++);
2366 retval |= nibble;
2367 fieldlength--;
2368 if (fieldlength)
2369 retval = retval << 4;
2370 }
2371 return retval;
2372 }
2373
2374 static char *
2375 unpack_nibble (char *buf, int *val)
2376 {
2377 *val = fromhex (*buf++);
2378 return buf;
2379 }
2380
2381 static char *
2382 unpack_byte (char *buf, int *value)
2383 {
2384 *value = stub_unpack_int (buf, 2);
2385 return buf + 2;
2386 }
2387
2388 static char *
2389 pack_int (char *buf, int value)
2390 {
2391 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2392 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2393 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2394 buf = pack_hex_byte (buf, (value & 0xff));
2395 return buf;
2396 }
2397
2398 static char *
2399 unpack_int (char *buf, int *value)
2400 {
2401 *value = stub_unpack_int (buf, 8);
2402 return buf + 8;
2403 }
2404
2405 #if 0 /* Currently unused, uncomment when needed. */
2406 static char *pack_string (char *pkt, char *string);
2407
2408 static char *
2409 pack_string (char *pkt, char *string)
2410 {
2411 char ch;
2412 int len;
2413
2414 len = strlen (string);
2415 if (len > 200)
2416 len = 200; /* Bigger than most GDB packets, junk??? */
2417 pkt = pack_hex_byte (pkt, len);
2418 while (len-- > 0)
2419 {
2420 ch = *string++;
2421 if ((ch == '\0') || (ch == '#'))
2422 ch = '*'; /* Protect encapsulation. */
2423 *pkt++ = ch;
2424 }
2425 return pkt;
2426 }
2427 #endif /* 0 (unused) */
2428
2429 static char *
2430 unpack_string (char *src, char *dest, int length)
2431 {
2432 while (length--)
2433 *dest++ = *src++;
2434 *dest = '\0';
2435 return src;
2436 }
2437
2438 static char *
2439 pack_threadid (char *pkt, threadref *id)
2440 {
2441 char *limit;
2442 unsigned char *altid;
2443
2444 altid = (unsigned char *) id;
2445 limit = pkt + BUF_THREAD_ID_SIZE;
2446 while (pkt < limit)
2447 pkt = pack_hex_byte (pkt, *altid++);
2448 return pkt;
2449 }
2450
2451
2452 static char *
2453 unpack_threadid (char *inbuf, threadref *id)
2454 {
2455 char *altref;
2456 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2457 int x, y;
2458
2459 altref = (char *) id;
2460
2461 while (inbuf < limit)
2462 {
2463 x = stubhex (*inbuf++);
2464 y = stubhex (*inbuf++);
2465 *altref++ = (x << 4) | y;
2466 }
2467 return inbuf;
2468 }
2469
2470 /* Externally, threadrefs are 64 bits but internally, they are still
2471 ints. This is due to a mismatch of specifications. We would like
2472 to use 64bit thread references internally. This is an adapter
2473 function. */
2474
2475 void
2476 int_to_threadref (threadref *id, int value)
2477 {
2478 unsigned char *scan;
2479
2480 scan = (unsigned char *) id;
2481 {
2482 int i = 4;
2483 while (i--)
2484 *scan++ = 0;
2485 }
2486 *scan++ = (value >> 24) & 0xff;
2487 *scan++ = (value >> 16) & 0xff;
2488 *scan++ = (value >> 8) & 0xff;
2489 *scan++ = (value & 0xff);
2490 }
2491
2492 static int
2493 threadref_to_int (threadref *ref)
2494 {
2495 int i, value = 0;
2496 unsigned char *scan;
2497
2498 scan = *ref;
2499 scan += 4;
2500 i = 4;
2501 while (i-- > 0)
2502 value = (value << 8) | ((*scan++) & 0xff);
2503 return value;
2504 }
2505
2506 static void
2507 copy_threadref (threadref *dest, threadref *src)
2508 {
2509 int i;
2510 unsigned char *csrc, *cdest;
2511
2512 csrc = (unsigned char *) src;
2513 cdest = (unsigned char *) dest;
2514 i = 8;
2515 while (i--)
2516 *cdest++ = *csrc++;
2517 }
2518
2519 static int
2520 threadmatch (threadref *dest, threadref *src)
2521 {
2522 /* Things are broken right now, so just assume we got a match. */
2523 #if 0
2524 unsigned char *srcp, *destp;
2525 int i, result;
2526 srcp = (char *) src;
2527 destp = (char *) dest;
2528
2529 result = 1;
2530 while (i-- > 0)
2531 result &= (*srcp++ == *destp++) ? 1 : 0;
2532 return result;
2533 #endif
2534 return 1;
2535 }
2536
2537 /*
2538 threadid:1, # always request threadid
2539 context_exists:2,
2540 display:4,
2541 unique_name:8,
2542 more_display:16
2543 */
2544
2545 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2546
2547 static char *
2548 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2549 {
2550 *pkt++ = 'q'; /* Info Query */
2551 *pkt++ = 'P'; /* process or thread info */
2552 pkt = pack_int (pkt, mode); /* mode */
2553 pkt = pack_threadid (pkt, id); /* threadid */
2554 *pkt = '\0'; /* terminate */
2555 return pkt;
2556 }
2557
2558 /* These values tag the fields in a thread info response packet. */
2559 /* Tagging the fields allows us to request specific fields and to
2560 add more fields as time goes by. */
2561
2562 #define TAG_THREADID 1 /* Echo the thread identifier. */
2563 #define TAG_EXISTS 2 /* Is this process defined enough to
2564 fetch registers and its stack? */
2565 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2566 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2567 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2568 the process. */
2569
2570 static int
2571 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2572 struct gdb_ext_thread_info *info)
2573 {
2574 struct remote_state *rs = get_remote_state ();
2575 int mask, length;
2576 int tag;
2577 threadref ref;
2578 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2579 int retval = 1;
2580
2581 /* info->threadid = 0; FIXME: implement zero_threadref. */
2582 info->active = 0;
2583 info->display[0] = '\0';
2584 info->shortname[0] = '\0';
2585 info->more_display[0] = '\0';
2586
2587 /* Assume the characters indicating the packet type have been
2588 stripped. */
2589 pkt = unpack_int (pkt, &mask); /* arg mask */
2590 pkt = unpack_threadid (pkt, &ref);
2591
2592 if (mask == 0)
2593 warning (_("Incomplete response to threadinfo request."));
2594 if (!threadmatch (&ref, expectedref))
2595 { /* This is an answer to a different request. */
2596 warning (_("ERROR RMT Thread info mismatch."));
2597 return 0;
2598 }
2599 copy_threadref (&info->threadid, &ref);
2600
2601 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2602
2603 /* Packets are terminated with nulls. */
2604 while ((pkt < limit) && mask && *pkt)
2605 {
2606 pkt = unpack_int (pkt, &tag); /* tag */
2607 pkt = unpack_byte (pkt, &length); /* length */
2608 if (!(tag & mask)) /* Tags out of synch with mask. */
2609 {
2610 warning (_("ERROR RMT: threadinfo tag mismatch."));
2611 retval = 0;
2612 break;
2613 }
2614 if (tag == TAG_THREADID)
2615 {
2616 if (length != 16)
2617 {
2618 warning (_("ERROR RMT: length of threadid is not 16."));
2619 retval = 0;
2620 break;
2621 }
2622 pkt = unpack_threadid (pkt, &ref);
2623 mask = mask & ~TAG_THREADID;
2624 continue;
2625 }
2626 if (tag == TAG_EXISTS)
2627 {
2628 info->active = stub_unpack_int (pkt, length);
2629 pkt += length;
2630 mask = mask & ~(TAG_EXISTS);
2631 if (length > 8)
2632 {
2633 warning (_("ERROR RMT: 'exists' length too long."));
2634 retval = 0;
2635 break;
2636 }
2637 continue;
2638 }
2639 if (tag == TAG_THREADNAME)
2640 {
2641 pkt = unpack_string (pkt, &info->shortname[0], length);
2642 mask = mask & ~TAG_THREADNAME;
2643 continue;
2644 }
2645 if (tag == TAG_DISPLAY)
2646 {
2647 pkt = unpack_string (pkt, &info->display[0], length);
2648 mask = mask & ~TAG_DISPLAY;
2649 continue;
2650 }
2651 if (tag == TAG_MOREDISPLAY)
2652 {
2653 pkt = unpack_string (pkt, &info->more_display[0], length);
2654 mask = mask & ~TAG_MOREDISPLAY;
2655 continue;
2656 }
2657 warning (_("ERROR RMT: unknown thread info tag."));
2658 break; /* Not a tag we know about. */
2659 }
2660 return retval;
2661 }
2662
2663 static int
2664 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2665 struct gdb_ext_thread_info *info)
2666 {
2667 struct remote_state *rs = get_remote_state ();
2668 int result;
2669
2670 pack_threadinfo_request (rs->buf, fieldset, threadid);
2671 putpkt (rs->buf);
2672 getpkt (&rs->buf, &rs->buf_size, 0);
2673
2674 if (rs->buf[0] == '\0')
2675 return 0;
2676
2677 result = remote_unpack_thread_info_response (rs->buf + 2,
2678 threadid, info);
2679 return result;
2680 }
2681
2682 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2683
2684 static char *
2685 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2686 threadref *nextthread)
2687 {
2688 *pkt++ = 'q'; /* info query packet */
2689 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2690 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2691 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2692 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2693 *pkt = '\0';
2694 return pkt;
2695 }
2696
2697 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2698
2699 static int
2700 parse_threadlist_response (char *pkt, int result_limit,
2701 threadref *original_echo, threadref *resultlist,
2702 int *doneflag)
2703 {
2704 struct remote_state *rs = get_remote_state ();
2705 char *limit;
2706 int count, resultcount, done;
2707
2708 resultcount = 0;
2709 /* Assume the 'q' and 'M chars have been stripped. */
2710 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2711 /* done parse past here */
2712 pkt = unpack_byte (pkt, &count); /* count field */
2713 pkt = unpack_nibble (pkt, &done);
2714 /* The first threadid is the argument threadid. */
2715 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2716 while ((count-- > 0) && (pkt < limit))
2717 {
2718 pkt = unpack_threadid (pkt, resultlist++);
2719 if (resultcount++ >= result_limit)
2720 break;
2721 }
2722 if (doneflag)
2723 *doneflag = done;
2724 return resultcount;
2725 }
2726
2727 /* Fetch the next batch of threads from the remote. Returns -1 if the
2728 qL packet is not supported, 0 on error and 1 on success. */
2729
2730 static int
2731 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2732 int *done, int *result_count, threadref *threadlist)
2733 {
2734 struct remote_state *rs = get_remote_state ();
2735 int result = 1;
2736
2737 /* Trancate result limit to be smaller than the packet size. */
2738 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2739 >= get_remote_packet_size ())
2740 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2741
2742 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2743 putpkt (rs->buf);
2744 getpkt (&rs->buf, &rs->buf_size, 0);
2745 if (*rs->buf == '\0')
2746 {
2747 /* Packet not supported. */
2748 return -1;
2749 }
2750
2751 *result_count =
2752 parse_threadlist_response (rs->buf + 2, result_limit,
2753 &rs->echo_nextthread, threadlist, done);
2754
2755 if (!threadmatch (&rs->echo_nextthread, nextthread))
2756 {
2757 /* FIXME: This is a good reason to drop the packet. */
2758 /* Possably, there is a duplicate response. */
2759 /* Possabilities :
2760 retransmit immediatly - race conditions
2761 retransmit after timeout - yes
2762 exit
2763 wait for packet, then exit
2764 */
2765 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2766 return 0; /* I choose simply exiting. */
2767 }
2768 if (*result_count <= 0)
2769 {
2770 if (*done != 1)
2771 {
2772 warning (_("RMT ERROR : failed to get remote thread list."));
2773 result = 0;
2774 }
2775 return result; /* break; */
2776 }
2777 if (*result_count > result_limit)
2778 {
2779 *result_count = 0;
2780 warning (_("RMT ERROR: threadlist response longer than requested."));
2781 return 0;
2782 }
2783 return result;
2784 }
2785
2786 /* Fetch the list of remote threads, with the qL packet, and call
2787 STEPFUNCTION for each thread found. Stops iterating and returns 1
2788 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2789 STEPFUNCTION returns false. If the packet is not supported,
2790 returns -1. */
2791
2792 static int
2793 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2794 int looplimit)
2795 {
2796 struct remote_state *rs = get_remote_state ();
2797 int done, i, result_count;
2798 int startflag = 1;
2799 int result = 1;
2800 int loopcount = 0;
2801
2802 done = 0;
2803 while (!done)
2804 {
2805 if (loopcount++ > looplimit)
2806 {
2807 result = 0;
2808 warning (_("Remote fetch threadlist -infinite loop-."));
2809 break;
2810 }
2811 result = remote_get_threadlist (startflag, &rs->nextthread,
2812 MAXTHREADLISTRESULTS,
2813 &done, &result_count,
2814 rs->resultthreadlist);
2815 if (result <= 0)
2816 break;
2817 /* Clear for later iterations. */
2818 startflag = 0;
2819 /* Setup to resume next batch of thread references, set nextthread. */
2820 if (result_count >= 1)
2821 copy_threadref (&rs->nextthread,
2822 &rs->resultthreadlist[result_count - 1]);
2823 i = 0;
2824 while (result_count--)
2825 {
2826 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2827 {
2828 result = 0;
2829 break;
2830 }
2831 }
2832 }
2833 return result;
2834 }
2835
2836 /* A thread found on the remote target. */
2837
2838 typedef struct thread_item
2839 {
2840 /* The thread's PTID. */
2841 ptid_t ptid;
2842
2843 /* The thread's extra info. May be NULL. */
2844 char *extra;
2845
2846 /* The thread's name. May be NULL. */
2847 char *name;
2848
2849 /* The core the thread was running on. -1 if not known. */
2850 int core;
2851 } thread_item_t;
2852 DEF_VEC_O(thread_item_t);
2853
2854 /* Context passed around to the various methods listing remote
2855 threads. As new threads are found, they're added to the ITEMS
2856 vector. */
2857
2858 struct threads_listing_context
2859 {
2860 /* The threads found on the remote target. */
2861 VEC (thread_item_t) *items;
2862 };
2863
2864 /* Discard the contents of the constructed thread listing context. */
2865
2866 static void
2867 clear_threads_listing_context (void *p)
2868 {
2869 struct threads_listing_context *context
2870 = (struct threads_listing_context *) p;
2871 int i;
2872 struct thread_item *item;
2873
2874 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2875 {
2876 xfree (item->extra);
2877 xfree (item->name);
2878 }
2879
2880 VEC_free (thread_item_t, context->items);
2881 }
2882
2883 /* Remove the thread specified as the related_pid field of WS
2884 from the CONTEXT list. */
2885
2886 static void
2887 threads_listing_context_remove (struct target_waitstatus *ws,
2888 struct threads_listing_context *context)
2889 {
2890 struct thread_item *item;
2891 int i;
2892 ptid_t child_ptid = ws->value.related_pid;
2893
2894 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2895 {
2896 if (ptid_equal (item->ptid, child_ptid))
2897 {
2898 VEC_ordered_remove (thread_item_t, context->items, i);
2899 break;
2900 }
2901 }
2902 }
2903
2904 static int
2905 remote_newthread_step (threadref *ref, void *data)
2906 {
2907 struct threads_listing_context *context
2908 = (struct threads_listing_context *) data;
2909 struct thread_item item;
2910 int pid = ptid_get_pid (inferior_ptid);
2911
2912 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2913 item.core = -1;
2914 item.extra = NULL;
2915
2916 VEC_safe_push (thread_item_t, context->items, &item);
2917
2918 return 1; /* continue iterator */
2919 }
2920
2921 #define CRAZY_MAX_THREADS 1000
2922
2923 static ptid_t
2924 remote_current_thread (ptid_t oldpid)
2925 {
2926 struct remote_state *rs = get_remote_state ();
2927
2928 putpkt ("qC");
2929 getpkt (&rs->buf, &rs->buf_size, 0);
2930 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2931 {
2932 char *obuf;
2933 ptid_t result;
2934
2935 result = read_ptid (&rs->buf[2], &obuf);
2936 if (*obuf != '\0' && remote_debug)
2937 fprintf_unfiltered (gdb_stdlog,
2938 "warning: garbage in qC reply\n");
2939
2940 return result;
2941 }
2942 else
2943 return oldpid;
2944 }
2945
2946 /* List remote threads using the deprecated qL packet. */
2947
2948 static int
2949 remote_get_threads_with_ql (struct target_ops *ops,
2950 struct threads_listing_context *context)
2951 {
2952 if (remote_threadlist_iterator (remote_newthread_step, context,
2953 CRAZY_MAX_THREADS) >= 0)
2954 return 1;
2955
2956 return 0;
2957 }
2958
2959 #if defined(HAVE_LIBEXPAT)
2960
2961 static void
2962 start_thread (struct gdb_xml_parser *parser,
2963 const struct gdb_xml_element *element,
2964 void *user_data, VEC(gdb_xml_value_s) *attributes)
2965 {
2966 struct threads_listing_context *data
2967 = (struct threads_listing_context *) user_data;
2968
2969 struct thread_item item;
2970 char *id;
2971 struct gdb_xml_value *attr;
2972
2973 id = (char *) xml_find_attribute (attributes, "id")->value;
2974 item.ptid = read_ptid (id, NULL);
2975
2976 attr = xml_find_attribute (attributes, "core");
2977 if (attr != NULL)
2978 item.core = *(ULONGEST *) attr->value;
2979 else
2980 item.core = -1;
2981
2982 attr = xml_find_attribute (attributes, "name");
2983 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
2984
2985 item.extra = 0;
2986
2987 VEC_safe_push (thread_item_t, data->items, &item);
2988 }
2989
2990 static void
2991 end_thread (struct gdb_xml_parser *parser,
2992 const struct gdb_xml_element *element,
2993 void *user_data, const char *body_text)
2994 {
2995 struct threads_listing_context *data
2996 = (struct threads_listing_context *) user_data;
2997
2998 if (body_text && *body_text)
2999 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3000 }
3001
3002 const struct gdb_xml_attribute thread_attributes[] = {
3003 { "id", GDB_XML_AF_NONE, NULL, NULL },
3004 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3005 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3006 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3007 };
3008
3009 const struct gdb_xml_element thread_children[] = {
3010 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3011 };
3012
3013 const struct gdb_xml_element threads_children[] = {
3014 { "thread", thread_attributes, thread_children,
3015 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3016 start_thread, end_thread },
3017 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3018 };
3019
3020 const struct gdb_xml_element threads_elements[] = {
3021 { "threads", NULL, threads_children,
3022 GDB_XML_EF_NONE, NULL, NULL },
3023 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3024 };
3025
3026 #endif
3027
3028 /* List remote threads using qXfer:threads:read. */
3029
3030 static int
3031 remote_get_threads_with_qxfer (struct target_ops *ops,
3032 struct threads_listing_context *context)
3033 {
3034 #if defined(HAVE_LIBEXPAT)
3035 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3036 {
3037 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3038 struct cleanup *back_to = make_cleanup (xfree, xml);
3039
3040 if (xml != NULL && *xml != '\0')
3041 {
3042 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3043 threads_elements, xml, context);
3044 }
3045
3046 do_cleanups (back_to);
3047 return 1;
3048 }
3049 #endif
3050
3051 return 0;
3052 }
3053
3054 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3055
3056 static int
3057 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3058 struct threads_listing_context *context)
3059 {
3060 struct remote_state *rs = get_remote_state ();
3061
3062 if (rs->use_threadinfo_query)
3063 {
3064 char *bufp;
3065
3066 putpkt ("qfThreadInfo");
3067 getpkt (&rs->buf, &rs->buf_size, 0);
3068 bufp = rs->buf;
3069 if (bufp[0] != '\0') /* q packet recognized */
3070 {
3071 while (*bufp++ == 'm') /* reply contains one or more TID */
3072 {
3073 do
3074 {
3075 struct thread_item item;
3076
3077 item.ptid = read_ptid (bufp, &bufp);
3078 item.core = -1;
3079 item.extra = NULL;
3080
3081 VEC_safe_push (thread_item_t, context->items, &item);
3082 }
3083 while (*bufp++ == ','); /* comma-separated list */
3084 putpkt ("qsThreadInfo");
3085 getpkt (&rs->buf, &rs->buf_size, 0);
3086 bufp = rs->buf;
3087 }
3088 return 1;
3089 }
3090 else
3091 {
3092 /* Packet not recognized. */
3093 rs->use_threadinfo_query = 0;
3094 }
3095 }
3096
3097 return 0;
3098 }
3099
3100 /* Implement the to_update_thread_list function for the remote
3101 targets. */
3102
3103 static void
3104 remote_update_thread_list (struct target_ops *ops)
3105 {
3106 struct remote_state *rs = get_remote_state ();
3107 struct threads_listing_context context;
3108 struct cleanup *old_chain;
3109 int got_list = 0;
3110
3111 context.items = NULL;
3112 old_chain = make_cleanup (clear_threads_listing_context, &context);
3113
3114 /* We have a few different mechanisms to fetch the thread list. Try
3115 them all, starting with the most preferred one first, falling
3116 back to older methods. */
3117 if (remote_get_threads_with_qxfer (ops, &context)
3118 || remote_get_threads_with_qthreadinfo (ops, &context)
3119 || remote_get_threads_with_ql (ops, &context))
3120 {
3121 int i;
3122 struct thread_item *item;
3123 struct thread_info *tp, *tmp;
3124
3125 got_list = 1;
3126
3127 if (VEC_empty (thread_item_t, context.items)
3128 && remote_thread_always_alive (ops, inferior_ptid))
3129 {
3130 /* Some targets don't really support threads, but still
3131 reply an (empty) thread list in response to the thread
3132 listing packets, instead of replying "packet not
3133 supported". Exit early so we don't delete the main
3134 thread. */
3135 do_cleanups (old_chain);
3136 return;
3137 }
3138
3139 /* CONTEXT now holds the current thread list on the remote
3140 target end. Delete GDB-side threads no longer found on the
3141 target. */
3142 ALL_THREADS_SAFE (tp, tmp)
3143 {
3144 for (i = 0;
3145 VEC_iterate (thread_item_t, context.items, i, item);
3146 ++i)
3147 {
3148 if (ptid_equal (item->ptid, tp->ptid))
3149 break;
3150 }
3151
3152 if (i == VEC_length (thread_item_t, context.items))
3153 {
3154 /* Not found. */
3155 delete_thread (tp->ptid);
3156 }
3157 }
3158
3159 /* Remove any unreported fork child threads from CONTEXT so
3160 that we don't interfere with follow fork, which is where
3161 creation of such threads is handled. */
3162 remove_new_fork_children (&context);
3163
3164 /* And now add threads we don't know about yet to our list. */
3165 for (i = 0;
3166 VEC_iterate (thread_item_t, context.items, i, item);
3167 ++i)
3168 {
3169 if (!ptid_equal (item->ptid, null_ptid))
3170 {
3171 struct private_thread_info *info;
3172 /* In non-stop mode, we assume new found threads are
3173 running until proven otherwise with a stop reply. In
3174 all-stop, we can only get here if all threads are
3175 stopped. */
3176 int running = target_is_non_stop_p () ? 1 : 0;
3177
3178 remote_notice_new_inferior (item->ptid, running);
3179
3180 info = demand_private_info (item->ptid);
3181 info->core = item->core;
3182 info->extra = item->extra;
3183 item->extra = NULL;
3184 info->name = item->name;
3185 item->name = NULL;
3186 }
3187 }
3188 }
3189
3190 if (!got_list)
3191 {
3192 /* If no thread listing method is supported, then query whether
3193 each known thread is alive, one by one, with the T packet.
3194 If the target doesn't support threads at all, then this is a
3195 no-op. See remote_thread_alive. */
3196 prune_threads ();
3197 }
3198
3199 do_cleanups (old_chain);
3200 }
3201
3202 /*
3203 * Collect a descriptive string about the given thread.
3204 * The target may say anything it wants to about the thread
3205 * (typically info about its blocked / runnable state, name, etc.).
3206 * This string will appear in the info threads display.
3207 *
3208 * Optional: targets are not required to implement this function.
3209 */
3210
3211 static char *
3212 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3213 {
3214 struct remote_state *rs = get_remote_state ();
3215 int result;
3216 int set;
3217 threadref id;
3218 struct gdb_ext_thread_info threadinfo;
3219 static char display_buf[100]; /* arbitrary... */
3220 int n = 0; /* position in display_buf */
3221
3222 if (rs->remote_desc == 0) /* paranoia */
3223 internal_error (__FILE__, __LINE__,
3224 _("remote_threads_extra_info"));
3225
3226 if (ptid_equal (tp->ptid, magic_null_ptid)
3227 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3228 /* This is the main thread which was added by GDB. The remote
3229 server doesn't know about it. */
3230 return NULL;
3231
3232 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3233 {
3234 struct thread_info *info = find_thread_ptid (tp->ptid);
3235
3236 if (info && info->priv)
3237 return info->priv->extra;
3238 else
3239 return NULL;
3240 }
3241
3242 if (rs->use_threadextra_query)
3243 {
3244 char *b = rs->buf;
3245 char *endb = rs->buf + get_remote_packet_size ();
3246
3247 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3248 b += strlen (b);
3249 write_ptid (b, endb, tp->ptid);
3250
3251 putpkt (rs->buf);
3252 getpkt (&rs->buf, &rs->buf_size, 0);
3253 if (rs->buf[0] != 0)
3254 {
3255 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3256 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3257 display_buf [result] = '\0';
3258 return display_buf;
3259 }
3260 }
3261
3262 /* If the above query fails, fall back to the old method. */
3263 rs->use_threadextra_query = 0;
3264 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3265 | TAG_MOREDISPLAY | TAG_DISPLAY;
3266 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3267 if (remote_get_threadinfo (&id, set, &threadinfo))
3268 if (threadinfo.active)
3269 {
3270 if (*threadinfo.shortname)
3271 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3272 " Name: %s,", threadinfo.shortname);
3273 if (*threadinfo.display)
3274 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3275 " State: %s,", threadinfo.display);
3276 if (*threadinfo.more_display)
3277 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3278 " Priority: %s", threadinfo.more_display);
3279
3280 if (n > 0)
3281 {
3282 /* For purely cosmetic reasons, clear up trailing commas. */
3283 if (',' == display_buf[n-1])
3284 display_buf[n-1] = ' ';
3285 return display_buf;
3286 }
3287 }
3288 return NULL;
3289 }
3290 \f
3291
3292 static int
3293 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3294 struct static_tracepoint_marker *marker)
3295 {
3296 struct remote_state *rs = get_remote_state ();
3297 char *p = rs->buf;
3298
3299 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3300 p += strlen (p);
3301 p += hexnumstr (p, addr);
3302 putpkt (rs->buf);
3303 getpkt (&rs->buf, &rs->buf_size, 0);
3304 p = rs->buf;
3305
3306 if (*p == 'E')
3307 error (_("Remote failure reply: %s"), p);
3308
3309 if (*p++ == 'm')
3310 {
3311 parse_static_tracepoint_marker_definition (p, &p, marker);
3312 return 1;
3313 }
3314
3315 return 0;
3316 }
3317
3318 static VEC(static_tracepoint_marker_p) *
3319 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3320 const char *strid)
3321 {
3322 struct remote_state *rs = get_remote_state ();
3323 VEC(static_tracepoint_marker_p) *markers = NULL;
3324 struct static_tracepoint_marker *marker = NULL;
3325 struct cleanup *old_chain;
3326 char *p;
3327
3328 /* Ask for a first packet of static tracepoint marker
3329 definition. */
3330 putpkt ("qTfSTM");
3331 getpkt (&rs->buf, &rs->buf_size, 0);
3332 p = rs->buf;
3333 if (*p == 'E')
3334 error (_("Remote failure reply: %s"), p);
3335
3336 old_chain = make_cleanup (free_current_marker, &marker);
3337
3338 while (*p++ == 'm')
3339 {
3340 if (marker == NULL)
3341 marker = XCNEW (struct static_tracepoint_marker);
3342
3343 do
3344 {
3345 parse_static_tracepoint_marker_definition (p, &p, marker);
3346
3347 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3348 {
3349 VEC_safe_push (static_tracepoint_marker_p,
3350 markers, marker);
3351 marker = NULL;
3352 }
3353 else
3354 {
3355 release_static_tracepoint_marker (marker);
3356 memset (marker, 0, sizeof (*marker));
3357 }
3358 }
3359 while (*p++ == ','); /* comma-separated list */
3360 /* Ask for another packet of static tracepoint definition. */
3361 putpkt ("qTsSTM");
3362 getpkt (&rs->buf, &rs->buf_size, 0);
3363 p = rs->buf;
3364 }
3365
3366 do_cleanups (old_chain);
3367 return markers;
3368 }
3369
3370 \f
3371 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3372
3373 static ptid_t
3374 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3375 {
3376 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3377 }
3378 \f
3379
3380 /* Restart the remote side; this is an extended protocol operation. */
3381
3382 static void
3383 extended_remote_restart (void)
3384 {
3385 struct remote_state *rs = get_remote_state ();
3386
3387 /* Send the restart command; for reasons I don't understand the
3388 remote side really expects a number after the "R". */
3389 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3390 putpkt (rs->buf);
3391
3392 remote_fileio_reset ();
3393 }
3394 \f
3395 /* Clean up connection to a remote debugger. */
3396
3397 static void
3398 remote_close (struct target_ops *self)
3399 {
3400 struct remote_state *rs = get_remote_state ();
3401
3402 if (rs->remote_desc == NULL)
3403 return; /* already closed */
3404
3405 /* Make sure we leave stdin registered in the event loop, and we
3406 don't leave the async SIGINT signal handler installed. */
3407 remote_terminal_ours (self);
3408
3409 serial_close (rs->remote_desc);
3410 rs->remote_desc = NULL;
3411
3412 /* We don't have a connection to the remote stub anymore. Get rid
3413 of all the inferiors and their threads we were controlling.
3414 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3415 will be unable to find the thread corresponding to (pid, 0, 0). */
3416 inferior_ptid = null_ptid;
3417 discard_all_inferiors ();
3418
3419 /* We are closing the remote target, so we should discard
3420 everything of this target. */
3421 discard_pending_stop_replies_in_queue (rs);
3422
3423 if (remote_async_inferior_event_token)
3424 delete_async_event_handler (&remote_async_inferior_event_token);
3425
3426 remote_notif_state_xfree (rs->notif_state);
3427
3428 trace_reset_local_state ();
3429 }
3430
3431 /* Query the remote side for the text, data and bss offsets. */
3432
3433 static void
3434 get_offsets (void)
3435 {
3436 struct remote_state *rs = get_remote_state ();
3437 char *buf;
3438 char *ptr;
3439 int lose, num_segments = 0, do_sections, do_segments;
3440 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3441 struct section_offsets *offs;
3442 struct symfile_segment_data *data;
3443
3444 if (symfile_objfile == NULL)
3445 return;
3446
3447 putpkt ("qOffsets");
3448 getpkt (&rs->buf, &rs->buf_size, 0);
3449 buf = rs->buf;
3450
3451 if (buf[0] == '\000')
3452 return; /* Return silently. Stub doesn't support
3453 this command. */
3454 if (buf[0] == 'E')
3455 {
3456 warning (_("Remote failure reply: %s"), buf);
3457 return;
3458 }
3459
3460 /* Pick up each field in turn. This used to be done with scanf, but
3461 scanf will make trouble if CORE_ADDR size doesn't match
3462 conversion directives correctly. The following code will work
3463 with any size of CORE_ADDR. */
3464 text_addr = data_addr = bss_addr = 0;
3465 ptr = buf;
3466 lose = 0;
3467
3468 if (startswith (ptr, "Text="))
3469 {
3470 ptr += 5;
3471 /* Don't use strtol, could lose on big values. */
3472 while (*ptr && *ptr != ';')
3473 text_addr = (text_addr << 4) + fromhex (*ptr++);
3474
3475 if (startswith (ptr, ";Data="))
3476 {
3477 ptr += 6;
3478 while (*ptr && *ptr != ';')
3479 data_addr = (data_addr << 4) + fromhex (*ptr++);
3480 }
3481 else
3482 lose = 1;
3483
3484 if (!lose && startswith (ptr, ";Bss="))
3485 {
3486 ptr += 5;
3487 while (*ptr && *ptr != ';')
3488 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3489
3490 if (bss_addr != data_addr)
3491 warning (_("Target reported unsupported offsets: %s"), buf);
3492 }
3493 else
3494 lose = 1;
3495 }
3496 else if (startswith (ptr, "TextSeg="))
3497 {
3498 ptr += 8;
3499 /* Don't use strtol, could lose on big values. */
3500 while (*ptr && *ptr != ';')
3501 text_addr = (text_addr << 4) + fromhex (*ptr++);
3502 num_segments = 1;
3503
3504 if (startswith (ptr, ";DataSeg="))
3505 {
3506 ptr += 9;
3507 while (*ptr && *ptr != ';')
3508 data_addr = (data_addr << 4) + fromhex (*ptr++);
3509 num_segments++;
3510 }
3511 }
3512 else
3513 lose = 1;
3514
3515 if (lose)
3516 error (_("Malformed response to offset query, %s"), buf);
3517 else if (*ptr != '\0')
3518 warning (_("Target reported unsupported offsets: %s"), buf);
3519
3520 offs = ((struct section_offsets *)
3521 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3522 memcpy (offs, symfile_objfile->section_offsets,
3523 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3524
3525 data = get_symfile_segment_data (symfile_objfile->obfd);
3526 do_segments = (data != NULL);
3527 do_sections = num_segments == 0;
3528
3529 if (num_segments > 0)
3530 {
3531 segments[0] = text_addr;
3532 segments[1] = data_addr;
3533 }
3534 /* If we have two segments, we can still try to relocate everything
3535 by assuming that the .text and .data offsets apply to the whole
3536 text and data segments. Convert the offsets given in the packet
3537 to base addresses for symfile_map_offsets_to_segments. */
3538 else if (data && data->num_segments == 2)
3539 {
3540 segments[0] = data->segment_bases[0] + text_addr;
3541 segments[1] = data->segment_bases[1] + data_addr;
3542 num_segments = 2;
3543 }
3544 /* If the object file has only one segment, assume that it is text
3545 rather than data; main programs with no writable data are rare,
3546 but programs with no code are useless. Of course the code might
3547 have ended up in the data segment... to detect that we would need
3548 the permissions here. */
3549 else if (data && data->num_segments == 1)
3550 {
3551 segments[0] = data->segment_bases[0] + text_addr;
3552 num_segments = 1;
3553 }
3554 /* There's no way to relocate by segment. */
3555 else
3556 do_segments = 0;
3557
3558 if (do_segments)
3559 {
3560 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3561 offs, num_segments, segments);
3562
3563 if (ret == 0 && !do_sections)
3564 error (_("Can not handle qOffsets TextSeg "
3565 "response with this symbol file"));
3566
3567 if (ret > 0)
3568 do_sections = 0;
3569 }
3570
3571 if (data)
3572 free_symfile_segment_data (data);
3573
3574 if (do_sections)
3575 {
3576 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3577
3578 /* This is a temporary kludge to force data and bss to use the
3579 same offsets because that's what nlmconv does now. The real
3580 solution requires changes to the stub and remote.c that I
3581 don't have time to do right now. */
3582
3583 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3584 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3585 }
3586
3587 objfile_relocate (symfile_objfile, offs);
3588 }
3589
3590 /* Send interrupt_sequence to remote target. */
3591 static void
3592 send_interrupt_sequence (void)
3593 {
3594 struct remote_state *rs = get_remote_state ();
3595
3596 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3597 remote_serial_write ("\x03", 1);
3598 else if (interrupt_sequence_mode == interrupt_sequence_break)
3599 serial_send_break (rs->remote_desc);
3600 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3601 {
3602 serial_send_break (rs->remote_desc);
3603 remote_serial_write ("g", 1);
3604 }
3605 else
3606 internal_error (__FILE__, __LINE__,
3607 _("Invalid value for interrupt_sequence_mode: %s."),
3608 interrupt_sequence_mode);
3609 }
3610
3611
3612 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3613 and extract the PTID. Returns NULL_PTID if not found. */
3614
3615 static ptid_t
3616 stop_reply_extract_thread (char *stop_reply)
3617 {
3618 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3619 {
3620 char *p;
3621
3622 /* Txx r:val ; r:val (...) */
3623 p = &stop_reply[3];
3624
3625 /* Look for "register" named "thread". */
3626 while (*p != '\0')
3627 {
3628 char *p1;
3629
3630 p1 = strchr (p, ':');
3631 if (p1 == NULL)
3632 return null_ptid;
3633
3634 if (strncmp (p, "thread", p1 - p) == 0)
3635 return read_ptid (++p1, &p);
3636
3637 p1 = strchr (p, ';');
3638 if (p1 == NULL)
3639 return null_ptid;
3640 p1++;
3641
3642 p = p1;
3643 }
3644 }
3645
3646 return null_ptid;
3647 }
3648
3649 /* Determine the remote side's current thread. If we have a stop
3650 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3651 "thread" register we can extract the current thread from. If not,
3652 ask the remote which is the current thread with qC. The former
3653 method avoids a roundtrip. */
3654
3655 static ptid_t
3656 get_current_thread (char *wait_status)
3657 {
3658 ptid_t ptid = null_ptid;
3659
3660 /* Note we don't use remote_parse_stop_reply as that makes use of
3661 the target architecture, which we haven't yet fully determined at
3662 this point. */
3663 if (wait_status != NULL)
3664 ptid = stop_reply_extract_thread (wait_status);
3665 if (ptid_equal (ptid, null_ptid))
3666 ptid = remote_current_thread (inferior_ptid);
3667
3668 return ptid;
3669 }
3670
3671 /* Query the remote target for which is the current thread/process,
3672 add it to our tables, and update INFERIOR_PTID. The caller is
3673 responsible for setting the state such that the remote end is ready
3674 to return the current thread.
3675
3676 This function is called after handling the '?' or 'vRun' packets,
3677 whose response is a stop reply from which we can also try
3678 extracting the thread. If the target doesn't support the explicit
3679 qC query, we infer the current thread from that stop reply, passed
3680 in in WAIT_STATUS, which may be NULL. */
3681
3682 static void
3683 add_current_inferior_and_thread (char *wait_status)
3684 {
3685 struct remote_state *rs = get_remote_state ();
3686 int fake_pid_p = 0;
3687 ptid_t ptid;
3688
3689 inferior_ptid = null_ptid;
3690
3691 /* Now, if we have thread information, update inferior_ptid. */
3692 ptid = get_current_thread (wait_status);
3693
3694 if (!ptid_equal (ptid, null_ptid))
3695 {
3696 if (!remote_multi_process_p (rs))
3697 fake_pid_p = 1;
3698
3699 inferior_ptid = ptid;
3700 }
3701 else
3702 {
3703 /* Without this, some commands which require an active target
3704 (such as kill) won't work. This variable serves (at least)
3705 double duty as both the pid of the target process (if it has
3706 such), and as a flag indicating that a target is active. */
3707 inferior_ptid = magic_null_ptid;
3708 fake_pid_p = 1;
3709 }
3710
3711 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3712
3713 /* Add the main thread. */
3714 add_thread_silent (inferior_ptid);
3715 }
3716
3717 /* Print info about a thread that was found already stopped on
3718 connection. */
3719
3720 static void
3721 print_one_stopped_thread (struct thread_info *thread)
3722 {
3723 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3724
3725 switch_to_thread (thread->ptid);
3726 stop_pc = get_frame_pc (get_current_frame ());
3727 set_current_sal_from_frame (get_current_frame ());
3728
3729 thread->suspend.waitstatus_pending_p = 0;
3730
3731 if (ws->kind == TARGET_WAITKIND_STOPPED)
3732 {
3733 enum gdb_signal sig = ws->value.sig;
3734
3735 if (signal_print_state (sig))
3736 observer_notify_signal_received (sig);
3737 }
3738 observer_notify_normal_stop (NULL, 1);
3739 }
3740
3741 /* Process all initial stop replies the remote side sent in response
3742 to the ? packet. These indicate threads that were already stopped
3743 on initial connection. We mark these threads as stopped and print
3744 their current frame before giving the user the prompt. */
3745
3746 static void
3747 process_initial_stop_replies (int from_tty)
3748 {
3749 int pending_stop_replies = stop_reply_queue_length ();
3750 struct inferior *inf;
3751 struct thread_info *thread;
3752 struct thread_info *selected = NULL;
3753 struct thread_info *lowest_stopped = NULL;
3754 struct thread_info *first = NULL;
3755
3756 /* Consume the initial pending events. */
3757 while (pending_stop_replies-- > 0)
3758 {
3759 ptid_t waiton_ptid = minus_one_ptid;
3760 ptid_t event_ptid;
3761 struct target_waitstatus ws;
3762 int ignore_event = 0;
3763 struct thread_info *thread;
3764
3765 memset (&ws, 0, sizeof (ws));
3766 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3767 if (remote_debug)
3768 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3769
3770 switch (ws.kind)
3771 {
3772 case TARGET_WAITKIND_IGNORE:
3773 case TARGET_WAITKIND_NO_RESUMED:
3774 case TARGET_WAITKIND_SIGNALLED:
3775 case TARGET_WAITKIND_EXITED:
3776 /* We shouldn't see these, but if we do, just ignore. */
3777 if (remote_debug)
3778 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3779 ignore_event = 1;
3780 break;
3781
3782 case TARGET_WAITKIND_EXECD:
3783 xfree (ws.value.execd_pathname);
3784 break;
3785 default:
3786 break;
3787 }
3788
3789 if (ignore_event)
3790 continue;
3791
3792 thread = find_thread_ptid (event_ptid);
3793
3794 if (ws.kind == TARGET_WAITKIND_STOPPED)
3795 {
3796 enum gdb_signal sig = ws.value.sig;
3797
3798 /* Stubs traditionally report SIGTRAP as initial signal,
3799 instead of signal 0. Suppress it. */
3800 if (sig == GDB_SIGNAL_TRAP)
3801 sig = GDB_SIGNAL_0;
3802 thread->suspend.stop_signal = sig;
3803 ws.value.sig = sig;
3804 }
3805
3806 thread->suspend.waitstatus = ws;
3807
3808 if (ws.kind != TARGET_WAITKIND_STOPPED
3809 || ws.value.sig != GDB_SIGNAL_0)
3810 thread->suspend.waitstatus_pending_p = 1;
3811
3812 set_executing (event_ptid, 0);
3813 set_running (event_ptid, 0);
3814 }
3815
3816 /* "Notice" the new inferiors before anything related to
3817 registers/memory. */
3818 ALL_INFERIORS (inf)
3819 {
3820 if (inf->pid == 0)
3821 continue;
3822
3823 inf->needs_setup = 1;
3824
3825 if (non_stop)
3826 {
3827 thread = any_live_thread_of_process (inf->pid);
3828 notice_new_inferior (thread->ptid,
3829 thread->state == THREAD_RUNNING,
3830 from_tty);
3831 }
3832 }
3833
3834 /* If all-stop on top of non-stop, pause all threads. Note this
3835 records the threads' stop pc, so must be done after "noticing"
3836 the inferiors. */
3837 if (!non_stop)
3838 {
3839 stop_all_threads ();
3840
3841 /* If all threads of an inferior were already stopped, we
3842 haven't setup the inferior yet. */
3843 ALL_INFERIORS (inf)
3844 {
3845 if (inf->pid == 0)
3846 continue;
3847
3848 if (inf->needs_setup)
3849 {
3850 thread = any_live_thread_of_process (inf->pid);
3851 switch_to_thread_no_regs (thread);
3852 setup_inferior (0);
3853 }
3854 }
3855 }
3856
3857 /* Now go over all threads that are stopped, and print their current
3858 frame. If all-stop, then if there's a signalled thread, pick
3859 that as current. */
3860 ALL_NON_EXITED_THREADS (thread)
3861 {
3862 struct target_waitstatus *ws;
3863
3864 if (first == NULL)
3865 first = thread;
3866
3867 if (!non_stop)
3868 set_running (thread->ptid, 0);
3869 else if (thread->state != THREAD_STOPPED)
3870 continue;
3871
3872 ws = &thread->suspend.waitstatus;
3873
3874 if (selected == NULL
3875 && thread->suspend.waitstatus_pending_p)
3876 selected = thread;
3877
3878 if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3879 lowest_stopped = thread;
3880
3881 if (non_stop)
3882 print_one_stopped_thread (thread);
3883 }
3884
3885 /* In all-stop, we only print the status of one thread, and leave
3886 others with their status pending. */
3887 if (!non_stop)
3888 {
3889 thread = selected;
3890 if (thread == NULL)
3891 thread = lowest_stopped;
3892 if (thread == NULL)
3893 thread = first;
3894
3895 print_one_stopped_thread (thread);
3896 }
3897
3898 /* For "info program". */
3899 thread = inferior_thread ();
3900 if (thread->state == THREAD_STOPPED)
3901 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3902 }
3903
3904 static void
3905 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3906 {
3907 struct remote_state *rs = get_remote_state ();
3908 struct packet_config *noack_config;
3909 char *wait_status = NULL;
3910
3911 immediate_quit++; /* Allow user to interrupt it. */
3912 QUIT;
3913
3914 if (interrupt_on_connect)
3915 send_interrupt_sequence ();
3916
3917 /* Ack any packet which the remote side has already sent. */
3918 serial_write (rs->remote_desc, "+", 1);
3919
3920 /* Signal other parts that we're going through the initial setup,
3921 and so things may not be stable yet. */
3922 rs->starting_up = 1;
3923
3924 /* The first packet we send to the target is the optional "supported
3925 packets" request. If the target can answer this, it will tell us
3926 which later probes to skip. */
3927 remote_query_supported ();
3928
3929 /* If the stub wants to get a QAllow, compose one and send it. */
3930 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3931 remote_set_permissions (target);
3932
3933 /* Next, we possibly activate noack mode.
3934
3935 If the QStartNoAckMode packet configuration is set to AUTO,
3936 enable noack mode if the stub reported a wish for it with
3937 qSupported.
3938
3939 If set to TRUE, then enable noack mode even if the stub didn't
3940 report it in qSupported. If the stub doesn't reply OK, the
3941 session ends with an error.
3942
3943 If FALSE, then don't activate noack mode, regardless of what the
3944 stub claimed should be the default with qSupported. */
3945
3946 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3947 if (packet_config_support (noack_config) != PACKET_DISABLE)
3948 {
3949 putpkt ("QStartNoAckMode");
3950 getpkt (&rs->buf, &rs->buf_size, 0);
3951 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3952 rs->noack_mode = 1;
3953 }
3954
3955 if (extended_p)
3956 {
3957 /* Tell the remote that we are using the extended protocol. */
3958 putpkt ("!");
3959 getpkt (&rs->buf, &rs->buf_size, 0);
3960 }
3961
3962 /* Let the target know which signals it is allowed to pass down to
3963 the program. */
3964 update_signals_program_target ();
3965
3966 /* Next, if the target can specify a description, read it. We do
3967 this before anything involving memory or registers. */
3968 target_find_description ();
3969
3970 /* Next, now that we know something about the target, update the
3971 address spaces in the program spaces. */
3972 update_address_spaces ();
3973
3974 /* On OSs where the list of libraries is global to all
3975 processes, we fetch them early. */
3976 if (gdbarch_has_global_solist (target_gdbarch ()))
3977 solib_add (NULL, from_tty, target, auto_solib_add);
3978
3979 if (target_is_non_stop_p ())
3980 {
3981 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3982 error (_("Non-stop mode requested, but remote "
3983 "does not support non-stop"));
3984
3985 putpkt ("QNonStop:1");
3986 getpkt (&rs->buf, &rs->buf_size, 0);
3987
3988 if (strcmp (rs->buf, "OK") != 0)
3989 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3990
3991 /* Find about threads and processes the stub is already
3992 controlling. We default to adding them in the running state.
3993 The '?' query below will then tell us about which threads are
3994 stopped. */
3995 remote_update_thread_list (target);
3996 }
3997 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3998 {
3999 /* Don't assume that the stub can operate in all-stop mode.
4000 Request it explicitly. */
4001 putpkt ("QNonStop:0");
4002 getpkt (&rs->buf, &rs->buf_size, 0);
4003
4004 if (strcmp (rs->buf, "OK") != 0)
4005 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4006 }
4007
4008 /* Upload TSVs regardless of whether the target is running or not. The
4009 remote stub, such as GDBserver, may have some predefined or builtin
4010 TSVs, even if the target is not running. */
4011 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4012 {
4013 struct uploaded_tsv *uploaded_tsvs = NULL;
4014
4015 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4016 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4017 }
4018
4019 /* Check whether the target is running now. */
4020 putpkt ("?");
4021 getpkt (&rs->buf, &rs->buf_size, 0);
4022
4023 if (!target_is_non_stop_p ())
4024 {
4025 ptid_t ptid;
4026 int fake_pid_p = 0;
4027 struct inferior *inf;
4028
4029 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4030 {
4031 if (!extended_p)
4032 error (_("The target is not running (try extended-remote?)"));
4033
4034 /* We're connected, but not running. Drop out before we
4035 call start_remote. */
4036 rs->starting_up = 0;
4037 return;
4038 }
4039 else
4040 {
4041 /* Save the reply for later. */
4042 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4043 strcpy (wait_status, rs->buf);
4044 }
4045
4046 /* Fetch thread list. */
4047 target_update_thread_list ();
4048
4049 /* Let the stub know that we want it to return the thread. */
4050 set_continue_thread (minus_one_ptid);
4051
4052 if (thread_count () == 0)
4053 {
4054 /* Target has no concept of threads at all. GDB treats
4055 non-threaded target as single-threaded; add a main
4056 thread. */
4057 add_current_inferior_and_thread (wait_status);
4058 }
4059 else
4060 {
4061 /* We have thread information; select the thread the target
4062 says should be current. If we're reconnecting to a
4063 multi-threaded program, this will ideally be the thread
4064 that last reported an event before GDB disconnected. */
4065 inferior_ptid = get_current_thread (wait_status);
4066 if (ptid_equal (inferior_ptid, null_ptid))
4067 {
4068 /* Odd... The target was able to list threads, but not
4069 tell us which thread was current (no "thread"
4070 register in T stop reply?). Just pick the first
4071 thread in the thread list then. */
4072
4073 if (remote_debug)
4074 fprintf_unfiltered (gdb_stdlog,
4075 "warning: couldn't determine remote "
4076 "current thread; picking first in list.\n");
4077
4078 inferior_ptid = thread_list->ptid;
4079 }
4080 }
4081
4082 /* init_wait_for_inferior should be called before get_offsets in order
4083 to manage `inserted' flag in bp loc in a correct state.
4084 breakpoint_init_inferior, called from init_wait_for_inferior, set
4085 `inserted' flag to 0, while before breakpoint_re_set, called from
4086 start_remote, set `inserted' flag to 1. In the initialization of
4087 inferior, breakpoint_init_inferior should be called first, and then
4088 breakpoint_re_set can be called. If this order is broken, state of
4089 `inserted' flag is wrong, and cause some problems on breakpoint
4090 manipulation. */
4091 init_wait_for_inferior ();
4092
4093 get_offsets (); /* Get text, data & bss offsets. */
4094
4095 /* If we could not find a description using qXfer, and we know
4096 how to do it some other way, try again. This is not
4097 supported for non-stop; it could be, but it is tricky if
4098 there are no stopped threads when we connect. */
4099 if (remote_read_description_p (target)
4100 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4101 {
4102 target_clear_description ();
4103 target_find_description ();
4104 }
4105
4106 /* Use the previously fetched status. */
4107 gdb_assert (wait_status != NULL);
4108 strcpy (rs->buf, wait_status);
4109 rs->cached_wait_status = 1;
4110
4111 immediate_quit--;
4112 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4113 }
4114 else
4115 {
4116 /* Clear WFI global state. Do this before finding about new
4117 threads and inferiors, and setting the current inferior.
4118 Otherwise we would clear the proceed status of the current
4119 inferior when we want its stop_soon state to be preserved
4120 (see notice_new_inferior). */
4121 init_wait_for_inferior ();
4122
4123 /* In non-stop, we will either get an "OK", meaning that there
4124 are no stopped threads at this time; or, a regular stop
4125 reply. In the latter case, there may be more than one thread
4126 stopped --- we pull them all out using the vStopped
4127 mechanism. */
4128 if (strcmp (rs->buf, "OK") != 0)
4129 {
4130 struct notif_client *notif = &notif_client_stop;
4131
4132 /* remote_notif_get_pending_replies acks this one, and gets
4133 the rest out. */
4134 rs->notif_state->pending_event[notif_client_stop.id]
4135 = remote_notif_parse (notif, rs->buf);
4136 remote_notif_get_pending_events (notif);
4137 }
4138
4139 if (thread_count () == 0)
4140 {
4141 if (!extended_p)
4142 error (_("The target is not running (try extended-remote?)"));
4143
4144 /* We're connected, but not running. Drop out before we
4145 call start_remote. */
4146 rs->starting_up = 0;
4147 return;
4148 }
4149
4150 /* In non-stop mode, any cached wait status will be stored in
4151 the stop reply queue. */
4152 gdb_assert (wait_status == NULL);
4153
4154 /* Report all signals during attach/startup. */
4155 remote_pass_signals (target, 0, NULL);
4156
4157 /* If there are already stopped threads, mark them stopped and
4158 report their stops before giving the prompt to the user. */
4159 process_initial_stop_replies (from_tty);
4160
4161 if (target_can_async_p ())
4162 target_async (1);
4163 }
4164
4165 /* If we connected to a live target, do some additional setup. */
4166 if (target_has_execution)
4167 {
4168 if (symfile_objfile) /* No use without a symbol-file. */
4169 remote_check_symbols ();
4170 }
4171
4172 /* Possibly the target has been engaged in a trace run started
4173 previously; find out where things are at. */
4174 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4175 {
4176 struct uploaded_tp *uploaded_tps = NULL;
4177
4178 if (current_trace_status ()->running)
4179 printf_filtered (_("Trace is already running on the target.\n"));
4180
4181 remote_upload_tracepoints (target, &uploaded_tps);
4182
4183 merge_uploaded_tracepoints (&uploaded_tps);
4184 }
4185
4186 /* The thread and inferior lists are now synchronized with the
4187 target, our symbols have been relocated, and we're merged the
4188 target's tracepoints with ours. We're done with basic start
4189 up. */
4190 rs->starting_up = 0;
4191
4192 /* Maybe breakpoints are global and need to be inserted now. */
4193 if (breakpoints_should_be_inserted_now ())
4194 insert_breakpoints ();
4195 }
4196
4197 /* Open a connection to a remote debugger.
4198 NAME is the filename used for communication. */
4199
4200 static void
4201 remote_open (const char *name, int from_tty)
4202 {
4203 remote_open_1 (name, from_tty, &remote_ops, 0);
4204 }
4205
4206 /* Open a connection to a remote debugger using the extended
4207 remote gdb protocol. NAME is the filename used for communication. */
4208
4209 static void
4210 extended_remote_open (const char *name, int from_tty)
4211 {
4212 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4213 }
4214
4215 /* Reset all packets back to "unknown support". Called when opening a
4216 new connection to a remote target. */
4217
4218 static void
4219 reset_all_packet_configs_support (void)
4220 {
4221 int i;
4222
4223 for (i = 0; i < PACKET_MAX; i++)
4224 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4225 }
4226
4227 /* Initialize all packet configs. */
4228
4229 static void
4230 init_all_packet_configs (void)
4231 {
4232 int i;
4233
4234 for (i = 0; i < PACKET_MAX; i++)
4235 {
4236 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4237 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4238 }
4239 }
4240
4241 /* Symbol look-up. */
4242
4243 static void
4244 remote_check_symbols (void)
4245 {
4246 struct remote_state *rs = get_remote_state ();
4247 char *msg, *reply, *tmp;
4248 struct bound_minimal_symbol sym;
4249 int end;
4250 struct cleanup *old_chain;
4251
4252 /* The remote side has no concept of inferiors that aren't running
4253 yet, it only knows about running processes. If we're connected
4254 but our current inferior is not running, we should not invite the
4255 remote target to request symbol lookups related to its
4256 (unrelated) current process. */
4257 if (!target_has_execution)
4258 return;
4259
4260 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4261 return;
4262
4263 /* Make sure the remote is pointing at the right process. Note
4264 there's no way to select "no process". */
4265 set_general_process ();
4266
4267 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4268 because we need both at the same time. */
4269 msg = (char *) xmalloc (get_remote_packet_size ());
4270 old_chain = make_cleanup (xfree, msg);
4271
4272 /* Invite target to request symbol lookups. */
4273
4274 putpkt ("qSymbol::");
4275 getpkt (&rs->buf, &rs->buf_size, 0);
4276 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4277 reply = rs->buf;
4278
4279 while (startswith (reply, "qSymbol:"))
4280 {
4281 struct bound_minimal_symbol sym;
4282
4283 tmp = &reply[8];
4284 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4285 msg[end] = '\0';
4286 sym = lookup_minimal_symbol (msg, NULL, NULL);
4287 if (sym.minsym == NULL)
4288 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4289 else
4290 {
4291 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4292 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4293
4294 /* If this is a function address, return the start of code
4295 instead of any data function descriptor. */
4296 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4297 sym_addr,
4298 &current_target);
4299
4300 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4301 phex_nz (sym_addr, addr_size), &reply[8]);
4302 }
4303
4304 putpkt (msg);
4305 getpkt (&rs->buf, &rs->buf_size, 0);
4306 reply = rs->buf;
4307 }
4308
4309 do_cleanups (old_chain);
4310 }
4311
4312 static struct serial *
4313 remote_serial_open (const char *name)
4314 {
4315 static int udp_warning = 0;
4316
4317 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4318 of in ser-tcp.c, because it is the remote protocol assuming that the
4319 serial connection is reliable and not the serial connection promising
4320 to be. */
4321 if (!udp_warning && startswith (name, "udp:"))
4322 {
4323 warning (_("The remote protocol may be unreliable over UDP.\n"
4324 "Some events may be lost, rendering further debugging "
4325 "impossible."));
4326 udp_warning = 1;
4327 }
4328
4329 return serial_open (name);
4330 }
4331
4332 /* Inform the target of our permission settings. The permission flags
4333 work without this, but if the target knows the settings, it can do
4334 a couple things. First, it can add its own check, to catch cases
4335 that somehow manage to get by the permissions checks in target
4336 methods. Second, if the target is wired to disallow particular
4337 settings (for instance, a system in the field that is not set up to
4338 be able to stop at a breakpoint), it can object to any unavailable
4339 permissions. */
4340
4341 void
4342 remote_set_permissions (struct target_ops *self)
4343 {
4344 struct remote_state *rs = get_remote_state ();
4345
4346 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4347 "WriteReg:%x;WriteMem:%x;"
4348 "InsertBreak:%x;InsertTrace:%x;"
4349 "InsertFastTrace:%x;Stop:%x",
4350 may_write_registers, may_write_memory,
4351 may_insert_breakpoints, may_insert_tracepoints,
4352 may_insert_fast_tracepoints, may_stop);
4353 putpkt (rs->buf);
4354 getpkt (&rs->buf, &rs->buf_size, 0);
4355
4356 /* If the target didn't like the packet, warn the user. Do not try
4357 to undo the user's settings, that would just be maddening. */
4358 if (strcmp (rs->buf, "OK") != 0)
4359 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4360 }
4361
4362 /* This type describes each known response to the qSupported
4363 packet. */
4364 struct protocol_feature
4365 {
4366 /* The name of this protocol feature. */
4367 const char *name;
4368
4369 /* The default for this protocol feature. */
4370 enum packet_support default_support;
4371
4372 /* The function to call when this feature is reported, or after
4373 qSupported processing if the feature is not supported.
4374 The first argument points to this structure. The second
4375 argument indicates whether the packet requested support be
4376 enabled, disabled, or probed (or the default, if this function
4377 is being called at the end of processing and this feature was
4378 not reported). The third argument may be NULL; if not NULL, it
4379 is a NUL-terminated string taken from the packet following
4380 this feature's name and an equals sign. */
4381 void (*func) (const struct protocol_feature *, enum packet_support,
4382 const char *);
4383
4384 /* The corresponding packet for this feature. Only used if
4385 FUNC is remote_supported_packet. */
4386 int packet;
4387 };
4388
4389 static void
4390 remote_supported_packet (const struct protocol_feature *feature,
4391 enum packet_support support,
4392 const char *argument)
4393 {
4394 if (argument)
4395 {
4396 warning (_("Remote qSupported response supplied an unexpected value for"
4397 " \"%s\"."), feature->name);
4398 return;
4399 }
4400
4401 remote_protocol_packets[feature->packet].support = support;
4402 }
4403
4404 static void
4405 remote_packet_size (const struct protocol_feature *feature,
4406 enum packet_support support, const char *value)
4407 {
4408 struct remote_state *rs = get_remote_state ();
4409
4410 int packet_size;
4411 char *value_end;
4412
4413 if (support != PACKET_ENABLE)
4414 return;
4415
4416 if (value == NULL || *value == '\0')
4417 {
4418 warning (_("Remote target reported \"%s\" without a size."),
4419 feature->name);
4420 return;
4421 }
4422
4423 errno = 0;
4424 packet_size = strtol (value, &value_end, 16);
4425 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4426 {
4427 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4428 feature->name, value);
4429 return;
4430 }
4431
4432 /* Record the new maximum packet size. */
4433 rs->explicit_packet_size = packet_size;
4434 }
4435
4436 static const struct protocol_feature remote_protocol_features[] = {
4437 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4438 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4439 PACKET_qXfer_auxv },
4440 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4441 PACKET_qXfer_exec_file },
4442 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4443 PACKET_qXfer_features },
4444 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4445 PACKET_qXfer_libraries },
4446 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4447 PACKET_qXfer_libraries_svr4 },
4448 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4449 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4450 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4451 PACKET_qXfer_memory_map },
4452 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4453 PACKET_qXfer_spu_read },
4454 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4455 PACKET_qXfer_spu_write },
4456 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4457 PACKET_qXfer_osdata },
4458 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4459 PACKET_qXfer_threads },
4460 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4461 PACKET_qXfer_traceframe_info },
4462 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4463 PACKET_QPassSignals },
4464 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4465 PACKET_QProgramSignals },
4466 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4467 PACKET_QStartNoAckMode },
4468 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4469 PACKET_multiprocess_feature },
4470 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4471 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4472 PACKET_qXfer_siginfo_read },
4473 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4474 PACKET_qXfer_siginfo_write },
4475 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4476 PACKET_ConditionalTracepoints },
4477 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4478 PACKET_ConditionalBreakpoints },
4479 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4480 PACKET_BreakpointCommands },
4481 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4482 PACKET_FastTracepoints },
4483 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4484 PACKET_StaticTracepoints },
4485 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4486 PACKET_InstallInTrace},
4487 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4488 PACKET_DisconnectedTracing_feature },
4489 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4490 PACKET_bc },
4491 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4492 PACKET_bs },
4493 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4494 PACKET_TracepointSource },
4495 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4496 PACKET_QAllow },
4497 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4498 PACKET_EnableDisableTracepoints_feature },
4499 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4500 PACKET_qXfer_fdpic },
4501 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4502 PACKET_qXfer_uib },
4503 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4504 PACKET_QDisableRandomization },
4505 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4506 { "QTBuffer:size", PACKET_DISABLE,
4507 remote_supported_packet, PACKET_QTBuffer_size},
4508 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4509 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4510 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4511 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4512 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4513 PACKET_qXfer_btrace },
4514 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4515 PACKET_qXfer_btrace_conf },
4516 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4517 PACKET_Qbtrace_conf_bts_size },
4518 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4519 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4520 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4521 PACKET_fork_event_feature },
4522 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4523 PACKET_vfork_event_feature },
4524 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4525 PACKET_exec_event_feature },
4526 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4527 PACKET_Qbtrace_conf_pt_size },
4528 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4529 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4530 };
4531
4532 static char *remote_support_xml;
4533
4534 /* Register string appended to "xmlRegisters=" in qSupported query. */
4535
4536 void
4537 register_remote_support_xml (const char *xml)
4538 {
4539 #if defined(HAVE_LIBEXPAT)
4540 if (remote_support_xml == NULL)
4541 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4542 else
4543 {
4544 char *copy = xstrdup (remote_support_xml + 13);
4545 char *p = strtok (copy, ",");
4546
4547 do
4548 {
4549 if (strcmp (p, xml) == 0)
4550 {
4551 /* already there */
4552 xfree (copy);
4553 return;
4554 }
4555 }
4556 while ((p = strtok (NULL, ",")) != NULL);
4557 xfree (copy);
4558
4559 remote_support_xml = reconcat (remote_support_xml,
4560 remote_support_xml, ",", xml,
4561 (char *) NULL);
4562 }
4563 #endif
4564 }
4565
4566 static char *
4567 remote_query_supported_append (char *msg, const char *append)
4568 {
4569 if (msg)
4570 return reconcat (msg, msg, ";", append, (char *) NULL);
4571 else
4572 return xstrdup (append);
4573 }
4574
4575 static void
4576 remote_query_supported (void)
4577 {
4578 struct remote_state *rs = get_remote_state ();
4579 char *next;
4580 int i;
4581 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4582
4583 /* The packet support flags are handled differently for this packet
4584 than for most others. We treat an error, a disabled packet, and
4585 an empty response identically: any features which must be reported
4586 to be used will be automatically disabled. An empty buffer
4587 accomplishes this, since that is also the representation for a list
4588 containing no features. */
4589
4590 rs->buf[0] = 0;
4591 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4592 {
4593 char *q = NULL;
4594 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4595
4596 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4597 q = remote_query_supported_append (q, "multiprocess+");
4598
4599 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4600 q = remote_query_supported_append (q, "swbreak+");
4601 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4602 q = remote_query_supported_append (q, "hwbreak+");
4603
4604 q = remote_query_supported_append (q, "qRelocInsn+");
4605
4606 if (rs->extended)
4607 {
4608 if (packet_set_cmd_state (PACKET_fork_event_feature)
4609 != AUTO_BOOLEAN_FALSE)
4610 q = remote_query_supported_append (q, "fork-events+");
4611 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4612 != AUTO_BOOLEAN_FALSE)
4613 q = remote_query_supported_append (q, "vfork-events+");
4614 if (packet_set_cmd_state (PACKET_exec_event_feature)
4615 != AUTO_BOOLEAN_FALSE)
4616 q = remote_query_supported_append (q, "exec-events+");
4617 }
4618
4619 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4620 q = remote_query_supported_append (q, "vContSupported+");
4621
4622 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4623 q = remote_query_supported_append (q, "QThreadEvents+");
4624
4625 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4626 the qSupported:xmlRegisters=i386 handling. */
4627 if (remote_support_xml != NULL)
4628 q = remote_query_supported_append (q, remote_support_xml);
4629
4630 q = reconcat (q, "qSupported:", q, (char *) NULL);
4631 putpkt (q);
4632
4633 do_cleanups (old_chain);
4634
4635 getpkt (&rs->buf, &rs->buf_size, 0);
4636
4637 /* If an error occured, warn, but do not return - just reset the
4638 buffer to empty and go on to disable features. */
4639 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4640 == PACKET_ERROR)
4641 {
4642 warning (_("Remote failure reply: %s"), rs->buf);
4643 rs->buf[0] = 0;
4644 }
4645 }
4646
4647 memset (seen, 0, sizeof (seen));
4648
4649 next = rs->buf;
4650 while (*next)
4651 {
4652 enum packet_support is_supported;
4653 char *p, *end, *name_end, *value;
4654
4655 /* First separate out this item from the rest of the packet. If
4656 there's another item after this, we overwrite the separator
4657 (terminated strings are much easier to work with). */
4658 p = next;
4659 end = strchr (p, ';');
4660 if (end == NULL)
4661 {
4662 end = p + strlen (p);
4663 next = end;
4664 }
4665 else
4666 {
4667 *end = '\0';
4668 next = end + 1;
4669
4670 if (end == p)
4671 {
4672 warning (_("empty item in \"qSupported\" response"));
4673 continue;
4674 }
4675 }
4676
4677 name_end = strchr (p, '=');
4678 if (name_end)
4679 {
4680 /* This is a name=value entry. */
4681 is_supported = PACKET_ENABLE;
4682 value = name_end + 1;
4683 *name_end = '\0';
4684 }
4685 else
4686 {
4687 value = NULL;
4688 switch (end[-1])
4689 {
4690 case '+':
4691 is_supported = PACKET_ENABLE;
4692 break;
4693
4694 case '-':
4695 is_supported = PACKET_DISABLE;
4696 break;
4697
4698 case '?':
4699 is_supported = PACKET_SUPPORT_UNKNOWN;
4700 break;
4701
4702 default:
4703 warning (_("unrecognized item \"%s\" "
4704 "in \"qSupported\" response"), p);
4705 continue;
4706 }
4707 end[-1] = '\0';
4708 }
4709
4710 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4711 if (strcmp (remote_protocol_features[i].name, p) == 0)
4712 {
4713 const struct protocol_feature *feature;
4714
4715 seen[i] = 1;
4716 feature = &remote_protocol_features[i];
4717 feature->func (feature, is_supported, value);
4718 break;
4719 }
4720 }
4721
4722 /* If we increased the packet size, make sure to increase the global
4723 buffer size also. We delay this until after parsing the entire
4724 qSupported packet, because this is the same buffer we were
4725 parsing. */
4726 if (rs->buf_size < rs->explicit_packet_size)
4727 {
4728 rs->buf_size = rs->explicit_packet_size;
4729 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4730 }
4731
4732 /* Handle the defaults for unmentioned features. */
4733 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4734 if (!seen[i])
4735 {
4736 const struct protocol_feature *feature;
4737
4738 feature = &remote_protocol_features[i];
4739 feature->func (feature, feature->default_support, NULL);
4740 }
4741 }
4742
4743 /* Remove any of the remote.c targets from target stack. Upper targets depend
4744 on it so remove them first. */
4745
4746 static void
4747 remote_unpush_target (void)
4748 {
4749 pop_all_targets_at_and_above (process_stratum);
4750 }
4751
4752 static void
4753 remote_open_1 (const char *name, int from_tty,
4754 struct target_ops *target, int extended_p)
4755 {
4756 struct remote_state *rs = get_remote_state ();
4757
4758 if (name == 0)
4759 error (_("To open a remote debug connection, you need to specify what\n"
4760 "serial device is attached to the remote system\n"
4761 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4762
4763 /* See FIXME above. */
4764 if (!target_async_permitted)
4765 wait_forever_enabled_p = 1;
4766
4767 /* If we're connected to a running target, target_preopen will kill it.
4768 Ask this question first, before target_preopen has a chance to kill
4769 anything. */
4770 if (rs->remote_desc != NULL && !have_inferiors ())
4771 {
4772 if (from_tty
4773 && !query (_("Already connected to a remote target. Disconnect? ")))
4774 error (_("Still connected."));
4775 }
4776
4777 /* Here the possibly existing remote target gets unpushed. */
4778 target_preopen (from_tty);
4779
4780 /* Make sure we send the passed signals list the next time we resume. */
4781 xfree (rs->last_pass_packet);
4782 rs->last_pass_packet = NULL;
4783
4784 /* Make sure we send the program signals list the next time we
4785 resume. */
4786 xfree (rs->last_program_signals_packet);
4787 rs->last_program_signals_packet = NULL;
4788
4789 remote_fileio_reset ();
4790 reopen_exec_file ();
4791 reread_symbols ();
4792
4793 rs->remote_desc = remote_serial_open (name);
4794 if (!rs->remote_desc)
4795 perror_with_name (name);
4796
4797 if (baud_rate != -1)
4798 {
4799 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4800 {
4801 /* The requested speed could not be set. Error out to
4802 top level after closing remote_desc. Take care to
4803 set remote_desc to NULL to avoid closing remote_desc
4804 more than once. */
4805 serial_close (rs->remote_desc);
4806 rs->remote_desc = NULL;
4807 perror_with_name (name);
4808 }
4809 }
4810
4811 serial_setparity (rs->remote_desc, serial_parity);
4812 serial_raw (rs->remote_desc);
4813
4814 /* If there is something sitting in the buffer we might take it as a
4815 response to a command, which would be bad. */
4816 serial_flush_input (rs->remote_desc);
4817
4818 if (from_tty)
4819 {
4820 puts_filtered ("Remote debugging using ");
4821 puts_filtered (name);
4822 puts_filtered ("\n");
4823 }
4824 push_target (target); /* Switch to using remote target now. */
4825
4826 /* Register extra event sources in the event loop. */
4827 remote_async_inferior_event_token
4828 = create_async_event_handler (remote_async_inferior_event_handler,
4829 NULL);
4830 rs->notif_state = remote_notif_state_allocate ();
4831
4832 /* Reset the target state; these things will be queried either by
4833 remote_query_supported or as they are needed. */
4834 reset_all_packet_configs_support ();
4835 rs->cached_wait_status = 0;
4836 rs->explicit_packet_size = 0;
4837 rs->noack_mode = 0;
4838 rs->extended = extended_p;
4839 rs->waiting_for_stop_reply = 0;
4840 rs->ctrlc_pending_p = 0;
4841
4842 rs->general_thread = not_sent_ptid;
4843 rs->continue_thread = not_sent_ptid;
4844 rs->remote_traceframe_number = -1;
4845
4846 /* Probe for ability to use "ThreadInfo" query, as required. */
4847 rs->use_threadinfo_query = 1;
4848 rs->use_threadextra_query = 1;
4849
4850 readahead_cache_invalidate ();
4851
4852 if (target_async_permitted)
4853 {
4854 /* With this target we start out by owning the terminal. */
4855 remote_async_terminal_ours_p = 1;
4856
4857 /* FIXME: cagney/1999-09-23: During the initial connection it is
4858 assumed that the target is already ready and able to respond to
4859 requests. Unfortunately remote_start_remote() eventually calls
4860 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4861 around this. Eventually a mechanism that allows
4862 wait_for_inferior() to expect/get timeouts will be
4863 implemented. */
4864 wait_forever_enabled_p = 0;
4865 }
4866
4867 /* First delete any symbols previously loaded from shared libraries. */
4868 no_shared_libraries (NULL, 0);
4869
4870 /* Start afresh. */
4871 init_thread_list ();
4872
4873 /* Start the remote connection. If error() or QUIT, discard this
4874 target (we'd otherwise be in an inconsistent state) and then
4875 propogate the error on up the exception chain. This ensures that
4876 the caller doesn't stumble along blindly assuming that the
4877 function succeeded. The CLI doesn't have this problem but other
4878 UI's, such as MI do.
4879
4880 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4881 this function should return an error indication letting the
4882 caller restore the previous state. Unfortunately the command
4883 ``target remote'' is directly wired to this function making that
4884 impossible. On a positive note, the CLI side of this problem has
4885 been fixed - the function set_cmd_context() makes it possible for
4886 all the ``target ....'' commands to share a common callback
4887 function. See cli-dump.c. */
4888 {
4889
4890 TRY
4891 {
4892 remote_start_remote (from_tty, target, extended_p);
4893 }
4894 CATCH (ex, RETURN_MASK_ALL)
4895 {
4896 /* Pop the partially set up target - unless something else did
4897 already before throwing the exception. */
4898 if (rs->remote_desc != NULL)
4899 remote_unpush_target ();
4900 if (target_async_permitted)
4901 wait_forever_enabled_p = 1;
4902 throw_exception (ex);
4903 }
4904 END_CATCH
4905 }
4906
4907 remote_btrace_reset ();
4908
4909 if (target_async_permitted)
4910 wait_forever_enabled_p = 1;
4911 }
4912
4913 /* Detach the specified process. */
4914
4915 static void
4916 remote_detach_pid (int pid)
4917 {
4918 struct remote_state *rs = get_remote_state ();
4919
4920 if (remote_multi_process_p (rs))
4921 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4922 else
4923 strcpy (rs->buf, "D");
4924
4925 putpkt (rs->buf);
4926 getpkt (&rs->buf, &rs->buf_size, 0);
4927
4928 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4929 ;
4930 else if (rs->buf[0] == '\0')
4931 error (_("Remote doesn't know how to detach"));
4932 else
4933 error (_("Can't detach process."));
4934 }
4935
4936 /* This detaches a program to which we previously attached, using
4937 inferior_ptid to identify the process. After this is done, GDB
4938 can be used to debug some other program. We better not have left
4939 any breakpoints in the target program or it'll die when it hits
4940 one. */
4941
4942 static void
4943 remote_detach_1 (const char *args, int from_tty)
4944 {
4945 int pid = ptid_get_pid (inferior_ptid);
4946 struct remote_state *rs = get_remote_state ();
4947 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4948 int is_fork_parent;
4949
4950 if (args)
4951 error (_("Argument given to \"detach\" when remotely debugging."));
4952
4953 if (!target_has_execution)
4954 error (_("No process to detach from."));
4955
4956 if (from_tty)
4957 {
4958 char *exec_file = get_exec_file (0);
4959 if (exec_file == NULL)
4960 exec_file = "";
4961 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4962 target_pid_to_str (pid_to_ptid (pid)));
4963 gdb_flush (gdb_stdout);
4964 }
4965
4966 /* Tell the remote target to detach. */
4967 remote_detach_pid (pid);
4968
4969 if (from_tty && !rs->extended)
4970 puts_filtered (_("Ending remote debugging.\n"));
4971
4972 /* Check to see if we are detaching a fork parent. Note that if we
4973 are detaching a fork child, tp == NULL. */
4974 is_fork_parent = (tp != NULL
4975 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4976
4977 /* If doing detach-on-fork, we don't mourn, because that will delete
4978 breakpoints that should be available for the followed inferior. */
4979 if (!is_fork_parent)
4980 target_mourn_inferior ();
4981 else
4982 {
4983 inferior_ptid = null_ptid;
4984 detach_inferior (pid);
4985 }
4986 }
4987
4988 static void
4989 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4990 {
4991 remote_detach_1 (args, from_tty);
4992 }
4993
4994 static void
4995 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4996 {
4997 remote_detach_1 (args, from_tty);
4998 }
4999
5000 /* Target follow-fork function for remote targets. On entry, and
5001 at return, the current inferior is the fork parent.
5002
5003 Note that although this is currently only used for extended-remote,
5004 it is named remote_follow_fork in anticipation of using it for the
5005 remote target as well. */
5006
5007 static int
5008 remote_follow_fork (struct target_ops *ops, int follow_child,
5009 int detach_fork)
5010 {
5011 struct remote_state *rs = get_remote_state ();
5012 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5013
5014 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5015 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5016 {
5017 /* When following the parent and detaching the child, we detach
5018 the child here. For the case of following the child and
5019 detaching the parent, the detach is done in the target-
5020 independent follow fork code in infrun.c. We can't use
5021 target_detach when detaching an unfollowed child because
5022 the client side doesn't know anything about the child. */
5023 if (detach_fork && !follow_child)
5024 {
5025 /* Detach the fork child. */
5026 ptid_t child_ptid;
5027 pid_t child_pid;
5028
5029 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5030 child_pid = ptid_get_pid (child_ptid);
5031
5032 remote_detach_pid (child_pid);
5033 detach_inferior (child_pid);
5034 }
5035 }
5036 return 0;
5037 }
5038
5039 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5040 in the program space of the new inferior. On entry and at return the
5041 current inferior is the exec'ing inferior. INF is the new exec'd
5042 inferior, which may be the same as the exec'ing inferior unless
5043 follow-exec-mode is "new". */
5044
5045 static void
5046 remote_follow_exec (struct target_ops *ops,
5047 struct inferior *inf, char *execd_pathname)
5048 {
5049 /* We know that this is a target file name, so if it has the "target:"
5050 prefix we strip it off before saving it in the program space. */
5051 if (is_target_filename (execd_pathname))
5052 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5053
5054 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5055 }
5056
5057 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5058
5059 static void
5060 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5061 {
5062 if (args)
5063 error (_("Argument given to \"disconnect\" when remotely debugging."));
5064
5065 /* Make sure we unpush even the extended remote targets; mourn
5066 won't do it. So call remote_mourn directly instead of
5067 target_mourn_inferior. */
5068 remote_mourn (target);
5069
5070 if (from_tty)
5071 puts_filtered ("Ending remote debugging.\n");
5072 }
5073
5074 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5075 be chatty about it. */
5076
5077 static void
5078 extended_remote_attach (struct target_ops *target, const char *args,
5079 int from_tty)
5080 {
5081 struct remote_state *rs = get_remote_state ();
5082 int pid;
5083 char *wait_status = NULL;
5084
5085 pid = parse_pid_to_attach (args);
5086
5087 /* Remote PID can be freely equal to getpid, do not check it here the same
5088 way as in other targets. */
5089
5090 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5091 error (_("This target does not support attaching to a process"));
5092
5093 if (from_tty)
5094 {
5095 char *exec_file = get_exec_file (0);
5096
5097 if (exec_file)
5098 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5099 target_pid_to_str (pid_to_ptid (pid)));
5100 else
5101 printf_unfiltered (_("Attaching to %s\n"),
5102 target_pid_to_str (pid_to_ptid (pid)));
5103
5104 gdb_flush (gdb_stdout);
5105 }
5106
5107 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5108 putpkt (rs->buf);
5109 getpkt (&rs->buf, &rs->buf_size, 0);
5110
5111 switch (packet_ok (rs->buf,
5112 &remote_protocol_packets[PACKET_vAttach]))
5113 {
5114 case PACKET_OK:
5115 if (!target_is_non_stop_p ())
5116 {
5117 /* Save the reply for later. */
5118 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5119 strcpy (wait_status, rs->buf);
5120 }
5121 else if (strcmp (rs->buf, "OK") != 0)
5122 error (_("Attaching to %s failed with: %s"),
5123 target_pid_to_str (pid_to_ptid (pid)),
5124 rs->buf);
5125 break;
5126 case PACKET_UNKNOWN:
5127 error (_("This target does not support attaching to a process"));
5128 default:
5129 error (_("Attaching to %s failed"),
5130 target_pid_to_str (pid_to_ptid (pid)));
5131 }
5132
5133 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5134
5135 inferior_ptid = pid_to_ptid (pid);
5136
5137 if (target_is_non_stop_p ())
5138 {
5139 struct thread_info *thread;
5140
5141 /* Get list of threads. */
5142 remote_update_thread_list (target);
5143
5144 thread = first_thread_of_process (pid);
5145 if (thread)
5146 inferior_ptid = thread->ptid;
5147 else
5148 inferior_ptid = pid_to_ptid (pid);
5149
5150 /* Invalidate our notion of the remote current thread. */
5151 record_currthread (rs, minus_one_ptid);
5152 }
5153 else
5154 {
5155 /* Now, if we have thread information, update inferior_ptid. */
5156 inferior_ptid = remote_current_thread (inferior_ptid);
5157
5158 /* Add the main thread to the thread list. */
5159 add_thread_silent (inferior_ptid);
5160 }
5161
5162 /* Next, if the target can specify a description, read it. We do
5163 this before anything involving memory or registers. */
5164 target_find_description ();
5165
5166 if (!target_is_non_stop_p ())
5167 {
5168 /* Use the previously fetched status. */
5169 gdb_assert (wait_status != NULL);
5170
5171 if (target_can_async_p ())
5172 {
5173 struct notif_event *reply
5174 = remote_notif_parse (&notif_client_stop, wait_status);
5175
5176 push_stop_reply ((struct stop_reply *) reply);
5177
5178 target_async (1);
5179 }
5180 else
5181 {
5182 gdb_assert (wait_status != NULL);
5183 strcpy (rs->buf, wait_status);
5184 rs->cached_wait_status = 1;
5185 }
5186 }
5187 else
5188 gdb_assert (wait_status == NULL);
5189 }
5190
5191 /* Implementation of the to_post_attach method. */
5192
5193 static void
5194 extended_remote_post_attach (struct target_ops *ops, int pid)
5195 {
5196 /* Get text, data & bss offsets. */
5197 get_offsets ();
5198
5199 /* In certain cases GDB might not have had the chance to start
5200 symbol lookup up until now. This could happen if the debugged
5201 binary is not using shared libraries, the vsyscall page is not
5202 present (on Linux) and the binary itself hadn't changed since the
5203 debugging process was started. */
5204 if (symfile_objfile != NULL)
5205 remote_check_symbols();
5206 }
5207
5208 \f
5209 /* Check for the availability of vCont. This function should also check
5210 the response. */
5211
5212 static void
5213 remote_vcont_probe (struct remote_state *rs)
5214 {
5215 char *buf;
5216
5217 strcpy (rs->buf, "vCont?");
5218 putpkt (rs->buf);
5219 getpkt (&rs->buf, &rs->buf_size, 0);
5220 buf = rs->buf;
5221
5222 /* Make sure that the features we assume are supported. */
5223 if (startswith (buf, "vCont"))
5224 {
5225 char *p = &buf[5];
5226 int support_c, support_C;
5227
5228 rs->supports_vCont.s = 0;
5229 rs->supports_vCont.S = 0;
5230 support_c = 0;
5231 support_C = 0;
5232 rs->supports_vCont.t = 0;
5233 rs->supports_vCont.r = 0;
5234 while (p && *p == ';')
5235 {
5236 p++;
5237 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5238 rs->supports_vCont.s = 1;
5239 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5240 rs->supports_vCont.S = 1;
5241 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5242 support_c = 1;
5243 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5244 support_C = 1;
5245 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5246 rs->supports_vCont.t = 1;
5247 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5248 rs->supports_vCont.r = 1;
5249
5250 p = strchr (p, ';');
5251 }
5252
5253 /* If c, and C are not all supported, we can't use vCont. Clearing
5254 BUF will make packet_ok disable the packet. */
5255 if (!support_c || !support_C)
5256 buf[0] = 0;
5257 }
5258
5259 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5260 }
5261
5262 /* Helper function for building "vCont" resumptions. Write a
5263 resumption to P. ENDP points to one-passed-the-end of the buffer
5264 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5265 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5266 resumed thread should be single-stepped and/or signalled. If PTID
5267 equals minus_one_ptid, then all threads are resumed; if PTID
5268 represents a process, then all threads of the process are resumed;
5269 the thread to be stepped and/or signalled is given in the global
5270 INFERIOR_PTID. */
5271
5272 static char *
5273 append_resumption (char *p, char *endp,
5274 ptid_t ptid, int step, enum gdb_signal siggnal)
5275 {
5276 struct remote_state *rs = get_remote_state ();
5277
5278 if (step && siggnal != GDB_SIGNAL_0)
5279 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5280 else if (step
5281 /* GDB is willing to range step. */
5282 && use_range_stepping
5283 /* Target supports range stepping. */
5284 && rs->supports_vCont.r
5285 /* We don't currently support range stepping multiple
5286 threads with a wildcard (though the protocol allows it,
5287 so stubs shouldn't make an active effort to forbid
5288 it). */
5289 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5290 {
5291 struct thread_info *tp;
5292
5293 if (ptid_equal (ptid, minus_one_ptid))
5294 {
5295 /* If we don't know about the target thread's tid, then
5296 we're resuming magic_null_ptid (see caller). */
5297 tp = find_thread_ptid (magic_null_ptid);
5298 }
5299 else
5300 tp = find_thread_ptid (ptid);
5301 gdb_assert (tp != NULL);
5302
5303 if (tp->control.may_range_step)
5304 {
5305 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5306
5307 p += xsnprintf (p, endp - p, ";r%s,%s",
5308 phex_nz (tp->control.step_range_start,
5309 addr_size),
5310 phex_nz (tp->control.step_range_end,
5311 addr_size));
5312 }
5313 else
5314 p += xsnprintf (p, endp - p, ";s");
5315 }
5316 else if (step)
5317 p += xsnprintf (p, endp - p, ";s");
5318 else if (siggnal != GDB_SIGNAL_0)
5319 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5320 else
5321 p += xsnprintf (p, endp - p, ";c");
5322
5323 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5324 {
5325 ptid_t nptid;
5326
5327 /* All (-1) threads of process. */
5328 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5329
5330 p += xsnprintf (p, endp - p, ":");
5331 p = write_ptid (p, endp, nptid);
5332 }
5333 else if (!ptid_equal (ptid, minus_one_ptid))
5334 {
5335 p += xsnprintf (p, endp - p, ":");
5336 p = write_ptid (p, endp, ptid);
5337 }
5338
5339 return p;
5340 }
5341
5342 /* Clear the thread's private info on resume. */
5343
5344 static void
5345 resume_clear_thread_private_info (struct thread_info *thread)
5346 {
5347 if (thread->priv != NULL)
5348 {
5349 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5350 thread->priv->watch_data_address = 0;
5351 }
5352 }
5353
5354 /* Append a vCont continue-with-signal action for threads that have a
5355 non-zero stop signal. */
5356
5357 static char *
5358 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5359 {
5360 struct thread_info *thread;
5361
5362 ALL_NON_EXITED_THREADS (thread)
5363 if (ptid_match (thread->ptid, ptid)
5364 && !ptid_equal (inferior_ptid, thread->ptid)
5365 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5366 {
5367 p = append_resumption (p, endp, thread->ptid,
5368 0, thread->suspend.stop_signal);
5369 thread->suspend.stop_signal = GDB_SIGNAL_0;
5370 resume_clear_thread_private_info (thread);
5371 }
5372
5373 return p;
5374 }
5375
5376 /* Resume the remote inferior by using a "vCont" packet. The thread
5377 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5378 resumed thread should be single-stepped and/or signalled. If PTID
5379 equals minus_one_ptid, then all threads are resumed; the thread to
5380 be stepped and/or signalled is given in the global INFERIOR_PTID.
5381 This function returns non-zero iff it resumes the inferior.
5382
5383 This function issues a strict subset of all possible vCont commands at the
5384 moment. */
5385
5386 static int
5387 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5388 {
5389 struct remote_state *rs = get_remote_state ();
5390 char *p;
5391 char *endp;
5392
5393 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5394 remote_vcont_probe (rs);
5395
5396 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5397 return 0;
5398
5399 p = rs->buf;
5400 endp = rs->buf + get_remote_packet_size ();
5401
5402 /* If we could generate a wider range of packets, we'd have to worry
5403 about overflowing BUF. Should there be a generic
5404 "multi-part-packet" packet? */
5405
5406 p += xsnprintf (p, endp - p, "vCont");
5407
5408 if (ptid_equal (ptid, magic_null_ptid))
5409 {
5410 /* MAGIC_NULL_PTID means that we don't have any active threads,
5411 so we don't have any TID numbers the inferior will
5412 understand. Make sure to only send forms that do not specify
5413 a TID. */
5414 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5415 }
5416 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5417 {
5418 /* Resume all threads (of all processes, or of a single
5419 process), with preference for INFERIOR_PTID. This assumes
5420 inferior_ptid belongs to the set of all threads we are about
5421 to resume. */
5422 if (step || siggnal != GDB_SIGNAL_0)
5423 {
5424 /* Step inferior_ptid, with or without signal. */
5425 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5426 }
5427
5428 /* Also pass down any pending signaled resumption for other
5429 threads not the current. */
5430 p = append_pending_thread_resumptions (p, endp, ptid);
5431
5432 /* And continue others without a signal. */
5433 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5434 }
5435 else
5436 {
5437 /* Scheduler locking; resume only PTID. */
5438 append_resumption (p, endp, ptid, step, siggnal);
5439 }
5440
5441 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5442 putpkt (rs->buf);
5443
5444 if (target_is_non_stop_p ())
5445 {
5446 /* In non-stop, the stub replies to vCont with "OK". The stop
5447 reply will be reported asynchronously by means of a `%Stop'
5448 notification. */
5449 getpkt (&rs->buf, &rs->buf_size, 0);
5450 if (strcmp (rs->buf, "OK") != 0)
5451 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5452 }
5453
5454 return 1;
5455 }
5456
5457 /* Tell the remote machine to resume. */
5458
5459 static void
5460 remote_resume (struct target_ops *ops,
5461 ptid_t ptid, int step, enum gdb_signal siggnal)
5462 {
5463 struct remote_state *rs = get_remote_state ();
5464 char *buf;
5465 struct thread_info *thread;
5466
5467 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5468 (explained in remote-notif.c:handle_notification) so
5469 remote_notif_process is not called. We need find a place where
5470 it is safe to start a 'vNotif' sequence. It is good to do it
5471 before resuming inferior, because inferior was stopped and no RSP
5472 traffic at that moment. */
5473 if (!target_is_non_stop_p ())
5474 remote_notif_process (rs->notif_state, &notif_client_stop);
5475
5476 rs->last_sent_signal = siggnal;
5477 rs->last_sent_step = step;
5478
5479 /* The vCont packet doesn't need to specify threads via Hc. */
5480 /* No reverse support (yet) for vCont. */
5481 if (execution_direction != EXEC_REVERSE)
5482 if (remote_vcont_resume (ptid, step, siggnal))
5483 goto done;
5484
5485 /* All other supported resume packets do use Hc, so set the continue
5486 thread. */
5487 if (ptid_equal (ptid, minus_one_ptid))
5488 set_continue_thread (any_thread_ptid);
5489 else
5490 set_continue_thread (ptid);
5491
5492 ALL_NON_EXITED_THREADS (thread)
5493 resume_clear_thread_private_info (thread);
5494
5495 buf = rs->buf;
5496 if (execution_direction == EXEC_REVERSE)
5497 {
5498 /* We don't pass signals to the target in reverse exec mode. */
5499 if (info_verbose && siggnal != GDB_SIGNAL_0)
5500 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5501 siggnal);
5502
5503 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5504 error (_("Remote reverse-step not supported."));
5505 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5506 error (_("Remote reverse-continue not supported."));
5507
5508 strcpy (buf, step ? "bs" : "bc");
5509 }
5510 else if (siggnal != GDB_SIGNAL_0)
5511 {
5512 buf[0] = step ? 'S' : 'C';
5513 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5514 buf[2] = tohex (((int) siggnal) & 0xf);
5515 buf[3] = '\0';
5516 }
5517 else
5518 strcpy (buf, step ? "s" : "c");
5519
5520 putpkt (buf);
5521
5522 done:
5523 /* We are about to start executing the inferior, let's register it
5524 with the event loop. NOTE: this is the one place where all the
5525 execution commands end up. We could alternatively do this in each
5526 of the execution commands in infcmd.c. */
5527 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5528 into infcmd.c in order to allow inferior function calls to work
5529 NOT asynchronously. */
5530 if (target_can_async_p ())
5531 target_async (1);
5532
5533 /* We've just told the target to resume. The remote server will
5534 wait for the inferior to stop, and then send a stop reply. In
5535 the mean time, we can't start another command/query ourselves
5536 because the stub wouldn't be ready to process it. This applies
5537 only to the base all-stop protocol, however. In non-stop (which
5538 only supports vCont), the stub replies with an "OK", and is
5539 immediate able to process further serial input. */
5540 if (!target_is_non_stop_p ())
5541 rs->waiting_for_stop_reply = 1;
5542 }
5543 \f
5544
5545 /* Set up the signal handler for SIGINT, while the target is
5546 executing, ovewriting the 'regular' SIGINT signal handler. */
5547 static void
5548 async_initialize_sigint_signal_handler (void)
5549 {
5550 signal (SIGINT, async_handle_remote_sigint);
5551 }
5552
5553 /* Signal handler for SIGINT, while the target is executing. */
5554 static void
5555 async_handle_remote_sigint (int sig)
5556 {
5557 signal (sig, async_handle_remote_sigint_twice);
5558 /* Note we need to go through gdb_call_async_signal_handler in order
5559 to wake up the event loop on Windows. */
5560 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5561 }
5562
5563 /* Signal handler for SIGINT, installed after SIGINT has already been
5564 sent once. It will take effect the second time that the user sends
5565 a ^C. */
5566 static void
5567 async_handle_remote_sigint_twice (int sig)
5568 {
5569 signal (sig, async_handle_remote_sigint);
5570 /* See note in async_handle_remote_sigint. */
5571 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5572 }
5573
5574 /* Implementation of to_check_pending_interrupt. */
5575
5576 static void
5577 remote_check_pending_interrupt (struct target_ops *self)
5578 {
5579 struct async_signal_handler *token = async_sigint_remote_twice_token;
5580
5581 if (async_signal_handler_is_marked (token))
5582 {
5583 clear_async_signal_handler (token);
5584 call_async_signal_handler (token);
5585 }
5586 }
5587
5588 /* Perform the real interruption of the target execution, in response
5589 to a ^C. */
5590 static void
5591 async_remote_interrupt (gdb_client_data arg)
5592 {
5593 if (remote_debug)
5594 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5595
5596 target_interrupt (inferior_ptid);
5597 }
5598
5599 /* Perform interrupt, if the first attempt did not succeed. Just give
5600 up on the target alltogether. */
5601 static void
5602 async_remote_interrupt_twice (gdb_client_data arg)
5603 {
5604 if (remote_debug)
5605 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5606
5607 interrupt_query ();
5608 }
5609
5610 /* Reinstall the usual SIGINT handlers, after the target has
5611 stopped. */
5612 static void
5613 async_cleanup_sigint_signal_handler (void *dummy)
5614 {
5615 signal (SIGINT, handle_sigint);
5616 }
5617
5618 /* Send ^C to target to halt it. Target will respond, and send us a
5619 packet. */
5620 static void (*ofunc) (int);
5621
5622 /* The command line interface's interrupt routine. This function is installed
5623 as a signal handler for SIGINT. The first time a user requests an
5624 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5625 response from the target (it didn't stop when the user requested it),
5626 we ask the user if he'd like to detach from the target. */
5627
5628 static void
5629 sync_remote_interrupt (int signo)
5630 {
5631 /* If this doesn't work, try more severe steps. */
5632 signal (signo, sync_remote_interrupt_twice);
5633
5634 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5635 }
5636
5637 /* The user typed ^C twice. */
5638
5639 static void
5640 sync_remote_interrupt_twice (int signo)
5641 {
5642 signal (signo, ofunc);
5643 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5644 signal (signo, sync_remote_interrupt);
5645 }
5646
5647 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5648 thread, all threads of a remote process, or all threads of all
5649 processes. */
5650
5651 static void
5652 remote_stop_ns (ptid_t ptid)
5653 {
5654 struct remote_state *rs = get_remote_state ();
5655 char *p = rs->buf;
5656 char *endp = rs->buf + get_remote_packet_size ();
5657
5658 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5659 remote_vcont_probe (rs);
5660
5661 if (!rs->supports_vCont.t)
5662 error (_("Remote server does not support stopping threads"));
5663
5664 if (ptid_equal (ptid, minus_one_ptid)
5665 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5666 p += xsnprintf (p, endp - p, "vCont;t");
5667 else
5668 {
5669 ptid_t nptid;
5670
5671 p += xsnprintf (p, endp - p, "vCont;t:");
5672
5673 if (ptid_is_pid (ptid))
5674 /* All (-1) threads of process. */
5675 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5676 else
5677 {
5678 /* Small optimization: if we already have a stop reply for
5679 this thread, no use in telling the stub we want this
5680 stopped. */
5681 if (peek_stop_reply (ptid))
5682 return;
5683
5684 nptid = ptid;
5685 }
5686
5687 write_ptid (p, endp, nptid);
5688 }
5689
5690 /* In non-stop, we get an immediate OK reply. The stop reply will
5691 come in asynchronously by notification. */
5692 putpkt (rs->buf);
5693 getpkt (&rs->buf, &rs->buf_size, 0);
5694 if (strcmp (rs->buf, "OK") != 0)
5695 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5696 }
5697
5698 /* All-stop version of target_interrupt. Sends a break or a ^C to
5699 interrupt the remote target. It is undefined which thread of which
5700 process reports the interrupt. */
5701
5702 static void
5703 remote_interrupt_as (void)
5704 {
5705 struct remote_state *rs = get_remote_state ();
5706
5707 rs->ctrlc_pending_p = 1;
5708
5709 /* If the inferior is stopped already, but the core didn't know
5710 about it yet, just ignore the request. The cached wait status
5711 will be collected in remote_wait. */
5712 if (rs->cached_wait_status)
5713 return;
5714
5715 /* Send interrupt_sequence to remote target. */
5716 send_interrupt_sequence ();
5717 }
5718
5719 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5720 the remote target. It is undefined which thread of which process
5721 reports the interrupt. Returns true if the packet is supported by
5722 the server, false otherwise. */
5723
5724 static int
5725 remote_interrupt_ns (void)
5726 {
5727 struct remote_state *rs = get_remote_state ();
5728 char *p = rs->buf;
5729 char *endp = rs->buf + get_remote_packet_size ();
5730
5731 xsnprintf (p, endp - p, "vCtrlC");
5732
5733 /* In non-stop, we get an immediate OK reply. The stop reply will
5734 come in asynchronously by notification. */
5735 putpkt (rs->buf);
5736 getpkt (&rs->buf, &rs->buf_size, 0);
5737
5738 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5739 {
5740 case PACKET_OK:
5741 break;
5742 case PACKET_UNKNOWN:
5743 return 0;
5744 case PACKET_ERROR:
5745 error (_("Interrupting target failed: %s"), rs->buf);
5746 }
5747
5748 return 1;
5749 }
5750
5751 /* Implement the to_stop function for the remote targets. */
5752
5753 static void
5754 remote_stop (struct target_ops *self, ptid_t ptid)
5755 {
5756 if (remote_debug)
5757 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5758
5759 if (target_is_non_stop_p ())
5760 remote_stop_ns (ptid);
5761 else
5762 {
5763 /* We don't currently have a way to transparently pause the
5764 remote target in all-stop mode. Interrupt it instead. */
5765 remote_interrupt_as ();
5766 }
5767 }
5768
5769 /* Implement the to_interrupt function for the remote targets. */
5770
5771 static void
5772 remote_interrupt (struct target_ops *self, ptid_t ptid)
5773 {
5774 if (remote_debug)
5775 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5776
5777 if (non_stop)
5778 {
5779 /* In non-stop mode, we always stop with no signal instead. */
5780 remote_stop_ns (ptid);
5781 }
5782 else
5783 {
5784 /* In all-stop, we emulate ^C-ing the remote target's
5785 terminal. */
5786 if (target_is_non_stop_p ())
5787 {
5788 if (!remote_interrupt_ns ())
5789 {
5790 /* No support for ^C-ing the remote target. Stop it
5791 (with no signal) instead. */
5792 remote_stop_ns (ptid);
5793 }
5794 }
5795 else
5796 remote_interrupt_as ();
5797 }
5798 }
5799
5800 /* Ask the user what to do when an interrupt is received. */
5801
5802 static void
5803 interrupt_query (void)
5804 {
5805 struct remote_state *rs = get_remote_state ();
5806 struct cleanup *old_chain;
5807
5808 old_chain = make_cleanup_restore_target_terminal ();
5809 target_terminal_ours ();
5810
5811 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5812 {
5813 if (query (_("The target is not responding to interrupt requests.\n"
5814 "Stop debugging it? ")))
5815 {
5816 remote_unpush_target ();
5817 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5818 }
5819 }
5820 else
5821 {
5822 if (query (_("Interrupted while waiting for the program.\n"
5823 "Give up waiting? ")))
5824 quit ();
5825 }
5826
5827 do_cleanups (old_chain);
5828 }
5829
5830 /* Enable/disable target terminal ownership. Most targets can use
5831 terminal groups to control terminal ownership. Remote targets are
5832 different in that explicit transfer of ownership to/from GDB/target
5833 is required. */
5834
5835 static void
5836 remote_terminal_inferior (struct target_ops *self)
5837 {
5838 if (!target_async_permitted)
5839 /* Nothing to do. */
5840 return;
5841
5842 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5843 idempotent. The event-loop GDB talking to an asynchronous target
5844 with a synchronous command calls this function from both
5845 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5846 transfer the terminal to the target when it shouldn't this guard
5847 can go away. */
5848 if (!remote_async_terminal_ours_p)
5849 return;
5850 delete_file_handler (input_fd);
5851 remote_async_terminal_ours_p = 0;
5852 async_initialize_sigint_signal_handler ();
5853 /* NOTE: At this point we could also register our selves as the
5854 recipient of all input. Any characters typed could then be
5855 passed on down to the target. */
5856 }
5857
5858 static void
5859 remote_terminal_ours (struct target_ops *self)
5860 {
5861 if (!target_async_permitted)
5862 /* Nothing to do. */
5863 return;
5864
5865 /* See FIXME in remote_terminal_inferior. */
5866 if (remote_async_terminal_ours_p)
5867 return;
5868 async_cleanup_sigint_signal_handler (NULL);
5869 add_file_handler (input_fd, stdin_event_handler, 0);
5870 remote_async_terminal_ours_p = 1;
5871 }
5872
5873 static void
5874 remote_console_output (char *msg)
5875 {
5876 char *p;
5877
5878 for (p = msg; p[0] && p[1]; p += 2)
5879 {
5880 char tb[2];
5881 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5882
5883 tb[0] = c;
5884 tb[1] = 0;
5885 fputs_unfiltered (tb, gdb_stdtarg);
5886 }
5887 gdb_flush (gdb_stdtarg);
5888 }
5889
5890 typedef struct cached_reg
5891 {
5892 int num;
5893 gdb_byte data[MAX_REGISTER_SIZE];
5894 } cached_reg_t;
5895
5896 DEF_VEC_O(cached_reg_t);
5897
5898 typedef struct stop_reply
5899 {
5900 struct notif_event base;
5901
5902 /* The identifier of the thread about this event */
5903 ptid_t ptid;
5904
5905 /* The remote state this event is associated with. When the remote
5906 connection, represented by a remote_state object, is closed,
5907 all the associated stop_reply events should be released. */
5908 struct remote_state *rs;
5909
5910 struct target_waitstatus ws;
5911
5912 /* Expedited registers. This makes remote debugging a bit more
5913 efficient for those targets that provide critical registers as
5914 part of their normal status mechanism (as another roundtrip to
5915 fetch them is avoided). */
5916 VEC(cached_reg_t) *regcache;
5917
5918 enum target_stop_reason stop_reason;
5919
5920 CORE_ADDR watch_data_address;
5921
5922 int core;
5923 } *stop_reply_p;
5924
5925 DECLARE_QUEUE_P (stop_reply_p);
5926 DEFINE_QUEUE_P (stop_reply_p);
5927 /* The list of already fetched and acknowledged stop events. This
5928 queue is used for notification Stop, and other notifications
5929 don't need queue for their events, because the notification events
5930 of Stop can't be consumed immediately, so that events should be
5931 queued first, and be consumed by remote_wait_{ns,as} one per
5932 time. Other notifications can consume their events immediately,
5933 so queue is not needed for them. */
5934 static QUEUE (stop_reply_p) *stop_reply_queue;
5935
5936 static void
5937 stop_reply_xfree (struct stop_reply *r)
5938 {
5939 notif_event_xfree ((struct notif_event *) r);
5940 }
5941
5942 /* Return the length of the stop reply queue. */
5943
5944 static int
5945 stop_reply_queue_length (void)
5946 {
5947 return QUEUE_length (stop_reply_p, stop_reply_queue);
5948 }
5949
5950 static void
5951 remote_notif_stop_parse (struct notif_client *self, char *buf,
5952 struct notif_event *event)
5953 {
5954 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5955 }
5956
5957 static void
5958 remote_notif_stop_ack (struct notif_client *self, char *buf,
5959 struct notif_event *event)
5960 {
5961 struct stop_reply *stop_reply = (struct stop_reply *) event;
5962
5963 /* acknowledge */
5964 putpkt ((char *) self->ack_command);
5965
5966 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5967 /* We got an unknown stop reply. */
5968 error (_("Unknown stop reply"));
5969
5970 push_stop_reply (stop_reply);
5971 }
5972
5973 static int
5974 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5975 {
5976 /* We can't get pending events in remote_notif_process for
5977 notification stop, and we have to do this in remote_wait_ns
5978 instead. If we fetch all queued events from stub, remote stub
5979 may exit and we have no chance to process them back in
5980 remote_wait_ns. */
5981 mark_async_event_handler (remote_async_inferior_event_token);
5982 return 0;
5983 }
5984
5985 static void
5986 stop_reply_dtr (struct notif_event *event)
5987 {
5988 struct stop_reply *r = (struct stop_reply *) event;
5989
5990 VEC_free (cached_reg_t, r->regcache);
5991 }
5992
5993 static struct notif_event *
5994 remote_notif_stop_alloc_reply (void)
5995 {
5996 /* We cast to a pointer to the "base class". */
5997 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5998
5999 r->dtr = stop_reply_dtr;
6000
6001 return r;
6002 }
6003
6004 /* A client of notification Stop. */
6005
6006 struct notif_client notif_client_stop =
6007 {
6008 "Stop",
6009 "vStopped",
6010 remote_notif_stop_parse,
6011 remote_notif_stop_ack,
6012 remote_notif_stop_can_get_pending_events,
6013 remote_notif_stop_alloc_reply,
6014 REMOTE_NOTIF_STOP,
6015 };
6016
6017 /* A parameter to pass data in and out. */
6018
6019 struct queue_iter_param
6020 {
6021 void *input;
6022 struct stop_reply *output;
6023 };
6024
6025 /* Determine if THREAD is a pending fork parent thread. ARG contains
6026 the pid of the process that owns the threads we want to check, or
6027 -1 if we want to check all threads. */
6028
6029 static int
6030 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6031 ptid_t thread_ptid)
6032 {
6033 if (ws->kind == TARGET_WAITKIND_FORKED
6034 || ws->kind == TARGET_WAITKIND_VFORKED)
6035 {
6036 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6037 return 1;
6038 }
6039
6040 return 0;
6041 }
6042
6043 /* Check whether EVENT is a fork event, and if it is, remove the
6044 fork child from the context list passed in DATA. */
6045
6046 static int
6047 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6048 QUEUE_ITER (stop_reply_p) *iter,
6049 stop_reply_p event,
6050 void *data)
6051 {
6052 struct queue_iter_param *param = (struct queue_iter_param *) data;
6053 struct threads_listing_context *context
6054 = (struct threads_listing_context *) param->input;
6055
6056 if (event->ws.kind == TARGET_WAITKIND_FORKED
6057 || event->ws.kind == TARGET_WAITKIND_VFORKED
6058 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6059 threads_listing_context_remove (&event->ws, context);
6060
6061 return 1;
6062 }
6063
6064 /* If CONTEXT contains any fork child threads that have not been
6065 reported yet, remove them from the CONTEXT list. If such a
6066 thread exists it is because we are stopped at a fork catchpoint
6067 and have not yet called follow_fork, which will set up the
6068 host-side data structures for the new process. */
6069
6070 static void
6071 remove_new_fork_children (struct threads_listing_context *context)
6072 {
6073 struct thread_info * thread;
6074 int pid = -1;
6075 struct notif_client *notif = &notif_client_stop;
6076 struct queue_iter_param param;
6077
6078 /* For any threads stopped at a fork event, remove the corresponding
6079 fork child threads from the CONTEXT list. */
6080 ALL_NON_EXITED_THREADS (thread)
6081 {
6082 struct target_waitstatus *ws = &thread->pending_follow;
6083
6084 if (is_pending_fork_parent (ws, pid, thread->ptid))
6085 {
6086 threads_listing_context_remove (ws, context);
6087 }
6088 }
6089
6090 /* Check for any pending fork events (not reported or processed yet)
6091 in process PID and remove those fork child threads from the
6092 CONTEXT list as well. */
6093 remote_notif_get_pending_events (notif);
6094 param.input = context;
6095 param.output = NULL;
6096 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6097 remove_child_of_pending_fork, &param);
6098 }
6099
6100 /* Remove stop replies in the queue if its pid is equal to the given
6101 inferior's pid. */
6102
6103 static int
6104 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6105 QUEUE_ITER (stop_reply_p) *iter,
6106 stop_reply_p event,
6107 void *data)
6108 {
6109 struct queue_iter_param *param = (struct queue_iter_param *) data;
6110 struct inferior *inf = (struct inferior *) param->input;
6111
6112 if (ptid_get_pid (event->ptid) == inf->pid)
6113 {
6114 stop_reply_xfree (event);
6115 QUEUE_remove_elem (stop_reply_p, q, iter);
6116 }
6117
6118 return 1;
6119 }
6120
6121 /* Discard all pending stop replies of inferior INF. */
6122
6123 static void
6124 discard_pending_stop_replies (struct inferior *inf)
6125 {
6126 int i;
6127 struct queue_iter_param param;
6128 struct stop_reply *reply;
6129 struct remote_state *rs = get_remote_state ();
6130 struct remote_notif_state *rns = rs->notif_state;
6131
6132 /* This function can be notified when an inferior exists. When the
6133 target is not remote, the notification state is NULL. */
6134 if (rs->remote_desc == NULL)
6135 return;
6136
6137 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6138
6139 /* Discard the in-flight notification. */
6140 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6141 {
6142 stop_reply_xfree (reply);
6143 rns->pending_event[notif_client_stop.id] = NULL;
6144 }
6145
6146 param.input = inf;
6147 param.output = NULL;
6148 /* Discard the stop replies we have already pulled with
6149 vStopped. */
6150 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6151 remove_stop_reply_for_inferior, &param);
6152 }
6153
6154 /* If its remote state is equal to the given remote state,
6155 remove EVENT from the stop reply queue. */
6156
6157 static int
6158 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6159 QUEUE_ITER (stop_reply_p) *iter,
6160 stop_reply_p event,
6161 void *data)
6162 {
6163 struct queue_iter_param *param = (struct queue_iter_param *) data;
6164 struct remote_state *rs = (struct remote_state *) param->input;
6165
6166 if (event->rs == rs)
6167 {
6168 stop_reply_xfree (event);
6169 QUEUE_remove_elem (stop_reply_p, q, iter);
6170 }
6171
6172 return 1;
6173 }
6174
6175 /* Discard the stop replies for RS in stop_reply_queue. */
6176
6177 static void
6178 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6179 {
6180 struct queue_iter_param param;
6181
6182 param.input = rs;
6183 param.output = NULL;
6184 /* Discard the stop replies we have already pulled with
6185 vStopped. */
6186 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6187 remove_stop_reply_of_remote_state, &param);
6188 }
6189
6190 /* A parameter to pass data in and out. */
6191
6192 static int
6193 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6194 QUEUE_ITER (stop_reply_p) *iter,
6195 stop_reply_p event,
6196 void *data)
6197 {
6198 struct queue_iter_param *param = (struct queue_iter_param *) data;
6199 ptid_t *ptid = (ptid_t *) param->input;
6200
6201 if (ptid_match (event->ptid, *ptid))
6202 {
6203 param->output = event;
6204 QUEUE_remove_elem (stop_reply_p, q, iter);
6205 return 0;
6206 }
6207
6208 return 1;
6209 }
6210
6211 /* Remove the first reply in 'stop_reply_queue' which matches
6212 PTID. */
6213
6214 static struct stop_reply *
6215 remote_notif_remove_queued_reply (ptid_t ptid)
6216 {
6217 struct queue_iter_param param;
6218
6219 param.input = &ptid;
6220 param.output = NULL;
6221
6222 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6223 remote_notif_remove_once_on_match, &param);
6224 if (notif_debug)
6225 fprintf_unfiltered (gdb_stdlog,
6226 "notif: discard queued event: 'Stop' in %s\n",
6227 target_pid_to_str (ptid));
6228
6229 return param.output;
6230 }
6231
6232 /* Look for a queued stop reply belonging to PTID. If one is found,
6233 remove it from the queue, and return it. Returns NULL if none is
6234 found. If there are still queued events left to process, tell the
6235 event loop to get back to target_wait soon. */
6236
6237 static struct stop_reply *
6238 queued_stop_reply (ptid_t ptid)
6239 {
6240 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6241
6242 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6243 /* There's still at least an event left. */
6244 mark_async_event_handler (remote_async_inferior_event_token);
6245
6246 return r;
6247 }
6248
6249 /* Push a fully parsed stop reply in the stop reply queue. Since we
6250 know that we now have at least one queued event left to pass to the
6251 core side, tell the event loop to get back to target_wait soon. */
6252
6253 static void
6254 push_stop_reply (struct stop_reply *new_event)
6255 {
6256 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6257
6258 if (notif_debug)
6259 fprintf_unfiltered (gdb_stdlog,
6260 "notif: push 'Stop' %s to queue %d\n",
6261 target_pid_to_str (new_event->ptid),
6262 QUEUE_length (stop_reply_p,
6263 stop_reply_queue));
6264
6265 mark_async_event_handler (remote_async_inferior_event_token);
6266 }
6267
6268 static int
6269 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6270 QUEUE_ITER (stop_reply_p) *iter,
6271 struct stop_reply *event,
6272 void *data)
6273 {
6274 ptid_t *ptid = (ptid_t *) data;
6275
6276 return !(ptid_equal (*ptid, event->ptid)
6277 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6278 }
6279
6280 /* Returns true if we have a stop reply for PTID. */
6281
6282 static int
6283 peek_stop_reply (ptid_t ptid)
6284 {
6285 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6286 stop_reply_match_ptid_and_ws, &ptid);
6287 }
6288
6289 /* Skip PACKET until the next semi-colon (or end of string). */
6290
6291 static char *
6292 skip_to_semicolon (char *p)
6293 {
6294 while (*p != '\0' && *p != ';')
6295 p++;
6296 return p;
6297 }
6298
6299 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6300 starting with P and ending with PEND matches PREFIX. */
6301
6302 static int
6303 strprefix (const char *p, const char *pend, const char *prefix)
6304 {
6305 for ( ; p < pend; p++, prefix++)
6306 if (*p != *prefix)
6307 return 0;
6308 return *prefix == '\0';
6309 }
6310
6311 /* Parse the stop reply in BUF. Either the function succeeds, and the
6312 result is stored in EVENT, or throws an error. */
6313
6314 static void
6315 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6316 {
6317 struct remote_arch_state *rsa = get_remote_arch_state ();
6318 ULONGEST addr;
6319 char *p;
6320 int skipregs = 0;
6321
6322 event->ptid = null_ptid;
6323 event->rs = get_remote_state ();
6324 event->ws.kind = TARGET_WAITKIND_IGNORE;
6325 event->ws.value.integer = 0;
6326 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6327 event->regcache = NULL;
6328 event->core = -1;
6329
6330 switch (buf[0])
6331 {
6332 case 'T': /* Status with PC, SP, FP, ... */
6333 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6334 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6335 ss = signal number
6336 n... = register number
6337 r... = register contents
6338 */
6339
6340 p = &buf[3]; /* after Txx */
6341 while (*p)
6342 {
6343 char *p1;
6344 int fieldsize;
6345
6346 p1 = strchr (p, ':');
6347 if (p1 == NULL)
6348 error (_("Malformed packet(a) (missing colon): %s\n\
6349 Packet: '%s'\n"),
6350 p, buf);
6351 if (p == p1)
6352 error (_("Malformed packet(a) (missing register number): %s\n\
6353 Packet: '%s'\n"),
6354 p, buf);
6355
6356 /* Some "registers" are actually extended stop information.
6357 Note if you're adding a new entry here: GDB 7.9 and
6358 earlier assume that all register "numbers" that start
6359 with an hex digit are real register numbers. Make sure
6360 the server only sends such a packet if it knows the
6361 client understands it. */
6362
6363 if (strprefix (p, p1, "thread"))
6364 event->ptid = read_ptid (++p1, &p);
6365 else if (strprefix (p, p1, "watch")
6366 || strprefix (p, p1, "rwatch")
6367 || strprefix (p, p1, "awatch"))
6368 {
6369 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6370 p = unpack_varlen_hex (++p1, &addr);
6371 event->watch_data_address = (CORE_ADDR) addr;
6372 }
6373 else if (strprefix (p, p1, "swbreak"))
6374 {
6375 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6376
6377 /* Make sure the stub doesn't forget to indicate support
6378 with qSupported. */
6379 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6380 error (_("Unexpected swbreak stop reason"));
6381
6382 /* The value part is documented as "must be empty",
6383 though we ignore it, in case we ever decide to make
6384 use of it in a backward compatible way. */
6385 p = skip_to_semicolon (p1 + 1);
6386 }
6387 else if (strprefix (p, p1, "hwbreak"))
6388 {
6389 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6390
6391 /* Make sure the stub doesn't forget to indicate support
6392 with qSupported. */
6393 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6394 error (_("Unexpected hwbreak stop reason"));
6395
6396 /* See above. */
6397 p = skip_to_semicolon (p1 + 1);
6398 }
6399 else if (strprefix (p, p1, "library"))
6400 {
6401 event->ws.kind = TARGET_WAITKIND_LOADED;
6402 p = skip_to_semicolon (p1 + 1);
6403 }
6404 else if (strprefix (p, p1, "replaylog"))
6405 {
6406 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6407 /* p1 will indicate "begin" or "end", but it makes
6408 no difference for now, so ignore it. */
6409 p = skip_to_semicolon (p1 + 1);
6410 }
6411 else if (strprefix (p, p1, "core"))
6412 {
6413 ULONGEST c;
6414
6415 p = unpack_varlen_hex (++p1, &c);
6416 event->core = c;
6417 }
6418 else if (strprefix (p, p1, "fork"))
6419 {
6420 event->ws.value.related_pid = read_ptid (++p1, &p);
6421 event->ws.kind = TARGET_WAITKIND_FORKED;
6422 }
6423 else if (strprefix (p, p1, "vfork"))
6424 {
6425 event->ws.value.related_pid = read_ptid (++p1, &p);
6426 event->ws.kind = TARGET_WAITKIND_VFORKED;
6427 }
6428 else if (strprefix (p, p1, "vforkdone"))
6429 {
6430 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6431 p = skip_to_semicolon (p1 + 1);
6432 }
6433 else if (strprefix (p, p1, "exec"))
6434 {
6435 ULONGEST ignored;
6436 char pathname[PATH_MAX];
6437 int pathlen;
6438
6439 /* Determine the length of the execd pathname. */
6440 p = unpack_varlen_hex (++p1, &ignored);
6441 pathlen = (p - p1) / 2;
6442
6443 /* Save the pathname for event reporting and for
6444 the next run command. */
6445 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6446 pathname[pathlen] = '\0';
6447
6448 /* This is freed during event handling. */
6449 event->ws.value.execd_pathname = xstrdup (pathname);
6450 event->ws.kind = TARGET_WAITKIND_EXECD;
6451
6452 /* Skip the registers included in this packet, since
6453 they may be for an architecture different from the
6454 one used by the original program. */
6455 skipregs = 1;
6456 }
6457 else if (strprefix (p, p1, "create"))
6458 {
6459 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6460 p = skip_to_semicolon (p1 + 1);
6461 }
6462 else
6463 {
6464 ULONGEST pnum;
6465 char *p_temp;
6466
6467 if (skipregs)
6468 {
6469 p = skip_to_semicolon (p1 + 1);
6470 p++;
6471 continue;
6472 }
6473
6474 /* Maybe a real ``P'' register number. */
6475 p_temp = unpack_varlen_hex (p, &pnum);
6476 /* If the first invalid character is the colon, we got a
6477 register number. Otherwise, it's an unknown stop
6478 reason. */
6479 if (p_temp == p1)
6480 {
6481 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6482 cached_reg_t cached_reg;
6483
6484 if (reg == NULL)
6485 error (_("Remote sent bad register number %s: %s\n\
6486 Packet: '%s'\n"),
6487 hex_string (pnum), p, buf);
6488
6489 cached_reg.num = reg->regnum;
6490
6491 p = p1 + 1;
6492 fieldsize = hex2bin (p, cached_reg.data,
6493 register_size (target_gdbarch (),
6494 reg->regnum));
6495 p += 2 * fieldsize;
6496 if (fieldsize < register_size (target_gdbarch (),
6497 reg->regnum))
6498 warning (_("Remote reply is too short: %s"), buf);
6499
6500 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6501 }
6502 else
6503 {
6504 /* Not a number. Silently skip unknown optional
6505 info. */
6506 p = skip_to_semicolon (p1 + 1);
6507 }
6508 }
6509
6510 if (*p != ';')
6511 error (_("Remote register badly formatted: %s\nhere: %s"),
6512 buf, p);
6513 ++p;
6514 }
6515
6516 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6517 break;
6518
6519 /* fall through */
6520 case 'S': /* Old style status, just signal only. */
6521 {
6522 int sig;
6523
6524 event->ws.kind = TARGET_WAITKIND_STOPPED;
6525 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6526 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6527 event->ws.value.sig = (enum gdb_signal) sig;
6528 else
6529 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6530 }
6531 break;
6532 case 'w': /* Thread exited. */
6533 {
6534 char *p;
6535 ULONGEST value;
6536
6537 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6538 p = unpack_varlen_hex (&buf[1], &value);
6539 event->ws.value.integer = value;
6540 if (*p != ';')
6541 error (_("stop reply packet badly formatted: %s"), buf);
6542 event->ptid = read_ptid (++p, &p);
6543 break;
6544 }
6545 case 'W': /* Target exited. */
6546 case 'X':
6547 {
6548 char *p;
6549 int pid;
6550 ULONGEST value;
6551
6552 /* GDB used to accept only 2 hex chars here. Stubs should
6553 only send more if they detect GDB supports multi-process
6554 support. */
6555 p = unpack_varlen_hex (&buf[1], &value);
6556
6557 if (buf[0] == 'W')
6558 {
6559 /* The remote process exited. */
6560 event->ws.kind = TARGET_WAITKIND_EXITED;
6561 event->ws.value.integer = value;
6562 }
6563 else
6564 {
6565 /* The remote process exited with a signal. */
6566 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6567 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6568 event->ws.value.sig = (enum gdb_signal) value;
6569 else
6570 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6571 }
6572
6573 /* If no process is specified, assume inferior_ptid. */
6574 pid = ptid_get_pid (inferior_ptid);
6575 if (*p == '\0')
6576 ;
6577 else if (*p == ';')
6578 {
6579 p++;
6580
6581 if (*p == '\0')
6582 ;
6583 else if (startswith (p, "process:"))
6584 {
6585 ULONGEST upid;
6586
6587 p += sizeof ("process:") - 1;
6588 unpack_varlen_hex (p, &upid);
6589 pid = upid;
6590 }
6591 else
6592 error (_("unknown stop reply packet: %s"), buf);
6593 }
6594 else
6595 error (_("unknown stop reply packet: %s"), buf);
6596 event->ptid = pid_to_ptid (pid);
6597 }
6598 break;
6599 }
6600
6601 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6602 error (_("No process or thread specified in stop reply: %s"), buf);
6603 }
6604
6605 /* When the stub wants to tell GDB about a new notification reply, it
6606 sends a notification (%Stop, for example). Those can come it at
6607 any time, hence, we have to make sure that any pending
6608 putpkt/getpkt sequence we're making is finished, before querying
6609 the stub for more events with the corresponding ack command
6610 (vStopped, for example). E.g., if we started a vStopped sequence
6611 immediately upon receiving the notification, something like this
6612 could happen:
6613
6614 1.1) --> Hg 1
6615 1.2) <-- OK
6616 1.3) --> g
6617 1.4) <-- %Stop
6618 1.5) --> vStopped
6619 1.6) <-- (registers reply to step #1.3)
6620
6621 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6622 query.
6623
6624 To solve this, whenever we parse a %Stop notification successfully,
6625 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6626 doing whatever we were doing:
6627
6628 2.1) --> Hg 1
6629 2.2) <-- OK
6630 2.3) --> g
6631 2.4) <-- %Stop
6632 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6633 2.5) <-- (registers reply to step #2.3)
6634
6635 Eventualy after step #2.5, we return to the event loop, which
6636 notices there's an event on the
6637 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6638 associated callback --- the function below. At this point, we're
6639 always safe to start a vStopped sequence. :
6640
6641 2.6) --> vStopped
6642 2.7) <-- T05 thread:2
6643 2.8) --> vStopped
6644 2.9) --> OK
6645 */
6646
6647 void
6648 remote_notif_get_pending_events (struct notif_client *nc)
6649 {
6650 struct remote_state *rs = get_remote_state ();
6651
6652 if (rs->notif_state->pending_event[nc->id] != NULL)
6653 {
6654 if (notif_debug)
6655 fprintf_unfiltered (gdb_stdlog,
6656 "notif: process: '%s' ack pending event\n",
6657 nc->name);
6658
6659 /* acknowledge */
6660 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6661 rs->notif_state->pending_event[nc->id] = NULL;
6662
6663 while (1)
6664 {
6665 getpkt (&rs->buf, &rs->buf_size, 0);
6666 if (strcmp (rs->buf, "OK") == 0)
6667 break;
6668 else
6669 remote_notif_ack (nc, rs->buf);
6670 }
6671 }
6672 else
6673 {
6674 if (notif_debug)
6675 fprintf_unfiltered (gdb_stdlog,
6676 "notif: process: '%s' no pending reply\n",
6677 nc->name);
6678 }
6679 }
6680
6681 /* Called when it is decided that STOP_REPLY holds the info of the
6682 event that is to be returned to the core. This function always
6683 destroys STOP_REPLY. */
6684
6685 static ptid_t
6686 process_stop_reply (struct stop_reply *stop_reply,
6687 struct target_waitstatus *status)
6688 {
6689 ptid_t ptid;
6690
6691 *status = stop_reply->ws;
6692 ptid = stop_reply->ptid;
6693
6694 /* If no thread/process was reported by the stub, assume the current
6695 inferior. */
6696 if (ptid_equal (ptid, null_ptid))
6697 ptid = inferior_ptid;
6698
6699 if (status->kind != TARGET_WAITKIND_EXITED
6700 && status->kind != TARGET_WAITKIND_SIGNALLED)
6701 {
6702 struct remote_state *rs = get_remote_state ();
6703 struct private_thread_info *remote_thr;
6704
6705 /* Expedited registers. */
6706 if (stop_reply->regcache)
6707 {
6708 struct regcache *regcache
6709 = get_thread_arch_regcache (ptid, target_gdbarch ());
6710 cached_reg_t *reg;
6711 int ix;
6712
6713 for (ix = 0;
6714 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6715 ix++)
6716 regcache_raw_supply (regcache, reg->num, reg->data);
6717 VEC_free (cached_reg_t, stop_reply->regcache);
6718 }
6719
6720 remote_notice_new_inferior (ptid, 0);
6721 remote_thr = demand_private_info (ptid);
6722 remote_thr->core = stop_reply->core;
6723 remote_thr->stop_reason = stop_reply->stop_reason;
6724 remote_thr->watch_data_address = stop_reply->watch_data_address;
6725 }
6726
6727 stop_reply_xfree (stop_reply);
6728 return ptid;
6729 }
6730
6731 /* The non-stop mode version of target_wait. */
6732
6733 static ptid_t
6734 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6735 {
6736 struct remote_state *rs = get_remote_state ();
6737 struct stop_reply *stop_reply;
6738 int ret;
6739 int is_notif = 0;
6740
6741 /* If in non-stop mode, get out of getpkt even if a
6742 notification is received. */
6743
6744 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6745 0 /* forever */, &is_notif);
6746 while (1)
6747 {
6748 if (ret != -1 && !is_notif)
6749 switch (rs->buf[0])
6750 {
6751 case 'E': /* Error of some sort. */
6752 /* We're out of sync with the target now. Did it continue
6753 or not? We can't tell which thread it was in non-stop,
6754 so just ignore this. */
6755 warning (_("Remote failure reply: %s"), rs->buf);
6756 break;
6757 case 'O': /* Console output. */
6758 remote_console_output (rs->buf + 1);
6759 break;
6760 default:
6761 warning (_("Invalid remote reply: %s"), rs->buf);
6762 break;
6763 }
6764
6765 /* Acknowledge a pending stop reply that may have arrived in the
6766 mean time. */
6767 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6768 remote_notif_get_pending_events (&notif_client_stop);
6769
6770 /* If indeed we noticed a stop reply, we're done. */
6771 stop_reply = queued_stop_reply (ptid);
6772 if (stop_reply != NULL)
6773 return process_stop_reply (stop_reply, status);
6774
6775 /* Still no event. If we're just polling for an event, then
6776 return to the event loop. */
6777 if (options & TARGET_WNOHANG)
6778 {
6779 status->kind = TARGET_WAITKIND_IGNORE;
6780 return minus_one_ptid;
6781 }
6782
6783 /* Otherwise do a blocking wait. */
6784 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6785 1 /* forever */, &is_notif);
6786 }
6787 }
6788
6789 /* Wait until the remote machine stops, then return, storing status in
6790 STATUS just as `wait' would. */
6791
6792 static ptid_t
6793 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6794 {
6795 struct remote_state *rs = get_remote_state ();
6796 ptid_t event_ptid = null_ptid;
6797 char *buf;
6798 struct stop_reply *stop_reply;
6799
6800 again:
6801
6802 status->kind = TARGET_WAITKIND_IGNORE;
6803 status->value.integer = 0;
6804
6805 stop_reply = queued_stop_reply (ptid);
6806 if (stop_reply != NULL)
6807 return process_stop_reply (stop_reply, status);
6808
6809 if (rs->cached_wait_status)
6810 /* Use the cached wait status, but only once. */
6811 rs->cached_wait_status = 0;
6812 else
6813 {
6814 int ret;
6815 int is_notif;
6816 int forever = ((options & TARGET_WNOHANG) == 0
6817 && wait_forever_enabled_p);
6818
6819 if (!rs->waiting_for_stop_reply)
6820 {
6821 status->kind = TARGET_WAITKIND_NO_RESUMED;
6822 return minus_one_ptid;
6823 }
6824
6825 if (!target_is_async_p ())
6826 {
6827 ofunc = signal (SIGINT, sync_remote_interrupt);
6828 /* If the user hit C-c before this packet, or between packets,
6829 pretend that it was hit right here. */
6830 if (check_quit_flag ())
6831 {
6832 clear_quit_flag ();
6833 sync_remote_interrupt (SIGINT);
6834 }
6835 }
6836
6837 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6838 _never_ wait for ever -> test on target_is_async_p().
6839 However, before we do that we need to ensure that the caller
6840 knows how to take the target into/out of async mode. */
6841 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6842 forever, &is_notif);
6843
6844 if (!target_is_async_p ())
6845 signal (SIGINT, ofunc);
6846
6847 /* GDB gets a notification. Return to core as this event is
6848 not interesting. */
6849 if (ret != -1 && is_notif)
6850 return minus_one_ptid;
6851
6852 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6853 return minus_one_ptid;
6854 }
6855
6856 buf = rs->buf;
6857
6858 /* Assume that the target has acknowledged Ctrl-C unless we receive
6859 an 'F' or 'O' packet. */
6860 if (buf[0] != 'F' && buf[0] != 'O')
6861 rs->ctrlc_pending_p = 0;
6862
6863 switch (buf[0])
6864 {
6865 case 'E': /* Error of some sort. */
6866 /* We're out of sync with the target now. Did it continue or
6867 not? Not is more likely, so report a stop. */
6868 rs->waiting_for_stop_reply = 0;
6869
6870 warning (_("Remote failure reply: %s"), buf);
6871 status->kind = TARGET_WAITKIND_STOPPED;
6872 status->value.sig = GDB_SIGNAL_0;
6873 break;
6874 case 'F': /* File-I/O request. */
6875 remote_fileio_request (buf, rs->ctrlc_pending_p);
6876 rs->ctrlc_pending_p = 0;
6877 break;
6878 case 'T': case 'S': case 'X': case 'W':
6879 {
6880 struct stop_reply *stop_reply;
6881
6882 /* There is a stop reply to handle. */
6883 rs->waiting_for_stop_reply = 0;
6884
6885 stop_reply
6886 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6887 rs->buf);
6888
6889 event_ptid = process_stop_reply (stop_reply, status);
6890 break;
6891 }
6892 case 'O': /* Console output. */
6893 remote_console_output (buf + 1);
6894 break;
6895 case '\0':
6896 if (rs->last_sent_signal != GDB_SIGNAL_0)
6897 {
6898 /* Zero length reply means that we tried 'S' or 'C' and the
6899 remote system doesn't support it. */
6900 target_terminal_ours_for_output ();
6901 printf_filtered
6902 ("Can't send signals to this remote system. %s not sent.\n",
6903 gdb_signal_to_name (rs->last_sent_signal));
6904 rs->last_sent_signal = GDB_SIGNAL_0;
6905 target_terminal_inferior ();
6906
6907 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6908 putpkt ((char *) buf);
6909 break;
6910 }
6911 /* else fallthrough */
6912 default:
6913 warning (_("Invalid remote reply: %s"), buf);
6914 break;
6915 }
6916
6917 if (status->kind == TARGET_WAITKIND_IGNORE)
6918 {
6919 /* Nothing interesting happened. If we're doing a non-blocking
6920 poll, we're done. Otherwise, go back to waiting. */
6921 if (options & TARGET_WNOHANG)
6922 return minus_one_ptid;
6923 else
6924 goto again;
6925 }
6926 else if (status->kind != TARGET_WAITKIND_EXITED
6927 && status->kind != TARGET_WAITKIND_SIGNALLED)
6928 {
6929 if (!ptid_equal (event_ptid, null_ptid))
6930 record_currthread (rs, event_ptid);
6931 else
6932 event_ptid = inferior_ptid;
6933 }
6934 else
6935 /* A process exit. Invalidate our notion of current thread. */
6936 record_currthread (rs, minus_one_ptid);
6937
6938 return event_ptid;
6939 }
6940
6941 /* Wait until the remote machine stops, then return, storing status in
6942 STATUS just as `wait' would. */
6943
6944 static ptid_t
6945 remote_wait (struct target_ops *ops,
6946 ptid_t ptid, struct target_waitstatus *status, int options)
6947 {
6948 ptid_t event_ptid;
6949
6950 if (target_is_non_stop_p ())
6951 event_ptid = remote_wait_ns (ptid, status, options);
6952 else
6953 event_ptid = remote_wait_as (ptid, status, options);
6954
6955 if (target_is_async_p ())
6956 {
6957 /* If there are are events left in the queue tell the event loop
6958 to return here. */
6959 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6960 mark_async_event_handler (remote_async_inferior_event_token);
6961 }
6962
6963 return event_ptid;
6964 }
6965
6966 /* Fetch a single register using a 'p' packet. */
6967
6968 static int
6969 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6970 {
6971 struct remote_state *rs = get_remote_state ();
6972 char *buf, *p;
6973 char regp[MAX_REGISTER_SIZE];
6974 int i;
6975
6976 if (packet_support (PACKET_p) == PACKET_DISABLE)
6977 return 0;
6978
6979 if (reg->pnum == -1)
6980 return 0;
6981
6982 p = rs->buf;
6983 *p++ = 'p';
6984 p += hexnumstr (p, reg->pnum);
6985 *p++ = '\0';
6986 putpkt (rs->buf);
6987 getpkt (&rs->buf, &rs->buf_size, 0);
6988
6989 buf = rs->buf;
6990
6991 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6992 {
6993 case PACKET_OK:
6994 break;
6995 case PACKET_UNKNOWN:
6996 return 0;
6997 case PACKET_ERROR:
6998 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6999 gdbarch_register_name (get_regcache_arch (regcache),
7000 reg->regnum),
7001 buf);
7002 }
7003
7004 /* If this register is unfetchable, tell the regcache. */
7005 if (buf[0] == 'x')
7006 {
7007 regcache_raw_supply (regcache, reg->regnum, NULL);
7008 return 1;
7009 }
7010
7011 /* Otherwise, parse and supply the value. */
7012 p = buf;
7013 i = 0;
7014 while (p[0] != 0)
7015 {
7016 if (p[1] == 0)
7017 error (_("fetch_register_using_p: early buf termination"));
7018
7019 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7020 p += 2;
7021 }
7022 regcache_raw_supply (regcache, reg->regnum, regp);
7023 return 1;
7024 }
7025
7026 /* Fetch the registers included in the target's 'g' packet. */
7027
7028 static int
7029 send_g_packet (void)
7030 {
7031 struct remote_state *rs = get_remote_state ();
7032 int buf_len;
7033
7034 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7035 remote_send (&rs->buf, &rs->buf_size);
7036
7037 /* We can get out of synch in various cases. If the first character
7038 in the buffer is not a hex character, assume that has happened
7039 and try to fetch another packet to read. */
7040 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7041 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7042 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7043 && rs->buf[0] != 'x') /* New: unavailable register value. */
7044 {
7045 if (remote_debug)
7046 fprintf_unfiltered (gdb_stdlog,
7047 "Bad register packet; fetching a new packet\n");
7048 getpkt (&rs->buf, &rs->buf_size, 0);
7049 }
7050
7051 buf_len = strlen (rs->buf);
7052
7053 /* Sanity check the received packet. */
7054 if (buf_len % 2 != 0)
7055 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7056
7057 return buf_len / 2;
7058 }
7059
7060 static void
7061 process_g_packet (struct regcache *regcache)
7062 {
7063 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7064 struct remote_state *rs = get_remote_state ();
7065 struct remote_arch_state *rsa = get_remote_arch_state ();
7066 int i, buf_len;
7067 char *p;
7068 char *regs;
7069
7070 buf_len = strlen (rs->buf);
7071
7072 /* Further sanity checks, with knowledge of the architecture. */
7073 if (buf_len > 2 * rsa->sizeof_g_packet)
7074 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7075
7076 /* Save the size of the packet sent to us by the target. It is used
7077 as a heuristic when determining the max size of packets that the
7078 target can safely receive. */
7079 if (rsa->actual_register_packet_size == 0)
7080 rsa->actual_register_packet_size = buf_len;
7081
7082 /* If this is smaller than we guessed the 'g' packet would be,
7083 update our records. A 'g' reply that doesn't include a register's
7084 value implies either that the register is not available, or that
7085 the 'p' packet must be used. */
7086 if (buf_len < 2 * rsa->sizeof_g_packet)
7087 {
7088 rsa->sizeof_g_packet = buf_len / 2;
7089
7090 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7091 {
7092 if (rsa->regs[i].pnum == -1)
7093 continue;
7094
7095 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7096 rsa->regs[i].in_g_packet = 0;
7097 else
7098 rsa->regs[i].in_g_packet = 1;
7099 }
7100 }
7101
7102 regs = (char *) alloca (rsa->sizeof_g_packet);
7103
7104 /* Unimplemented registers read as all bits zero. */
7105 memset (regs, 0, rsa->sizeof_g_packet);
7106
7107 /* Reply describes registers byte by byte, each byte encoded as two
7108 hex characters. Suck them all up, then supply them to the
7109 register cacheing/storage mechanism. */
7110
7111 p = rs->buf;
7112 for (i = 0; i < rsa->sizeof_g_packet; i++)
7113 {
7114 if (p[0] == 0 || p[1] == 0)
7115 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7116 internal_error (__FILE__, __LINE__,
7117 _("unexpected end of 'g' packet reply"));
7118
7119 if (p[0] == 'x' && p[1] == 'x')
7120 regs[i] = 0; /* 'x' */
7121 else
7122 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7123 p += 2;
7124 }
7125
7126 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7127 {
7128 struct packet_reg *r = &rsa->regs[i];
7129
7130 if (r->in_g_packet)
7131 {
7132 if (r->offset * 2 >= strlen (rs->buf))
7133 /* This shouldn't happen - we adjusted in_g_packet above. */
7134 internal_error (__FILE__, __LINE__,
7135 _("unexpected end of 'g' packet reply"));
7136 else if (rs->buf[r->offset * 2] == 'x')
7137 {
7138 gdb_assert (r->offset * 2 < strlen (rs->buf));
7139 /* The register isn't available, mark it as such (at
7140 the same time setting the value to zero). */
7141 regcache_raw_supply (regcache, r->regnum, NULL);
7142 }
7143 else
7144 regcache_raw_supply (regcache, r->regnum,
7145 regs + r->offset);
7146 }
7147 }
7148 }
7149
7150 static void
7151 fetch_registers_using_g (struct regcache *regcache)
7152 {
7153 send_g_packet ();
7154 process_g_packet (regcache);
7155 }
7156
7157 /* Make the remote selected traceframe match GDB's selected
7158 traceframe. */
7159
7160 static void
7161 set_remote_traceframe (void)
7162 {
7163 int newnum;
7164 struct remote_state *rs = get_remote_state ();
7165
7166 if (rs->remote_traceframe_number == get_traceframe_number ())
7167 return;
7168
7169 /* Avoid recursion, remote_trace_find calls us again. */
7170 rs->remote_traceframe_number = get_traceframe_number ();
7171
7172 newnum = target_trace_find (tfind_number,
7173 get_traceframe_number (), 0, 0, NULL);
7174
7175 /* Should not happen. If it does, all bets are off. */
7176 if (newnum != get_traceframe_number ())
7177 warning (_("could not set remote traceframe"));
7178 }
7179
7180 static void
7181 remote_fetch_registers (struct target_ops *ops,
7182 struct regcache *regcache, int regnum)
7183 {
7184 struct remote_arch_state *rsa = get_remote_arch_state ();
7185 int i;
7186
7187 set_remote_traceframe ();
7188 set_general_thread (inferior_ptid);
7189
7190 if (regnum >= 0)
7191 {
7192 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7193
7194 gdb_assert (reg != NULL);
7195
7196 /* If this register might be in the 'g' packet, try that first -
7197 we are likely to read more than one register. If this is the
7198 first 'g' packet, we might be overly optimistic about its
7199 contents, so fall back to 'p'. */
7200 if (reg->in_g_packet)
7201 {
7202 fetch_registers_using_g (regcache);
7203 if (reg->in_g_packet)
7204 return;
7205 }
7206
7207 if (fetch_register_using_p (regcache, reg))
7208 return;
7209
7210 /* This register is not available. */
7211 regcache_raw_supply (regcache, reg->regnum, NULL);
7212
7213 return;
7214 }
7215
7216 fetch_registers_using_g (regcache);
7217
7218 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7219 if (!rsa->regs[i].in_g_packet)
7220 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7221 {
7222 /* This register is not available. */
7223 regcache_raw_supply (regcache, i, NULL);
7224 }
7225 }
7226
7227 /* Prepare to store registers. Since we may send them all (using a
7228 'G' request), we have to read out the ones we don't want to change
7229 first. */
7230
7231 static void
7232 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7233 {
7234 struct remote_arch_state *rsa = get_remote_arch_state ();
7235 int i;
7236 gdb_byte buf[MAX_REGISTER_SIZE];
7237
7238 /* Make sure the entire registers array is valid. */
7239 switch (packet_support (PACKET_P))
7240 {
7241 case PACKET_DISABLE:
7242 case PACKET_SUPPORT_UNKNOWN:
7243 /* Make sure all the necessary registers are cached. */
7244 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7245 if (rsa->regs[i].in_g_packet)
7246 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7247 break;
7248 case PACKET_ENABLE:
7249 break;
7250 }
7251 }
7252
7253 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7254 packet was not recognized. */
7255
7256 static int
7257 store_register_using_P (const struct regcache *regcache,
7258 struct packet_reg *reg)
7259 {
7260 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7261 struct remote_state *rs = get_remote_state ();
7262 /* Try storing a single register. */
7263 char *buf = rs->buf;
7264 gdb_byte regp[MAX_REGISTER_SIZE];
7265 char *p;
7266
7267 if (packet_support (PACKET_P) == PACKET_DISABLE)
7268 return 0;
7269
7270 if (reg->pnum == -1)
7271 return 0;
7272
7273 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7274 p = buf + strlen (buf);
7275 regcache_raw_collect (regcache, reg->regnum, regp);
7276 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7277 putpkt (rs->buf);
7278 getpkt (&rs->buf, &rs->buf_size, 0);
7279
7280 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7281 {
7282 case PACKET_OK:
7283 return 1;
7284 case PACKET_ERROR:
7285 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7286 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7287 case PACKET_UNKNOWN:
7288 return 0;
7289 default:
7290 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7291 }
7292 }
7293
7294 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7295 contents of the register cache buffer. FIXME: ignores errors. */
7296
7297 static void
7298 store_registers_using_G (const struct regcache *regcache)
7299 {
7300 struct remote_state *rs = get_remote_state ();
7301 struct remote_arch_state *rsa = get_remote_arch_state ();
7302 gdb_byte *regs;
7303 char *p;
7304
7305 /* Extract all the registers in the regcache copying them into a
7306 local buffer. */
7307 {
7308 int i;
7309
7310 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7311 memset (regs, 0, rsa->sizeof_g_packet);
7312 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7313 {
7314 struct packet_reg *r = &rsa->regs[i];
7315
7316 if (r->in_g_packet)
7317 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7318 }
7319 }
7320
7321 /* Command describes registers byte by byte,
7322 each byte encoded as two hex characters. */
7323 p = rs->buf;
7324 *p++ = 'G';
7325 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7326 updated. */
7327 bin2hex (regs, p, rsa->sizeof_g_packet);
7328 putpkt (rs->buf);
7329 getpkt (&rs->buf, &rs->buf_size, 0);
7330 if (packet_check_result (rs->buf) == PACKET_ERROR)
7331 error (_("Could not write registers; remote failure reply '%s'"),
7332 rs->buf);
7333 }
7334
7335 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7336 of the register cache buffer. FIXME: ignores errors. */
7337
7338 static void
7339 remote_store_registers (struct target_ops *ops,
7340 struct regcache *regcache, int regnum)
7341 {
7342 struct remote_arch_state *rsa = get_remote_arch_state ();
7343 int i;
7344
7345 set_remote_traceframe ();
7346 set_general_thread (inferior_ptid);
7347
7348 if (regnum >= 0)
7349 {
7350 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7351
7352 gdb_assert (reg != NULL);
7353
7354 /* Always prefer to store registers using the 'P' packet if
7355 possible; we often change only a small number of registers.
7356 Sometimes we change a larger number; we'd need help from a
7357 higher layer to know to use 'G'. */
7358 if (store_register_using_P (regcache, reg))
7359 return;
7360
7361 /* For now, don't complain if we have no way to write the
7362 register. GDB loses track of unavailable registers too
7363 easily. Some day, this may be an error. We don't have
7364 any way to read the register, either... */
7365 if (!reg->in_g_packet)
7366 return;
7367
7368 store_registers_using_G (regcache);
7369 return;
7370 }
7371
7372 store_registers_using_G (regcache);
7373
7374 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7375 if (!rsa->regs[i].in_g_packet)
7376 if (!store_register_using_P (regcache, &rsa->regs[i]))
7377 /* See above for why we do not issue an error here. */
7378 continue;
7379 }
7380 \f
7381
7382 /* Return the number of hex digits in num. */
7383
7384 static int
7385 hexnumlen (ULONGEST num)
7386 {
7387 int i;
7388
7389 for (i = 0; num != 0; i++)
7390 num >>= 4;
7391
7392 return max (i, 1);
7393 }
7394
7395 /* Set BUF to the minimum number of hex digits representing NUM. */
7396
7397 static int
7398 hexnumstr (char *buf, ULONGEST num)
7399 {
7400 int len = hexnumlen (num);
7401
7402 return hexnumnstr (buf, num, len);
7403 }
7404
7405
7406 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7407
7408 static int
7409 hexnumnstr (char *buf, ULONGEST num, int width)
7410 {
7411 int i;
7412
7413 buf[width] = '\0';
7414
7415 for (i = width - 1; i >= 0; i--)
7416 {
7417 buf[i] = "0123456789abcdef"[(num & 0xf)];
7418 num >>= 4;
7419 }
7420
7421 return width;
7422 }
7423
7424 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7425
7426 static CORE_ADDR
7427 remote_address_masked (CORE_ADDR addr)
7428 {
7429 unsigned int address_size = remote_address_size;
7430
7431 /* If "remoteaddresssize" was not set, default to target address size. */
7432 if (!address_size)
7433 address_size = gdbarch_addr_bit (target_gdbarch ());
7434
7435 if (address_size > 0
7436 && address_size < (sizeof (ULONGEST) * 8))
7437 {
7438 /* Only create a mask when that mask can safely be constructed
7439 in a ULONGEST variable. */
7440 ULONGEST mask = 1;
7441
7442 mask = (mask << address_size) - 1;
7443 addr &= mask;
7444 }
7445 return addr;
7446 }
7447
7448 /* Determine whether the remote target supports binary downloading.
7449 This is accomplished by sending a no-op memory write of zero length
7450 to the target at the specified address. It does not suffice to send
7451 the whole packet, since many stubs strip the eighth bit and
7452 subsequently compute a wrong checksum, which causes real havoc with
7453 remote_write_bytes.
7454
7455 NOTE: This can still lose if the serial line is not eight-bit
7456 clean. In cases like this, the user should clear "remote
7457 X-packet". */
7458
7459 static void
7460 check_binary_download (CORE_ADDR addr)
7461 {
7462 struct remote_state *rs = get_remote_state ();
7463
7464 switch (packet_support (PACKET_X))
7465 {
7466 case PACKET_DISABLE:
7467 break;
7468 case PACKET_ENABLE:
7469 break;
7470 case PACKET_SUPPORT_UNKNOWN:
7471 {
7472 char *p;
7473
7474 p = rs->buf;
7475 *p++ = 'X';
7476 p += hexnumstr (p, (ULONGEST) addr);
7477 *p++ = ',';
7478 p += hexnumstr (p, (ULONGEST) 0);
7479 *p++ = ':';
7480 *p = '\0';
7481
7482 putpkt_binary (rs->buf, (int) (p - rs->buf));
7483 getpkt (&rs->buf, &rs->buf_size, 0);
7484
7485 if (rs->buf[0] == '\0')
7486 {
7487 if (remote_debug)
7488 fprintf_unfiltered (gdb_stdlog,
7489 "binary downloading NOT "
7490 "supported by target\n");
7491 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7492 }
7493 else
7494 {
7495 if (remote_debug)
7496 fprintf_unfiltered (gdb_stdlog,
7497 "binary downloading supported by target\n");
7498 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7499 }
7500 break;
7501 }
7502 }
7503 }
7504
7505 /* Helper function to resize the payload in order to try to get a good
7506 alignment. We try to write an amount of data such that the next write will
7507 start on an address aligned on REMOTE_ALIGN_WRITES. */
7508
7509 static int
7510 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7511 {
7512 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7513 }
7514
7515 /* Write memory data directly to the remote machine.
7516 This does not inform the data cache; the data cache uses this.
7517 HEADER is the starting part of the packet.
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 units to write.
7521 UNIT_SIZE is the length in bytes of an addressable unit.
7522 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7523 should send data as binary ('X'), or hex-encoded ('M').
7524
7525 The function creates packet of the form
7526 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7527
7528 where encoding of <DATA> is terminated by PACKET_FORMAT.
7529
7530 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7531 are omitted.
7532
7533 Return the transferred status, error or OK (an
7534 'enum target_xfer_status' value). Save the number of addressable units
7535 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7536
7537 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7538 exchange between gdb and the stub could look like (?? in place of the
7539 checksum):
7540
7541 -> $m1000,4#??
7542 <- aaaabbbbccccdddd
7543
7544 -> $M1000,3:eeeeffffeeee#??
7545 <- OK
7546
7547 -> $m1000,4#??
7548 <- eeeeffffeeeedddd */
7549
7550 static enum target_xfer_status
7551 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7552 const gdb_byte *myaddr, ULONGEST len_units,
7553 int unit_size, ULONGEST *xfered_len_units,
7554 char packet_format, int use_length)
7555 {
7556 struct remote_state *rs = get_remote_state ();
7557 char *p;
7558 char *plen = NULL;
7559 int plenlen = 0;
7560 int todo_units;
7561 int units_written;
7562 int payload_capacity_bytes;
7563 int payload_length_bytes;
7564
7565 if (packet_format != 'X' && packet_format != 'M')
7566 internal_error (__FILE__, __LINE__,
7567 _("remote_write_bytes_aux: bad packet format"));
7568
7569 if (len_units == 0)
7570 return TARGET_XFER_EOF;
7571
7572 payload_capacity_bytes = get_memory_write_packet_size ();
7573
7574 /* The packet buffer will be large enough for the payload;
7575 get_memory_packet_size ensures this. */
7576 rs->buf[0] = '\0';
7577
7578 /* Compute the size of the actual payload by subtracting out the
7579 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7580
7581 payload_capacity_bytes -= strlen ("$,:#NN");
7582 if (!use_length)
7583 /* The comma won't be used. */
7584 payload_capacity_bytes += 1;
7585 payload_capacity_bytes -= strlen (header);
7586 payload_capacity_bytes -= hexnumlen (memaddr);
7587
7588 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7589
7590 strcat (rs->buf, header);
7591 p = rs->buf + strlen (header);
7592
7593 /* Compute a best guess of the number of bytes actually transfered. */
7594 if (packet_format == 'X')
7595 {
7596 /* Best guess at number of bytes that will fit. */
7597 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7598 if (use_length)
7599 payload_capacity_bytes -= hexnumlen (todo_units);
7600 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7601 }
7602 else
7603 {
7604 /* Number of bytes that will fit. */
7605 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7606 if (use_length)
7607 payload_capacity_bytes -= hexnumlen (todo_units);
7608 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7609 }
7610
7611 if (todo_units <= 0)
7612 internal_error (__FILE__, __LINE__,
7613 _("minimum packet size too small to write data"));
7614
7615 /* If we already need another packet, then try to align the end
7616 of this packet to a useful boundary. */
7617 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7618 todo_units = align_for_efficient_write (todo_units, memaddr);
7619
7620 /* Append "<memaddr>". */
7621 memaddr = remote_address_masked (memaddr);
7622 p += hexnumstr (p, (ULONGEST) memaddr);
7623
7624 if (use_length)
7625 {
7626 /* Append ",". */
7627 *p++ = ',';
7628
7629 /* Append the length and retain its location and size. It may need to be
7630 adjusted once the packet body has been created. */
7631 plen = p;
7632 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7633 p += plenlen;
7634 }
7635
7636 /* Append ":". */
7637 *p++ = ':';
7638 *p = '\0';
7639
7640 /* Append the packet body. */
7641 if (packet_format == 'X')
7642 {
7643 /* Binary mode. Send target system values byte by byte, in
7644 increasing byte addresses. Only escape certain critical
7645 characters. */
7646 payload_length_bytes =
7647 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7648 &units_written, payload_capacity_bytes);
7649
7650 /* If not all TODO units fit, then we'll need another packet. Make
7651 a second try to keep the end of the packet aligned. Don't do
7652 this if the packet is tiny. */
7653 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7654 {
7655 int new_todo_units;
7656
7657 new_todo_units = align_for_efficient_write (units_written, memaddr);
7658
7659 if (new_todo_units != units_written)
7660 payload_length_bytes =
7661 remote_escape_output (myaddr, new_todo_units, unit_size,
7662 (gdb_byte *) p, &units_written,
7663 payload_capacity_bytes);
7664 }
7665
7666 p += payload_length_bytes;
7667 if (use_length && units_written < todo_units)
7668 {
7669 /* Escape chars have filled up the buffer prematurely,
7670 and we have actually sent fewer units than planned.
7671 Fix-up the length field of the packet. Use the same
7672 number of characters as before. */
7673 plen += hexnumnstr (plen, (ULONGEST) units_written,
7674 plenlen);
7675 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7676 }
7677 }
7678 else
7679 {
7680 /* Normal mode: Send target system values byte by byte, in
7681 increasing byte addresses. Each byte is encoded as a two hex
7682 value. */
7683 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7684 units_written = todo_units;
7685 }
7686
7687 putpkt_binary (rs->buf, (int) (p - rs->buf));
7688 getpkt (&rs->buf, &rs->buf_size, 0);
7689
7690 if (rs->buf[0] == 'E')
7691 return TARGET_XFER_E_IO;
7692
7693 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7694 send fewer units than we'd planned. */
7695 *xfered_len_units = (ULONGEST) units_written;
7696 return TARGET_XFER_OK;
7697 }
7698
7699 /* Write memory data directly to the remote machine.
7700 This does not inform the data cache; the data cache uses this.
7701 MEMADDR is the address in the remote memory space.
7702 MYADDR is the address of the buffer in our space.
7703 LEN is the number of bytes.
7704
7705 Return the transferred status, error or OK (an
7706 'enum target_xfer_status' value). Save the number of bytes
7707 transferred in *XFERED_LEN. Only transfer a single packet. */
7708
7709 static enum target_xfer_status
7710 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7711 int unit_size, ULONGEST *xfered_len)
7712 {
7713 char *packet_format = 0;
7714
7715 /* Check whether the target supports binary download. */
7716 check_binary_download (memaddr);
7717
7718 switch (packet_support (PACKET_X))
7719 {
7720 case PACKET_ENABLE:
7721 packet_format = "X";
7722 break;
7723 case PACKET_DISABLE:
7724 packet_format = "M";
7725 break;
7726 case PACKET_SUPPORT_UNKNOWN:
7727 internal_error (__FILE__, __LINE__,
7728 _("remote_write_bytes: bad internal state"));
7729 default:
7730 internal_error (__FILE__, __LINE__, _("bad switch"));
7731 }
7732
7733 return remote_write_bytes_aux (packet_format,
7734 memaddr, myaddr, len, unit_size, xfered_len,
7735 packet_format[0], 1);
7736 }
7737
7738 /* Read memory data directly from the remote machine.
7739 This does not use the data cache; the data cache uses this.
7740 MEMADDR is the address in the remote memory space.
7741 MYADDR is the address of the buffer in our space.
7742 LEN_UNITS is the number of addressable memory units to read..
7743 UNIT_SIZE is the length in bytes of an addressable unit.
7744
7745 Return the transferred status, error or OK (an
7746 'enum target_xfer_status' value). Save the number of bytes
7747 transferred in *XFERED_LEN_UNITS.
7748
7749 See the comment of remote_write_bytes_aux for an example of
7750 memory read/write exchange between gdb and the stub. */
7751
7752 static enum target_xfer_status
7753 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7754 int unit_size, ULONGEST *xfered_len_units)
7755 {
7756 struct remote_state *rs = get_remote_state ();
7757 int buf_size_bytes; /* Max size of packet output buffer. */
7758 char *p;
7759 int todo_units;
7760 int decoded_bytes;
7761
7762 buf_size_bytes = get_memory_read_packet_size ();
7763 /* The packet buffer will be large enough for the payload;
7764 get_memory_packet_size ensures this. */
7765
7766 /* Number of units that will fit. */
7767 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7768
7769 /* Construct "m"<memaddr>","<len>". */
7770 memaddr = remote_address_masked (memaddr);
7771 p = rs->buf;
7772 *p++ = 'm';
7773 p += hexnumstr (p, (ULONGEST) memaddr);
7774 *p++ = ',';
7775 p += hexnumstr (p, (ULONGEST) todo_units);
7776 *p = '\0';
7777 putpkt (rs->buf);
7778 getpkt (&rs->buf, &rs->buf_size, 0);
7779 if (rs->buf[0] == 'E'
7780 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7781 && rs->buf[3] == '\0')
7782 return TARGET_XFER_E_IO;
7783 /* Reply describes memory byte by byte, each byte encoded as two hex
7784 characters. */
7785 p = rs->buf;
7786 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7787 /* Return what we have. Let higher layers handle partial reads. */
7788 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7789 return TARGET_XFER_OK;
7790 }
7791
7792 /* Using the set of read-only target sections of remote, read live
7793 read-only memory.
7794
7795 For interface/parameters/return description see target.h,
7796 to_xfer_partial. */
7797
7798 static enum target_xfer_status
7799 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7800 ULONGEST memaddr, ULONGEST len,
7801 int unit_size, ULONGEST *xfered_len)
7802 {
7803 struct target_section *secp;
7804 struct target_section_table *table;
7805
7806 secp = target_section_by_addr (ops, memaddr);
7807 if (secp != NULL
7808 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7809 secp->the_bfd_section)
7810 & SEC_READONLY))
7811 {
7812 struct target_section *p;
7813 ULONGEST memend = memaddr + len;
7814
7815 table = target_get_section_table (ops);
7816
7817 for (p = table->sections; p < table->sections_end; p++)
7818 {
7819 if (memaddr >= p->addr)
7820 {
7821 if (memend <= p->endaddr)
7822 {
7823 /* Entire transfer is within this section. */
7824 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7825 xfered_len);
7826 }
7827 else if (memaddr >= p->endaddr)
7828 {
7829 /* This section ends before the transfer starts. */
7830 continue;
7831 }
7832 else
7833 {
7834 /* This section overlaps the transfer. Just do half. */
7835 len = p->endaddr - memaddr;
7836 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7837 xfered_len);
7838 }
7839 }
7840 }
7841 }
7842
7843 return TARGET_XFER_EOF;
7844 }
7845
7846 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7847 first if the requested memory is unavailable in traceframe.
7848 Otherwise, fall back to remote_read_bytes_1. */
7849
7850 static enum target_xfer_status
7851 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7852 gdb_byte *myaddr, ULONGEST len, int unit_size,
7853 ULONGEST *xfered_len)
7854 {
7855 if (len == 0)
7856 return TARGET_XFER_EOF;
7857
7858 if (get_traceframe_number () != -1)
7859 {
7860 VEC(mem_range_s) *available;
7861
7862 /* If we fail to get the set of available memory, then the
7863 target does not support querying traceframe info, and so we
7864 attempt reading from the traceframe anyway (assuming the
7865 target implements the old QTro packet then). */
7866 if (traceframe_available_memory (&available, memaddr, len))
7867 {
7868 struct cleanup *old_chain;
7869
7870 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7871
7872 if (VEC_empty (mem_range_s, available)
7873 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7874 {
7875 enum target_xfer_status res;
7876
7877 /* Don't read into the traceframe's available
7878 memory. */
7879 if (!VEC_empty (mem_range_s, available))
7880 {
7881 LONGEST oldlen = len;
7882
7883 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7884 gdb_assert (len <= oldlen);
7885 }
7886
7887 do_cleanups (old_chain);
7888
7889 /* This goes through the topmost target again. */
7890 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7891 len, unit_size, xfered_len);
7892 if (res == TARGET_XFER_OK)
7893 return TARGET_XFER_OK;
7894 else
7895 {
7896 /* No use trying further, we know some memory starting
7897 at MEMADDR isn't available. */
7898 *xfered_len = len;
7899 return TARGET_XFER_UNAVAILABLE;
7900 }
7901 }
7902
7903 /* Don't try to read more than how much is available, in
7904 case the target implements the deprecated QTro packet to
7905 cater for older GDBs (the target's knowledge of read-only
7906 sections may be outdated by now). */
7907 len = VEC_index (mem_range_s, available, 0)->length;
7908
7909 do_cleanups (old_chain);
7910 }
7911 }
7912
7913 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7914 }
7915
7916 \f
7917
7918 /* Sends a packet with content determined by the printf format string
7919 FORMAT and the remaining arguments, then gets the reply. Returns
7920 whether the packet was a success, a failure, or unknown. */
7921
7922 static enum packet_result remote_send_printf (const char *format, ...)
7923 ATTRIBUTE_PRINTF (1, 2);
7924
7925 static enum packet_result
7926 remote_send_printf (const char *format, ...)
7927 {
7928 struct remote_state *rs = get_remote_state ();
7929 int max_size = get_remote_packet_size ();
7930 va_list ap;
7931
7932 va_start (ap, format);
7933
7934 rs->buf[0] = '\0';
7935 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7936 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7937
7938 if (putpkt (rs->buf) < 0)
7939 error (_("Communication problem with target."));
7940
7941 rs->buf[0] = '\0';
7942 getpkt (&rs->buf, &rs->buf_size, 0);
7943
7944 return packet_check_result (rs->buf);
7945 }
7946
7947 static void
7948 restore_remote_timeout (void *p)
7949 {
7950 int value = *(int *)p;
7951
7952 remote_timeout = value;
7953 }
7954
7955 /* Flash writing can take quite some time. We'll set
7956 effectively infinite timeout for flash operations.
7957 In future, we'll need to decide on a better approach. */
7958 static const int remote_flash_timeout = 1000;
7959
7960 static void
7961 remote_flash_erase (struct target_ops *ops,
7962 ULONGEST address, LONGEST length)
7963 {
7964 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7965 int saved_remote_timeout = remote_timeout;
7966 enum packet_result ret;
7967 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7968 &saved_remote_timeout);
7969
7970 remote_timeout = remote_flash_timeout;
7971
7972 ret = remote_send_printf ("vFlashErase:%s,%s",
7973 phex (address, addr_size),
7974 phex (length, 4));
7975 switch (ret)
7976 {
7977 case PACKET_UNKNOWN:
7978 error (_("Remote target does not support flash erase"));
7979 case PACKET_ERROR:
7980 error (_("Error erasing flash with vFlashErase packet"));
7981 default:
7982 break;
7983 }
7984
7985 do_cleanups (back_to);
7986 }
7987
7988 static enum target_xfer_status
7989 remote_flash_write (struct target_ops *ops, ULONGEST address,
7990 ULONGEST length, ULONGEST *xfered_len,
7991 const gdb_byte *data)
7992 {
7993 int saved_remote_timeout = remote_timeout;
7994 enum target_xfer_status ret;
7995 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7996 &saved_remote_timeout);
7997
7998 remote_timeout = remote_flash_timeout;
7999 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8000 xfered_len,'X', 0);
8001 do_cleanups (back_to);
8002
8003 return ret;
8004 }
8005
8006 static void
8007 remote_flash_done (struct target_ops *ops)
8008 {
8009 int saved_remote_timeout = remote_timeout;
8010 int ret;
8011 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8012 &saved_remote_timeout);
8013
8014 remote_timeout = remote_flash_timeout;
8015 ret = remote_send_printf ("vFlashDone");
8016 do_cleanups (back_to);
8017
8018 switch (ret)
8019 {
8020 case PACKET_UNKNOWN:
8021 error (_("Remote target does not support vFlashDone"));
8022 case PACKET_ERROR:
8023 error (_("Error finishing flash operation"));
8024 default:
8025 break;
8026 }
8027 }
8028
8029 static void
8030 remote_files_info (struct target_ops *ignore)
8031 {
8032 puts_filtered ("Debugging a target over a serial line.\n");
8033 }
8034 \f
8035 /* Stuff for dealing with the packets which are part of this protocol.
8036 See comment at top of file for details. */
8037
8038 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8039 error to higher layers. Called when a serial error is detected.
8040 The exception message is STRING, followed by a colon and a blank,
8041 the system error message for errno at function entry and final dot
8042 for output compatibility with throw_perror_with_name. */
8043
8044 static void
8045 unpush_and_perror (const char *string)
8046 {
8047 int saved_errno = errno;
8048
8049 remote_unpush_target ();
8050 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8051 safe_strerror (saved_errno));
8052 }
8053
8054 /* Read a single character from the remote end. */
8055
8056 static int
8057 readchar (int timeout)
8058 {
8059 int ch;
8060 struct remote_state *rs = get_remote_state ();
8061
8062 ch = serial_readchar (rs->remote_desc, timeout);
8063
8064 if (ch >= 0)
8065 return ch;
8066
8067 switch ((enum serial_rc) ch)
8068 {
8069 case SERIAL_EOF:
8070 remote_unpush_target ();
8071 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8072 /* no return */
8073 case SERIAL_ERROR:
8074 unpush_and_perror (_("Remote communication error. "
8075 "Target disconnected."));
8076 /* no return */
8077 case SERIAL_TIMEOUT:
8078 break;
8079 }
8080 return ch;
8081 }
8082
8083 /* Wrapper for serial_write that closes the target and throws if
8084 writing fails. */
8085
8086 static void
8087 remote_serial_write (const char *str, int len)
8088 {
8089 struct remote_state *rs = get_remote_state ();
8090
8091 if (serial_write (rs->remote_desc, str, len))
8092 {
8093 unpush_and_perror (_("Remote communication error. "
8094 "Target disconnected."));
8095 }
8096 }
8097
8098 /* Send the command in *BUF to the remote machine, and read the reply
8099 into *BUF. Report an error if we get an error reply. Resize
8100 *BUF using xrealloc if necessary to hold the result, and update
8101 *SIZEOF_BUF. */
8102
8103 static void
8104 remote_send (char **buf,
8105 long *sizeof_buf)
8106 {
8107 putpkt (*buf);
8108 getpkt (buf, sizeof_buf, 0);
8109
8110 if ((*buf)[0] == 'E')
8111 error (_("Remote failure reply: %s"), *buf);
8112 }
8113
8114 /* Return a pointer to an xmalloc'ed string representing an escaped
8115 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8116 etc. The caller is responsible for releasing the returned
8117 memory. */
8118
8119 static char *
8120 escape_buffer (const char *buf, int n)
8121 {
8122 struct cleanup *old_chain;
8123 struct ui_file *stb;
8124 char *str;
8125
8126 stb = mem_fileopen ();
8127 old_chain = make_cleanup_ui_file_delete (stb);
8128
8129 fputstrn_unfiltered (buf, n, '\\', stb);
8130 str = ui_file_xstrdup (stb, NULL);
8131 do_cleanups (old_chain);
8132 return str;
8133 }
8134
8135 /* Display a null-terminated packet on stdout, for debugging, using C
8136 string notation. */
8137
8138 static void
8139 print_packet (const char *buf)
8140 {
8141 puts_filtered ("\"");
8142 fputstr_filtered (buf, '"', gdb_stdout);
8143 puts_filtered ("\"");
8144 }
8145
8146 int
8147 putpkt (const char *buf)
8148 {
8149 return putpkt_binary (buf, strlen (buf));
8150 }
8151
8152 /* Send a packet to the remote machine, with error checking. The data
8153 of the packet is in BUF. The string in BUF can be at most
8154 get_remote_packet_size () - 5 to account for the $, # and checksum,
8155 and for a possible /0 if we are debugging (remote_debug) and want
8156 to print the sent packet as a string. */
8157
8158 static int
8159 putpkt_binary (const char *buf, int cnt)
8160 {
8161 struct remote_state *rs = get_remote_state ();
8162 int i;
8163 unsigned char csum = 0;
8164 char *buf2 = (char *) xmalloc (cnt + 6);
8165 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8166
8167 int ch;
8168 int tcount = 0;
8169 char *p;
8170 char *message;
8171
8172 /* Catch cases like trying to read memory or listing threads while
8173 we're waiting for a stop reply. The remote server wouldn't be
8174 ready to handle this request, so we'd hang and timeout. We don't
8175 have to worry about this in synchronous mode, because in that
8176 case it's not possible to issue a command while the target is
8177 running. This is not a problem in non-stop mode, because in that
8178 case, the stub is always ready to process serial input. */
8179 if (!target_is_non_stop_p ()
8180 && target_is_async_p ()
8181 && rs->waiting_for_stop_reply)
8182 {
8183 error (_("Cannot execute this command while the target is running.\n"
8184 "Use the \"interrupt\" command to stop the target\n"
8185 "and then try again."));
8186 }
8187
8188 /* We're sending out a new packet. Make sure we don't look at a
8189 stale cached response. */
8190 rs->cached_wait_status = 0;
8191
8192 /* Copy the packet into buffer BUF2, encapsulating it
8193 and giving it a checksum. */
8194
8195 p = buf2;
8196 *p++ = '$';
8197
8198 for (i = 0; i < cnt; i++)
8199 {
8200 csum += buf[i];
8201 *p++ = buf[i];
8202 }
8203 *p++ = '#';
8204 *p++ = tohex ((csum >> 4) & 0xf);
8205 *p++ = tohex (csum & 0xf);
8206
8207 /* Send it over and over until we get a positive ack. */
8208
8209 while (1)
8210 {
8211 int started_error_output = 0;
8212
8213 if (remote_debug)
8214 {
8215 struct cleanup *old_chain;
8216 char *str;
8217
8218 *p = '\0';
8219 str = escape_buffer (buf2, p - buf2);
8220 old_chain = make_cleanup (xfree, str);
8221 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8222 gdb_flush (gdb_stdlog);
8223 do_cleanups (old_chain);
8224 }
8225 remote_serial_write (buf2, p - buf2);
8226
8227 /* If this is a no acks version of the remote protocol, send the
8228 packet and move on. */
8229 if (rs->noack_mode)
8230 break;
8231
8232 /* Read until either a timeout occurs (-2) or '+' is read.
8233 Handle any notification that arrives in the mean time. */
8234 while (1)
8235 {
8236 ch = readchar (remote_timeout);
8237
8238 if (remote_debug)
8239 {
8240 switch (ch)
8241 {
8242 case '+':
8243 case '-':
8244 case SERIAL_TIMEOUT:
8245 case '$':
8246 case '%':
8247 if (started_error_output)
8248 {
8249 putchar_unfiltered ('\n');
8250 started_error_output = 0;
8251 }
8252 }
8253 }
8254
8255 switch (ch)
8256 {
8257 case '+':
8258 if (remote_debug)
8259 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8260 do_cleanups (old_chain);
8261 return 1;
8262 case '-':
8263 if (remote_debug)
8264 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8265 /* FALLTHROUGH */
8266 case SERIAL_TIMEOUT:
8267 tcount++;
8268 if (tcount > 3)
8269 {
8270 do_cleanups (old_chain);
8271 return 0;
8272 }
8273 break; /* Retransmit buffer. */
8274 case '$':
8275 {
8276 if (remote_debug)
8277 fprintf_unfiltered (gdb_stdlog,
8278 "Packet instead of Ack, ignoring it\n");
8279 /* It's probably an old response sent because an ACK
8280 was lost. Gobble up the packet and ack it so it
8281 doesn't get retransmitted when we resend this
8282 packet. */
8283 skip_frame ();
8284 remote_serial_write ("+", 1);
8285 continue; /* Now, go look for +. */
8286 }
8287
8288 case '%':
8289 {
8290 int val;
8291
8292 /* If we got a notification, handle it, and go back to looking
8293 for an ack. */
8294 /* We've found the start of a notification. Now
8295 collect the data. */
8296 val = read_frame (&rs->buf, &rs->buf_size);
8297 if (val >= 0)
8298 {
8299 if (remote_debug)
8300 {
8301 struct cleanup *old_chain;
8302 char *str;
8303
8304 str = escape_buffer (rs->buf, val);
8305 old_chain = make_cleanup (xfree, str);
8306 fprintf_unfiltered (gdb_stdlog,
8307 " Notification received: %s\n",
8308 str);
8309 do_cleanups (old_chain);
8310 }
8311 handle_notification (rs->notif_state, rs->buf);
8312 /* We're in sync now, rewait for the ack. */
8313 tcount = 0;
8314 }
8315 else
8316 {
8317 if (remote_debug)
8318 {
8319 if (!started_error_output)
8320 {
8321 started_error_output = 1;
8322 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8323 }
8324 fputc_unfiltered (ch & 0177, gdb_stdlog);
8325 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8326 }
8327 }
8328 continue;
8329 }
8330 /* fall-through */
8331 default:
8332 if (remote_debug)
8333 {
8334 if (!started_error_output)
8335 {
8336 started_error_output = 1;
8337 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8338 }
8339 fputc_unfiltered (ch & 0177, gdb_stdlog);
8340 }
8341 continue;
8342 }
8343 break; /* Here to retransmit. */
8344 }
8345
8346 #if 0
8347 /* This is wrong. If doing a long backtrace, the user should be
8348 able to get out next time we call QUIT, without anything as
8349 violent as interrupt_query. If we want to provide a way out of
8350 here without getting to the next QUIT, it should be based on
8351 hitting ^C twice as in remote_wait. */
8352 if (quit_flag)
8353 {
8354 quit_flag = 0;
8355 interrupt_query ();
8356 }
8357 #endif
8358 }
8359
8360 do_cleanups (old_chain);
8361 return 0;
8362 }
8363
8364 /* Come here after finding the start of a frame when we expected an
8365 ack. Do our best to discard the rest of this packet. */
8366
8367 static void
8368 skip_frame (void)
8369 {
8370 int c;
8371
8372 while (1)
8373 {
8374 c = readchar (remote_timeout);
8375 switch (c)
8376 {
8377 case SERIAL_TIMEOUT:
8378 /* Nothing we can do. */
8379 return;
8380 case '#':
8381 /* Discard the two bytes of checksum and stop. */
8382 c = readchar (remote_timeout);
8383 if (c >= 0)
8384 c = readchar (remote_timeout);
8385
8386 return;
8387 case '*': /* Run length encoding. */
8388 /* Discard the repeat count. */
8389 c = readchar (remote_timeout);
8390 if (c < 0)
8391 return;
8392 break;
8393 default:
8394 /* A regular character. */
8395 break;
8396 }
8397 }
8398 }
8399
8400 /* Come here after finding the start of the frame. Collect the rest
8401 into *BUF, verifying the checksum, length, and handling run-length
8402 compression. NUL terminate the buffer. If there is not enough room,
8403 expand *BUF using xrealloc.
8404
8405 Returns -1 on error, number of characters in buffer (ignoring the
8406 trailing NULL) on success. (could be extended to return one of the
8407 SERIAL status indications). */
8408
8409 static long
8410 read_frame (char **buf_p,
8411 long *sizeof_buf)
8412 {
8413 unsigned char csum;
8414 long bc;
8415 int c;
8416 char *buf = *buf_p;
8417 struct remote_state *rs = get_remote_state ();
8418
8419 csum = 0;
8420 bc = 0;
8421
8422 while (1)
8423 {
8424 c = readchar (remote_timeout);
8425 switch (c)
8426 {
8427 case SERIAL_TIMEOUT:
8428 if (remote_debug)
8429 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8430 return -1;
8431 case '$':
8432 if (remote_debug)
8433 fputs_filtered ("Saw new packet start in middle of old one\n",
8434 gdb_stdlog);
8435 return -1; /* Start a new packet, count retries. */
8436 case '#':
8437 {
8438 unsigned char pktcsum;
8439 int check_0 = 0;
8440 int check_1 = 0;
8441
8442 buf[bc] = '\0';
8443
8444 check_0 = readchar (remote_timeout);
8445 if (check_0 >= 0)
8446 check_1 = readchar (remote_timeout);
8447
8448 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8449 {
8450 if (remote_debug)
8451 fputs_filtered ("Timeout in checksum, retrying\n",
8452 gdb_stdlog);
8453 return -1;
8454 }
8455 else if (check_0 < 0 || check_1 < 0)
8456 {
8457 if (remote_debug)
8458 fputs_filtered ("Communication error in checksum\n",
8459 gdb_stdlog);
8460 return -1;
8461 }
8462
8463 /* Don't recompute the checksum; with no ack packets we
8464 don't have any way to indicate a packet retransmission
8465 is necessary. */
8466 if (rs->noack_mode)
8467 return bc;
8468
8469 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8470 if (csum == pktcsum)
8471 return bc;
8472
8473 if (remote_debug)
8474 {
8475 struct cleanup *old_chain;
8476 char *str;
8477
8478 str = escape_buffer (buf, bc);
8479 old_chain = make_cleanup (xfree, str);
8480 fprintf_unfiltered (gdb_stdlog,
8481 "Bad checksum, sentsum=0x%x, "
8482 "csum=0x%x, buf=%s\n",
8483 pktcsum, csum, str);
8484 do_cleanups (old_chain);
8485 }
8486 /* Number of characters in buffer ignoring trailing
8487 NULL. */
8488 return -1;
8489 }
8490 case '*': /* Run length encoding. */
8491 {
8492 int repeat;
8493
8494 csum += c;
8495 c = readchar (remote_timeout);
8496 csum += c;
8497 repeat = c - ' ' + 3; /* Compute repeat count. */
8498
8499 /* The character before ``*'' is repeated. */
8500
8501 if (repeat > 0 && repeat <= 255 && bc > 0)
8502 {
8503 if (bc + repeat - 1 >= *sizeof_buf - 1)
8504 {
8505 /* Make some more room in the buffer. */
8506 *sizeof_buf += repeat;
8507 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8508 buf = *buf_p;
8509 }
8510
8511 memset (&buf[bc], buf[bc - 1], repeat);
8512 bc += repeat;
8513 continue;
8514 }
8515
8516 buf[bc] = '\0';
8517 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8518 return -1;
8519 }
8520 default:
8521 if (bc >= *sizeof_buf - 1)
8522 {
8523 /* Make some more room in the buffer. */
8524 *sizeof_buf *= 2;
8525 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8526 buf = *buf_p;
8527 }
8528
8529 buf[bc++] = c;
8530 csum += c;
8531 continue;
8532 }
8533 }
8534 }
8535
8536 /* Read a packet from the remote machine, with error checking, and
8537 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8538 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8539 rather than timing out; this is used (in synchronous mode) to wait
8540 for a target that is is executing user code to stop. */
8541 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8542 don't have to change all the calls to getpkt to deal with the
8543 return value, because at the moment I don't know what the right
8544 thing to do it for those. */
8545 void
8546 getpkt (char **buf,
8547 long *sizeof_buf,
8548 int forever)
8549 {
8550 int timed_out;
8551
8552 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8553 }
8554
8555
8556 /* Read a packet from the remote machine, with error checking, and
8557 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8558 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8559 rather than timing out; this is used (in synchronous mode) to wait
8560 for a target that is is executing user code to stop. If FOREVER ==
8561 0, this function is allowed to time out gracefully and return an
8562 indication of this to the caller. Otherwise return the number of
8563 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8564 enough reason to return to the caller. *IS_NOTIF is an output
8565 boolean that indicates whether *BUF holds a notification or not
8566 (a regular packet). */
8567
8568 static int
8569 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8570 int expecting_notif, int *is_notif)
8571 {
8572 struct remote_state *rs = get_remote_state ();
8573 int c;
8574 int tries;
8575 int timeout;
8576 int val = -1;
8577
8578 /* We're reading a new response. Make sure we don't look at a
8579 previously cached response. */
8580 rs->cached_wait_status = 0;
8581
8582 strcpy (*buf, "timeout");
8583
8584 if (forever)
8585 timeout = watchdog > 0 ? watchdog : -1;
8586 else if (expecting_notif)
8587 timeout = 0; /* There should already be a char in the buffer. If
8588 not, bail out. */
8589 else
8590 timeout = remote_timeout;
8591
8592 #define MAX_TRIES 3
8593
8594 /* Process any number of notifications, and then return when
8595 we get a packet. */
8596 for (;;)
8597 {
8598 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8599 times. */
8600 for (tries = 1; tries <= MAX_TRIES; tries++)
8601 {
8602 /* This can loop forever if the remote side sends us
8603 characters continuously, but if it pauses, we'll get
8604 SERIAL_TIMEOUT from readchar because of timeout. Then
8605 we'll count that as a retry.
8606
8607 Note that even when forever is set, we will only wait
8608 forever prior to the start of a packet. After that, we
8609 expect characters to arrive at a brisk pace. They should
8610 show up within remote_timeout intervals. */
8611 do
8612 c = readchar (timeout);
8613 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8614
8615 if (c == SERIAL_TIMEOUT)
8616 {
8617 if (expecting_notif)
8618 return -1; /* Don't complain, it's normal to not get
8619 anything in this case. */
8620
8621 if (forever) /* Watchdog went off? Kill the target. */
8622 {
8623 QUIT;
8624 remote_unpush_target ();
8625 throw_error (TARGET_CLOSE_ERROR,
8626 _("Watchdog timeout has expired. "
8627 "Target detached."));
8628 }
8629 if (remote_debug)
8630 fputs_filtered ("Timed out.\n", gdb_stdlog);
8631 }
8632 else
8633 {
8634 /* We've found the start of a packet or notification.
8635 Now collect the data. */
8636 val = read_frame (buf, sizeof_buf);
8637 if (val >= 0)
8638 break;
8639 }
8640
8641 remote_serial_write ("-", 1);
8642 }
8643
8644 if (tries > MAX_TRIES)
8645 {
8646 /* We have tried hard enough, and just can't receive the
8647 packet/notification. Give up. */
8648 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8649
8650 /* Skip the ack char if we're in no-ack mode. */
8651 if (!rs->noack_mode)
8652 remote_serial_write ("+", 1);
8653 return -1;
8654 }
8655
8656 /* If we got an ordinary packet, return that to our caller. */
8657 if (c == '$')
8658 {
8659 if (remote_debug)
8660 {
8661 struct cleanup *old_chain;
8662 char *str;
8663
8664 str = escape_buffer (*buf, val);
8665 old_chain = make_cleanup (xfree, str);
8666 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8667 do_cleanups (old_chain);
8668 }
8669
8670 /* Skip the ack char if we're in no-ack mode. */
8671 if (!rs->noack_mode)
8672 remote_serial_write ("+", 1);
8673 if (is_notif != NULL)
8674 *is_notif = 0;
8675 return val;
8676 }
8677
8678 /* If we got a notification, handle it, and go back to looking
8679 for a packet. */
8680 else
8681 {
8682 gdb_assert (c == '%');
8683
8684 if (remote_debug)
8685 {
8686 struct cleanup *old_chain;
8687 char *str;
8688
8689 str = escape_buffer (*buf, val);
8690 old_chain = make_cleanup (xfree, str);
8691 fprintf_unfiltered (gdb_stdlog,
8692 " Notification received: %s\n",
8693 str);
8694 do_cleanups (old_chain);
8695 }
8696 if (is_notif != NULL)
8697 *is_notif = 1;
8698
8699 handle_notification (rs->notif_state, *buf);
8700
8701 /* Notifications require no acknowledgement. */
8702
8703 if (expecting_notif)
8704 return val;
8705 }
8706 }
8707 }
8708
8709 static int
8710 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8711 {
8712 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8713 }
8714
8715 static int
8716 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8717 int *is_notif)
8718 {
8719 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8720 is_notif);
8721 }
8722
8723 /* Check whether EVENT is a fork event for the process specified
8724 by the pid passed in DATA, and if it is, kill the fork child. */
8725
8726 static int
8727 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8728 QUEUE_ITER (stop_reply_p) *iter,
8729 stop_reply_p event,
8730 void *data)
8731 {
8732 struct queue_iter_param *param = (struct queue_iter_param *) data;
8733 int parent_pid = *(int *) param->input;
8734
8735 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8736 {
8737 struct remote_state *rs = get_remote_state ();
8738 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8739 int res;
8740
8741 res = remote_vkill (child_pid, rs);
8742 if (res != 0)
8743 error (_("Can't kill fork child process %d"), child_pid);
8744 }
8745
8746 return 1;
8747 }
8748
8749 /* Kill any new fork children of process PID that haven't been
8750 processed by follow_fork. */
8751
8752 static void
8753 kill_new_fork_children (int pid, struct remote_state *rs)
8754 {
8755 struct thread_info *thread;
8756 struct notif_client *notif = &notif_client_stop;
8757 struct queue_iter_param param;
8758
8759 /* Kill the fork child threads of any threads in process PID
8760 that are stopped at a fork event. */
8761 ALL_NON_EXITED_THREADS (thread)
8762 {
8763 struct target_waitstatus *ws = &thread->pending_follow;
8764
8765 if (is_pending_fork_parent (ws, pid, thread->ptid))
8766 {
8767 struct remote_state *rs = get_remote_state ();
8768 int child_pid = ptid_get_pid (ws->value.related_pid);
8769 int res;
8770
8771 res = remote_vkill (child_pid, rs);
8772 if (res != 0)
8773 error (_("Can't kill fork child process %d"), child_pid);
8774 }
8775 }
8776
8777 /* Check for any pending fork events (not reported or processed yet)
8778 in process PID and kill those fork child threads as well. */
8779 remote_notif_get_pending_events (notif);
8780 param.input = &pid;
8781 param.output = NULL;
8782 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8783 kill_child_of_pending_fork, &param);
8784 }
8785
8786 \f
8787 static void
8788 remote_kill (struct target_ops *ops)
8789 {
8790
8791 /* Catch errors so the user can quit from gdb even when we
8792 aren't on speaking terms with the remote system. */
8793 TRY
8794 {
8795 putpkt ("k");
8796 }
8797 CATCH (ex, RETURN_MASK_ERROR)
8798 {
8799 if (ex.error == TARGET_CLOSE_ERROR)
8800 {
8801 /* If we got an (EOF) error that caused the target
8802 to go away, then we're done, that's what we wanted.
8803 "k" is susceptible to cause a premature EOF, given
8804 that the remote server isn't actually required to
8805 reply to "k", and it can happen that it doesn't
8806 even get to reply ACK to the "k". */
8807 return;
8808 }
8809
8810 /* Otherwise, something went wrong. We didn't actually kill
8811 the target. Just propagate the exception, and let the
8812 user or higher layers decide what to do. */
8813 throw_exception (ex);
8814 }
8815 END_CATCH
8816
8817 /* We've killed the remote end, we get to mourn it. Since this is
8818 target remote, single-process, mourning the inferior also
8819 unpushes remote_ops. */
8820 target_mourn_inferior ();
8821 }
8822
8823 static int
8824 remote_vkill (int pid, struct remote_state *rs)
8825 {
8826 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8827 return -1;
8828
8829 /* Tell the remote target to detach. */
8830 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8831 putpkt (rs->buf);
8832 getpkt (&rs->buf, &rs->buf_size, 0);
8833
8834 switch (packet_ok (rs->buf,
8835 &remote_protocol_packets[PACKET_vKill]))
8836 {
8837 case PACKET_OK:
8838 return 0;
8839 case PACKET_ERROR:
8840 return 1;
8841 case PACKET_UNKNOWN:
8842 return -1;
8843 default:
8844 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8845 }
8846 }
8847
8848 static void
8849 extended_remote_kill (struct target_ops *ops)
8850 {
8851 int res;
8852 int pid = ptid_get_pid (inferior_ptid);
8853 struct remote_state *rs = get_remote_state ();
8854
8855 /* If we're stopped while forking and we haven't followed yet, kill the
8856 child task. We need to do this before killing the parent task
8857 because if this is a vfork then the parent will be sleeping. */
8858 kill_new_fork_children (pid, rs);
8859
8860 res = remote_vkill (pid, rs);
8861 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8862 {
8863 /* Don't try 'k' on a multi-process aware stub -- it has no way
8864 to specify the pid. */
8865
8866 putpkt ("k");
8867 #if 0
8868 getpkt (&rs->buf, &rs->buf_size, 0);
8869 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8870 res = 1;
8871 #else
8872 /* Don't wait for it to die. I'm not really sure it matters whether
8873 we do or not. For the existing stubs, kill is a noop. */
8874 res = 0;
8875 #endif
8876 }
8877
8878 if (res != 0)
8879 error (_("Can't kill process"));
8880
8881 target_mourn_inferior ();
8882 }
8883
8884 static void
8885 remote_mourn (struct target_ops *target)
8886 {
8887 unpush_target (target);
8888
8889 /* remote_close takes care of doing most of the clean up. */
8890 generic_mourn_inferior ();
8891 }
8892
8893 static void
8894 extended_remote_mourn (struct target_ops *target)
8895 {
8896 struct remote_state *rs = get_remote_state ();
8897
8898 /* In case we got here due to an error, but we're going to stay
8899 connected. */
8900 rs->waiting_for_stop_reply = 0;
8901
8902 /* If the current general thread belonged to the process we just
8903 detached from or has exited, the remote side current general
8904 thread becomes undefined. Considering a case like this:
8905
8906 - We just got here due to a detach.
8907 - The process that we're detaching from happens to immediately
8908 report a global breakpoint being hit in non-stop mode, in the
8909 same thread we had selected before.
8910 - GDB attaches to this process again.
8911 - This event happens to be the next event we handle.
8912
8913 GDB would consider that the current general thread didn't need to
8914 be set on the stub side (with Hg), since for all it knew,
8915 GENERAL_THREAD hadn't changed.
8916
8917 Notice that although in all-stop mode, the remote server always
8918 sets the current thread to the thread reporting the stop event,
8919 that doesn't happen in non-stop mode; in non-stop, the stub *must
8920 not* change the current thread when reporting a breakpoint hit,
8921 due to the decoupling of event reporting and event handling.
8922
8923 To keep things simple, we always invalidate our notion of the
8924 current thread. */
8925 record_currthread (rs, minus_one_ptid);
8926
8927 /* Unlike "target remote", we do not want to unpush the target; then
8928 the next time the user says "run", we won't be connected. */
8929
8930 /* Call common code to mark the inferior as not running. */
8931 generic_mourn_inferior ();
8932
8933 if (!have_inferiors ())
8934 {
8935 if (!remote_multi_process_p (rs))
8936 {
8937 /* Check whether the target is running now - some remote stubs
8938 automatically restart after kill. */
8939 putpkt ("?");
8940 getpkt (&rs->buf, &rs->buf_size, 0);
8941
8942 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8943 {
8944 /* Assume that the target has been restarted. Set
8945 inferior_ptid so that bits of core GDB realizes
8946 there's something here, e.g., so that the user can
8947 say "kill" again. */
8948 inferior_ptid = magic_null_ptid;
8949 }
8950 }
8951 }
8952 }
8953
8954 static int
8955 extended_remote_supports_disable_randomization (struct target_ops *self)
8956 {
8957 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8958 }
8959
8960 static void
8961 extended_remote_disable_randomization (int val)
8962 {
8963 struct remote_state *rs = get_remote_state ();
8964 char *reply;
8965
8966 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8967 val);
8968 putpkt (rs->buf);
8969 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8970 if (*reply == '\0')
8971 error (_("Target does not support QDisableRandomization."));
8972 if (strcmp (reply, "OK") != 0)
8973 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8974 }
8975
8976 static int
8977 extended_remote_run (char *args)
8978 {
8979 struct remote_state *rs = get_remote_state ();
8980 int len;
8981 const char *remote_exec_file = get_remote_exec_file ();
8982
8983 /* If the user has disabled vRun support, or we have detected that
8984 support is not available, do not try it. */
8985 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8986 return -1;
8987
8988 strcpy (rs->buf, "vRun;");
8989 len = strlen (rs->buf);
8990
8991 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8992 error (_("Remote file name too long for run packet"));
8993 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8994 strlen (remote_exec_file));
8995
8996 gdb_assert (args != NULL);
8997 if (*args)
8998 {
8999 struct cleanup *back_to;
9000 int i;
9001 char **argv;
9002
9003 argv = gdb_buildargv (args);
9004 back_to = make_cleanup_freeargv (argv);
9005 for (i = 0; argv[i] != NULL; i++)
9006 {
9007 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9008 error (_("Argument list too long for run packet"));
9009 rs->buf[len++] = ';';
9010 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9011 strlen (argv[i]));
9012 }
9013 do_cleanups (back_to);
9014 }
9015
9016 rs->buf[len++] = '\0';
9017
9018 putpkt (rs->buf);
9019 getpkt (&rs->buf, &rs->buf_size, 0);
9020
9021 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9022 {
9023 case PACKET_OK:
9024 /* We have a wait response. All is well. */
9025 return 0;
9026 case PACKET_UNKNOWN:
9027 return -1;
9028 case PACKET_ERROR:
9029 if (remote_exec_file[0] == '\0')
9030 error (_("Running the default executable on the remote target failed; "
9031 "try \"set remote exec-file\"?"));
9032 else
9033 error (_("Running \"%s\" on the remote target failed"),
9034 remote_exec_file);
9035 default:
9036 gdb_assert_not_reached (_("bad switch"));
9037 }
9038 }
9039
9040 /* In the extended protocol we want to be able to do things like
9041 "run" and have them basically work as expected. So we need
9042 a special create_inferior function. We support changing the
9043 executable file and the command line arguments, but not the
9044 environment. */
9045
9046 static void
9047 extended_remote_create_inferior (struct target_ops *ops,
9048 char *exec_file, char *args,
9049 char **env, int from_tty)
9050 {
9051 int run_worked;
9052 char *stop_reply;
9053 struct remote_state *rs = get_remote_state ();
9054 const char *remote_exec_file = get_remote_exec_file ();
9055
9056 /* If running asynchronously, register the target file descriptor
9057 with the event loop. */
9058 if (target_can_async_p ())
9059 target_async (1);
9060
9061 /* Disable address space randomization if requested (and supported). */
9062 if (extended_remote_supports_disable_randomization (ops))
9063 extended_remote_disable_randomization (disable_randomization);
9064
9065 /* Now restart the remote server. */
9066 run_worked = extended_remote_run (args) != -1;
9067 if (!run_worked)
9068 {
9069 /* vRun was not supported. Fail if we need it to do what the
9070 user requested. */
9071 if (remote_exec_file[0])
9072 error (_("Remote target does not support \"set remote exec-file\""));
9073 if (args[0])
9074 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9075
9076 /* Fall back to "R". */
9077 extended_remote_restart ();
9078 }
9079
9080 if (!have_inferiors ())
9081 {
9082 /* Clean up from the last time we ran, before we mark the target
9083 running again. This will mark breakpoints uninserted, and
9084 get_offsets may insert breakpoints. */
9085 init_thread_list ();
9086 init_wait_for_inferior ();
9087 }
9088
9089 /* vRun's success return is a stop reply. */
9090 stop_reply = run_worked ? rs->buf : NULL;
9091 add_current_inferior_and_thread (stop_reply);
9092
9093 /* Get updated offsets, if the stub uses qOffsets. */
9094 get_offsets ();
9095 }
9096 \f
9097
9098 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9099 the list of conditions (in agent expression bytecode format), if any, the
9100 target needs to evaluate. The output is placed into the packet buffer
9101 started from BUF and ended at BUF_END. */
9102
9103 static int
9104 remote_add_target_side_condition (struct gdbarch *gdbarch,
9105 struct bp_target_info *bp_tgt, char *buf,
9106 char *buf_end)
9107 {
9108 struct agent_expr *aexpr = NULL;
9109 int i, ix;
9110 char *pkt;
9111 char *buf_start = buf;
9112
9113 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9114 return 0;
9115
9116 buf += strlen (buf);
9117 xsnprintf (buf, buf_end - buf, "%s", ";");
9118 buf++;
9119
9120 /* Send conditions to the target and free the vector. */
9121 for (ix = 0;
9122 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9123 ix++)
9124 {
9125 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9126 buf += strlen (buf);
9127 for (i = 0; i < aexpr->len; ++i)
9128 buf = pack_hex_byte (buf, aexpr->buf[i]);
9129 *buf = '\0';
9130 }
9131 return 0;
9132 }
9133
9134 static void
9135 remote_add_target_side_commands (struct gdbarch *gdbarch,
9136 struct bp_target_info *bp_tgt, char *buf)
9137 {
9138 struct agent_expr *aexpr = NULL;
9139 int i, ix;
9140
9141 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9142 return;
9143
9144 buf += strlen (buf);
9145
9146 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9147 buf += strlen (buf);
9148
9149 /* Concatenate all the agent expressions that are commands into the
9150 cmds parameter. */
9151 for (ix = 0;
9152 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9153 ix++)
9154 {
9155 sprintf (buf, "X%x,", aexpr->len);
9156 buf += strlen (buf);
9157 for (i = 0; i < aexpr->len; ++i)
9158 buf = pack_hex_byte (buf, aexpr->buf[i]);
9159 *buf = '\0';
9160 }
9161 }
9162
9163 /* Insert a breakpoint. On targets that have software breakpoint
9164 support, we ask the remote target to do the work; on targets
9165 which don't, we insert a traditional memory breakpoint. */
9166
9167 static int
9168 remote_insert_breakpoint (struct target_ops *ops,
9169 struct gdbarch *gdbarch,
9170 struct bp_target_info *bp_tgt)
9171 {
9172 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9173 If it succeeds, then set the support to PACKET_ENABLE. If it
9174 fails, and the user has explicitly requested the Z support then
9175 report an error, otherwise, mark it disabled and go on. */
9176
9177 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9178 {
9179 CORE_ADDR addr = bp_tgt->reqstd_address;
9180 struct remote_state *rs;
9181 char *p, *endbuf;
9182 int bpsize;
9183 struct condition_list *cond = NULL;
9184
9185 /* Make sure the remote is pointing at the right process, if
9186 necessary. */
9187 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9188 set_general_process ();
9189
9190 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9191
9192 rs = get_remote_state ();
9193 p = rs->buf;
9194 endbuf = rs->buf + get_remote_packet_size ();
9195
9196 *(p++) = 'Z';
9197 *(p++) = '0';
9198 *(p++) = ',';
9199 addr = (ULONGEST) remote_address_masked (addr);
9200 p += hexnumstr (p, addr);
9201 xsnprintf (p, endbuf - p, ",%d", bpsize);
9202
9203 if (remote_supports_cond_breakpoints (ops))
9204 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9205
9206 if (remote_can_run_breakpoint_commands (ops))
9207 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9208
9209 putpkt (rs->buf);
9210 getpkt (&rs->buf, &rs->buf_size, 0);
9211
9212 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9213 {
9214 case PACKET_ERROR:
9215 return -1;
9216 case PACKET_OK:
9217 bp_tgt->placed_address = addr;
9218 bp_tgt->placed_size = bpsize;
9219 return 0;
9220 case PACKET_UNKNOWN:
9221 break;
9222 }
9223 }
9224
9225 /* If this breakpoint has target-side commands but this stub doesn't
9226 support Z0 packets, throw error. */
9227 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9228 throw_error (NOT_SUPPORTED_ERROR, _("\
9229 Target doesn't support breakpoints that have target side commands."));
9230
9231 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9232 }
9233
9234 static int
9235 remote_remove_breakpoint (struct target_ops *ops,
9236 struct gdbarch *gdbarch,
9237 struct bp_target_info *bp_tgt)
9238 {
9239 CORE_ADDR addr = bp_tgt->placed_address;
9240 struct remote_state *rs = get_remote_state ();
9241
9242 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9243 {
9244 char *p = rs->buf;
9245 char *endbuf = rs->buf + get_remote_packet_size ();
9246
9247 /* Make sure the remote is pointing at the right process, if
9248 necessary. */
9249 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9250 set_general_process ();
9251
9252 *(p++) = 'z';
9253 *(p++) = '0';
9254 *(p++) = ',';
9255
9256 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9257 p += hexnumstr (p, addr);
9258 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9259
9260 putpkt (rs->buf);
9261 getpkt (&rs->buf, &rs->buf_size, 0);
9262
9263 return (rs->buf[0] == 'E');
9264 }
9265
9266 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9267 }
9268
9269 static enum Z_packet_type
9270 watchpoint_to_Z_packet (int type)
9271 {
9272 switch (type)
9273 {
9274 case hw_write:
9275 return Z_PACKET_WRITE_WP;
9276 break;
9277 case hw_read:
9278 return Z_PACKET_READ_WP;
9279 break;
9280 case hw_access:
9281 return Z_PACKET_ACCESS_WP;
9282 break;
9283 default:
9284 internal_error (__FILE__, __LINE__,
9285 _("hw_bp_to_z: bad watchpoint type %d"), type);
9286 }
9287 }
9288
9289 static int
9290 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9291 enum target_hw_bp_type type, struct expression *cond)
9292 {
9293 struct remote_state *rs = get_remote_state ();
9294 char *endbuf = rs->buf + get_remote_packet_size ();
9295 char *p;
9296 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9297
9298 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9299 return 1;
9300
9301 /* Make sure the remote is pointing at the right process, if
9302 necessary. */
9303 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9304 set_general_process ();
9305
9306 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9307 p = strchr (rs->buf, '\0');
9308 addr = remote_address_masked (addr);
9309 p += hexnumstr (p, (ULONGEST) addr);
9310 xsnprintf (p, endbuf - p, ",%x", len);
9311
9312 putpkt (rs->buf);
9313 getpkt (&rs->buf, &rs->buf_size, 0);
9314
9315 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9316 {
9317 case PACKET_ERROR:
9318 return -1;
9319 case PACKET_UNKNOWN:
9320 return 1;
9321 case PACKET_OK:
9322 return 0;
9323 }
9324 internal_error (__FILE__, __LINE__,
9325 _("remote_insert_watchpoint: reached end of function"));
9326 }
9327
9328 static int
9329 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9330 CORE_ADDR start, int length)
9331 {
9332 CORE_ADDR diff = remote_address_masked (addr - start);
9333
9334 return diff < length;
9335 }
9336
9337
9338 static int
9339 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9340 enum target_hw_bp_type type, struct expression *cond)
9341 {
9342 struct remote_state *rs = get_remote_state ();
9343 char *endbuf = rs->buf + get_remote_packet_size ();
9344 char *p;
9345 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9346
9347 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9348 return -1;
9349
9350 /* Make sure the remote is pointing at the right process, if
9351 necessary. */
9352 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9353 set_general_process ();
9354
9355 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9356 p = strchr (rs->buf, '\0');
9357 addr = remote_address_masked (addr);
9358 p += hexnumstr (p, (ULONGEST) addr);
9359 xsnprintf (p, endbuf - p, ",%x", len);
9360 putpkt (rs->buf);
9361 getpkt (&rs->buf, &rs->buf_size, 0);
9362
9363 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9364 {
9365 case PACKET_ERROR:
9366 case PACKET_UNKNOWN:
9367 return -1;
9368 case PACKET_OK:
9369 return 0;
9370 }
9371 internal_error (__FILE__, __LINE__,
9372 _("remote_remove_watchpoint: reached end of function"));
9373 }
9374
9375
9376 int remote_hw_watchpoint_limit = -1;
9377 int remote_hw_watchpoint_length_limit = -1;
9378 int remote_hw_breakpoint_limit = -1;
9379
9380 static int
9381 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9382 CORE_ADDR addr, int len)
9383 {
9384 if (remote_hw_watchpoint_length_limit == 0)
9385 return 0;
9386 else if (remote_hw_watchpoint_length_limit < 0)
9387 return 1;
9388 else if (len <= remote_hw_watchpoint_length_limit)
9389 return 1;
9390 else
9391 return 0;
9392 }
9393
9394 static int
9395 remote_check_watch_resources (struct target_ops *self,
9396 enum bptype type, int cnt, int ot)
9397 {
9398 if (type == bp_hardware_breakpoint)
9399 {
9400 if (remote_hw_breakpoint_limit == 0)
9401 return 0;
9402 else if (remote_hw_breakpoint_limit < 0)
9403 return 1;
9404 else if (cnt <= remote_hw_breakpoint_limit)
9405 return 1;
9406 }
9407 else
9408 {
9409 if (remote_hw_watchpoint_limit == 0)
9410 return 0;
9411 else if (remote_hw_watchpoint_limit < 0)
9412 return 1;
9413 else if (ot)
9414 return -1;
9415 else if (cnt <= remote_hw_watchpoint_limit)
9416 return 1;
9417 }
9418 return -1;
9419 }
9420
9421 /* The to_stopped_by_sw_breakpoint method of target remote. */
9422
9423 static int
9424 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9425 {
9426 struct thread_info *thread = inferior_thread ();
9427
9428 return (thread->priv != NULL
9429 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9430 }
9431
9432 /* The to_supports_stopped_by_sw_breakpoint method of target
9433 remote. */
9434
9435 static int
9436 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9437 {
9438 struct remote_state *rs = get_remote_state ();
9439
9440 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9441 }
9442
9443 /* The to_stopped_by_hw_breakpoint method of target remote. */
9444
9445 static int
9446 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9447 {
9448 struct thread_info *thread = inferior_thread ();
9449
9450 return (thread->priv != NULL
9451 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9452 }
9453
9454 /* The to_supports_stopped_by_hw_breakpoint method of target
9455 remote. */
9456
9457 static int
9458 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9459 {
9460 struct remote_state *rs = get_remote_state ();
9461
9462 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9463 }
9464
9465 static int
9466 remote_stopped_by_watchpoint (struct target_ops *ops)
9467 {
9468 struct thread_info *thread = inferior_thread ();
9469
9470 return (thread->priv != NULL
9471 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9472 }
9473
9474 static int
9475 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9476 {
9477 struct thread_info *thread = inferior_thread ();
9478
9479 if (thread->priv != NULL
9480 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9481 {
9482 *addr_p = thread->priv->watch_data_address;
9483 return 1;
9484 }
9485
9486 return 0;
9487 }
9488
9489
9490 static int
9491 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9492 struct bp_target_info *bp_tgt)
9493 {
9494 CORE_ADDR addr = bp_tgt->reqstd_address;
9495 struct remote_state *rs;
9496 char *p, *endbuf;
9497 char *message;
9498 int bpsize;
9499
9500 /* The length field should be set to the size of a breakpoint
9501 instruction, even though we aren't inserting one ourselves. */
9502
9503 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9504
9505 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9506 return -1;
9507
9508 /* Make sure the remote is pointing at the right process, if
9509 necessary. */
9510 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9511 set_general_process ();
9512
9513 rs = get_remote_state ();
9514 p = rs->buf;
9515 endbuf = rs->buf + get_remote_packet_size ();
9516
9517 *(p++) = 'Z';
9518 *(p++) = '1';
9519 *(p++) = ',';
9520
9521 addr = remote_address_masked (addr);
9522 p += hexnumstr (p, (ULONGEST) addr);
9523 xsnprintf (p, endbuf - p, ",%x", bpsize);
9524
9525 if (remote_supports_cond_breakpoints (self))
9526 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9527
9528 if (remote_can_run_breakpoint_commands (self))
9529 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9530
9531 putpkt (rs->buf);
9532 getpkt (&rs->buf, &rs->buf_size, 0);
9533
9534 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9535 {
9536 case PACKET_ERROR:
9537 if (rs->buf[1] == '.')
9538 {
9539 message = strchr (rs->buf + 2, '.');
9540 if (message)
9541 error (_("Remote failure reply: %s"), message + 1);
9542 }
9543 return -1;
9544 case PACKET_UNKNOWN:
9545 return -1;
9546 case PACKET_OK:
9547 bp_tgt->placed_address = addr;
9548 bp_tgt->placed_size = bpsize;
9549 return 0;
9550 }
9551 internal_error (__FILE__, __LINE__,
9552 _("remote_insert_hw_breakpoint: reached end of function"));
9553 }
9554
9555
9556 static int
9557 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9558 struct bp_target_info *bp_tgt)
9559 {
9560 CORE_ADDR addr;
9561 struct remote_state *rs = get_remote_state ();
9562 char *p = rs->buf;
9563 char *endbuf = rs->buf + get_remote_packet_size ();
9564
9565 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9566 return -1;
9567
9568 /* Make sure the remote is pointing at the right process, if
9569 necessary. */
9570 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9571 set_general_process ();
9572
9573 *(p++) = 'z';
9574 *(p++) = '1';
9575 *(p++) = ',';
9576
9577 addr = remote_address_masked (bp_tgt->placed_address);
9578 p += hexnumstr (p, (ULONGEST) addr);
9579 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9580
9581 putpkt (rs->buf);
9582 getpkt (&rs->buf, &rs->buf_size, 0);
9583
9584 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9585 {
9586 case PACKET_ERROR:
9587 case PACKET_UNKNOWN:
9588 return -1;
9589 case PACKET_OK:
9590 return 0;
9591 }
9592 internal_error (__FILE__, __LINE__,
9593 _("remote_remove_hw_breakpoint: reached end of function"));
9594 }
9595
9596 /* Verify memory using the "qCRC:" request. */
9597
9598 static int
9599 remote_verify_memory (struct target_ops *ops,
9600 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9601 {
9602 struct remote_state *rs = get_remote_state ();
9603 unsigned long host_crc, target_crc;
9604 char *tmp;
9605
9606 /* It doesn't make sense to use qCRC if the remote target is
9607 connected but not running. */
9608 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9609 {
9610 enum packet_result result;
9611
9612 /* Make sure the remote is pointing at the right process. */
9613 set_general_process ();
9614
9615 /* FIXME: assumes lma can fit into long. */
9616 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9617 (long) lma, (long) size);
9618 putpkt (rs->buf);
9619
9620 /* Be clever; compute the host_crc before waiting for target
9621 reply. */
9622 host_crc = xcrc32 (data, size, 0xffffffff);
9623
9624 getpkt (&rs->buf, &rs->buf_size, 0);
9625
9626 result = packet_ok (rs->buf,
9627 &remote_protocol_packets[PACKET_qCRC]);
9628 if (result == PACKET_ERROR)
9629 return -1;
9630 else if (result == PACKET_OK)
9631 {
9632 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9633 target_crc = target_crc * 16 + fromhex (*tmp);
9634
9635 return (host_crc == target_crc);
9636 }
9637 }
9638
9639 return simple_verify_memory (ops, data, lma, size);
9640 }
9641
9642 /* compare-sections command
9643
9644 With no arguments, compares each loadable section in the exec bfd
9645 with the same memory range on the target, and reports mismatches.
9646 Useful for verifying the image on the target against the exec file. */
9647
9648 static void
9649 compare_sections_command (char *args, int from_tty)
9650 {
9651 asection *s;
9652 struct cleanup *old_chain;
9653 gdb_byte *sectdata;
9654 const char *sectname;
9655 bfd_size_type size;
9656 bfd_vma lma;
9657 int matched = 0;
9658 int mismatched = 0;
9659 int res;
9660 int read_only = 0;
9661
9662 if (!exec_bfd)
9663 error (_("command cannot be used without an exec file"));
9664
9665 /* Make sure the remote is pointing at the right process. */
9666 set_general_process ();
9667
9668 if (args != NULL && strcmp (args, "-r") == 0)
9669 {
9670 read_only = 1;
9671 args = NULL;
9672 }
9673
9674 for (s = exec_bfd->sections; s; s = s->next)
9675 {
9676 if (!(s->flags & SEC_LOAD))
9677 continue; /* Skip non-loadable section. */
9678
9679 if (read_only && (s->flags & SEC_READONLY) == 0)
9680 continue; /* Skip writeable sections */
9681
9682 size = bfd_get_section_size (s);
9683 if (size == 0)
9684 continue; /* Skip zero-length section. */
9685
9686 sectname = bfd_get_section_name (exec_bfd, s);
9687 if (args && strcmp (args, sectname) != 0)
9688 continue; /* Not the section selected by user. */
9689
9690 matched = 1; /* Do this section. */
9691 lma = s->lma;
9692
9693 sectdata = (gdb_byte *) xmalloc (size);
9694 old_chain = make_cleanup (xfree, sectdata);
9695 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9696
9697 res = target_verify_memory (sectdata, lma, size);
9698
9699 if (res == -1)
9700 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9701 paddress (target_gdbarch (), lma),
9702 paddress (target_gdbarch (), lma + size));
9703
9704 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9705 paddress (target_gdbarch (), lma),
9706 paddress (target_gdbarch (), lma + size));
9707 if (res)
9708 printf_filtered ("matched.\n");
9709 else
9710 {
9711 printf_filtered ("MIS-MATCHED!\n");
9712 mismatched++;
9713 }
9714
9715 do_cleanups (old_chain);
9716 }
9717 if (mismatched > 0)
9718 warning (_("One or more sections of the target image does not match\n\
9719 the loaded file\n"));
9720 if (args && !matched)
9721 printf_filtered (_("No loaded section named '%s'.\n"), args);
9722 }
9723
9724 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9725 into remote target. The number of bytes written to the remote
9726 target is returned, or -1 for error. */
9727
9728 static enum target_xfer_status
9729 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9730 const char *annex, const gdb_byte *writebuf,
9731 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9732 struct packet_config *packet)
9733 {
9734 int i, buf_len;
9735 ULONGEST n;
9736 struct remote_state *rs = get_remote_state ();
9737 int max_size = get_memory_write_packet_size ();
9738
9739 if (packet->support == PACKET_DISABLE)
9740 return TARGET_XFER_E_IO;
9741
9742 /* Insert header. */
9743 i = snprintf (rs->buf, max_size,
9744 "qXfer:%s:write:%s:%s:",
9745 object_name, annex ? annex : "",
9746 phex_nz (offset, sizeof offset));
9747 max_size -= (i + 1);
9748
9749 /* Escape as much data as fits into rs->buf. */
9750 buf_len = remote_escape_output
9751 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9752
9753 if (putpkt_binary (rs->buf, i + buf_len) < 0
9754 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9755 || packet_ok (rs->buf, packet) != PACKET_OK)
9756 return TARGET_XFER_E_IO;
9757
9758 unpack_varlen_hex (rs->buf, &n);
9759
9760 *xfered_len = n;
9761 return TARGET_XFER_OK;
9762 }
9763
9764 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9765 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9766 number of bytes read is returned, or 0 for EOF, or -1 for error.
9767 The number of bytes read may be less than LEN without indicating an
9768 EOF. PACKET is checked and updated to indicate whether the remote
9769 target supports this object. */
9770
9771 static enum target_xfer_status
9772 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9773 const char *annex,
9774 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9775 ULONGEST *xfered_len,
9776 struct packet_config *packet)
9777 {
9778 struct remote_state *rs = get_remote_state ();
9779 LONGEST i, n, packet_len;
9780
9781 if (packet->support == PACKET_DISABLE)
9782 return TARGET_XFER_E_IO;
9783
9784 /* Check whether we've cached an end-of-object packet that matches
9785 this request. */
9786 if (rs->finished_object)
9787 {
9788 if (strcmp (object_name, rs->finished_object) == 0
9789 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9790 && offset == rs->finished_offset)
9791 return TARGET_XFER_EOF;
9792
9793
9794 /* Otherwise, we're now reading something different. Discard
9795 the cache. */
9796 xfree (rs->finished_object);
9797 xfree (rs->finished_annex);
9798 rs->finished_object = NULL;
9799 rs->finished_annex = NULL;
9800 }
9801
9802 /* Request only enough to fit in a single packet. The actual data
9803 may not, since we don't know how much of it will need to be escaped;
9804 the target is free to respond with slightly less data. We subtract
9805 five to account for the response type and the protocol frame. */
9806 n = min (get_remote_packet_size () - 5, len);
9807 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9808 object_name, annex ? annex : "",
9809 phex_nz (offset, sizeof offset),
9810 phex_nz (n, sizeof n));
9811 i = putpkt (rs->buf);
9812 if (i < 0)
9813 return TARGET_XFER_E_IO;
9814
9815 rs->buf[0] = '\0';
9816 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9817 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9818 return TARGET_XFER_E_IO;
9819
9820 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9821 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9822
9823 /* 'm' means there is (or at least might be) more data after this
9824 batch. That does not make sense unless there's at least one byte
9825 of data in this reply. */
9826 if (rs->buf[0] == 'm' && packet_len == 1)
9827 error (_("Remote qXfer reply contained no data."));
9828
9829 /* Got some data. */
9830 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9831 packet_len - 1, readbuf, n);
9832
9833 /* 'l' is an EOF marker, possibly including a final block of data,
9834 or possibly empty. If we have the final block of a non-empty
9835 object, record this fact to bypass a subsequent partial read. */
9836 if (rs->buf[0] == 'l' && offset + i > 0)
9837 {
9838 rs->finished_object = xstrdup (object_name);
9839 rs->finished_annex = xstrdup (annex ? annex : "");
9840 rs->finished_offset = offset + i;
9841 }
9842
9843 if (i == 0)
9844 return TARGET_XFER_EOF;
9845 else
9846 {
9847 *xfered_len = i;
9848 return TARGET_XFER_OK;
9849 }
9850 }
9851
9852 static enum target_xfer_status
9853 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9854 const char *annex, gdb_byte *readbuf,
9855 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9856 ULONGEST *xfered_len)
9857 {
9858 struct remote_state *rs;
9859 int i;
9860 char *p2;
9861 char query_type;
9862 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9863
9864 set_remote_traceframe ();
9865 set_general_thread (inferior_ptid);
9866
9867 rs = get_remote_state ();
9868
9869 /* Handle memory using the standard memory routines. */
9870 if (object == TARGET_OBJECT_MEMORY)
9871 {
9872 /* If the remote target is connected but not running, we should
9873 pass this request down to a lower stratum (e.g. the executable
9874 file). */
9875 if (!target_has_execution)
9876 return TARGET_XFER_EOF;
9877
9878 if (writebuf != NULL)
9879 return remote_write_bytes (offset, writebuf, len, unit_size,
9880 xfered_len);
9881 else
9882 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9883 xfered_len);
9884 }
9885
9886 /* Handle SPU memory using qxfer packets. */
9887 if (object == TARGET_OBJECT_SPU)
9888 {
9889 if (readbuf)
9890 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9891 xfered_len, &remote_protocol_packets
9892 [PACKET_qXfer_spu_read]);
9893 else
9894 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9895 xfered_len, &remote_protocol_packets
9896 [PACKET_qXfer_spu_write]);
9897 }
9898
9899 /* Handle extra signal info using qxfer packets. */
9900 if (object == TARGET_OBJECT_SIGNAL_INFO)
9901 {
9902 if (readbuf)
9903 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9904 xfered_len, &remote_protocol_packets
9905 [PACKET_qXfer_siginfo_read]);
9906 else
9907 return remote_write_qxfer (ops, "siginfo", annex,
9908 writebuf, offset, len, xfered_len,
9909 &remote_protocol_packets
9910 [PACKET_qXfer_siginfo_write]);
9911 }
9912
9913 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9914 {
9915 if (readbuf)
9916 return remote_read_qxfer (ops, "statictrace", annex,
9917 readbuf, offset, len, xfered_len,
9918 &remote_protocol_packets
9919 [PACKET_qXfer_statictrace_read]);
9920 else
9921 return TARGET_XFER_E_IO;
9922 }
9923
9924 /* Only handle flash writes. */
9925 if (writebuf != NULL)
9926 {
9927 LONGEST xfered;
9928
9929 switch (object)
9930 {
9931 case TARGET_OBJECT_FLASH:
9932 return remote_flash_write (ops, offset, len, xfered_len,
9933 writebuf);
9934
9935 default:
9936 return TARGET_XFER_E_IO;
9937 }
9938 }
9939
9940 /* Map pre-existing objects onto letters. DO NOT do this for new
9941 objects!!! Instead specify new query packets. */
9942 switch (object)
9943 {
9944 case TARGET_OBJECT_AVR:
9945 query_type = 'R';
9946 break;
9947
9948 case TARGET_OBJECT_AUXV:
9949 gdb_assert (annex == NULL);
9950 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9951 xfered_len,
9952 &remote_protocol_packets[PACKET_qXfer_auxv]);
9953
9954 case TARGET_OBJECT_AVAILABLE_FEATURES:
9955 return remote_read_qxfer
9956 (ops, "features", annex, readbuf, offset, len, xfered_len,
9957 &remote_protocol_packets[PACKET_qXfer_features]);
9958
9959 case TARGET_OBJECT_LIBRARIES:
9960 return remote_read_qxfer
9961 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9962 &remote_protocol_packets[PACKET_qXfer_libraries]);
9963
9964 case TARGET_OBJECT_LIBRARIES_SVR4:
9965 return remote_read_qxfer
9966 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9967 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9968
9969 case TARGET_OBJECT_MEMORY_MAP:
9970 gdb_assert (annex == NULL);
9971 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9972 xfered_len,
9973 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9974
9975 case TARGET_OBJECT_OSDATA:
9976 /* Should only get here if we're connected. */
9977 gdb_assert (rs->remote_desc);
9978 return remote_read_qxfer
9979 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9980 &remote_protocol_packets[PACKET_qXfer_osdata]);
9981
9982 case TARGET_OBJECT_THREADS:
9983 gdb_assert (annex == NULL);
9984 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9985 xfered_len,
9986 &remote_protocol_packets[PACKET_qXfer_threads]);
9987
9988 case TARGET_OBJECT_TRACEFRAME_INFO:
9989 gdb_assert (annex == NULL);
9990 return remote_read_qxfer
9991 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9992 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9993
9994 case TARGET_OBJECT_FDPIC:
9995 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9996 xfered_len,
9997 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9998
9999 case TARGET_OBJECT_OPENVMS_UIB:
10000 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10001 xfered_len,
10002 &remote_protocol_packets[PACKET_qXfer_uib]);
10003
10004 case TARGET_OBJECT_BTRACE:
10005 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10006 xfered_len,
10007 &remote_protocol_packets[PACKET_qXfer_btrace]);
10008
10009 case TARGET_OBJECT_BTRACE_CONF:
10010 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10011 len, xfered_len,
10012 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10013
10014 case TARGET_OBJECT_EXEC_FILE:
10015 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10016 len, xfered_len,
10017 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10018
10019 default:
10020 return TARGET_XFER_E_IO;
10021 }
10022
10023 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10024 large enough let the caller deal with it. */
10025 if (len < get_remote_packet_size ())
10026 return TARGET_XFER_E_IO;
10027 len = get_remote_packet_size ();
10028
10029 /* Except for querying the minimum buffer size, target must be open. */
10030 if (!rs->remote_desc)
10031 error (_("remote query is only available after target open"));
10032
10033 gdb_assert (annex != NULL);
10034 gdb_assert (readbuf != NULL);
10035
10036 p2 = rs->buf;
10037 *p2++ = 'q';
10038 *p2++ = query_type;
10039
10040 /* We used one buffer char for the remote protocol q command and
10041 another for the query type. As the remote protocol encapsulation
10042 uses 4 chars plus one extra in case we are debugging
10043 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10044 string. */
10045 i = 0;
10046 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10047 {
10048 /* Bad caller may have sent forbidden characters. */
10049 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10050 *p2++ = annex[i];
10051 i++;
10052 }
10053 *p2 = '\0';
10054 gdb_assert (annex[i] == '\0');
10055
10056 i = putpkt (rs->buf);
10057 if (i < 0)
10058 return TARGET_XFER_E_IO;
10059
10060 getpkt (&rs->buf, &rs->buf_size, 0);
10061 strcpy ((char *) readbuf, rs->buf);
10062
10063 *xfered_len = strlen ((char *) readbuf);
10064 return TARGET_XFER_OK;
10065 }
10066
10067 static int
10068 remote_search_memory (struct target_ops* ops,
10069 CORE_ADDR start_addr, ULONGEST search_space_len,
10070 const gdb_byte *pattern, ULONGEST pattern_len,
10071 CORE_ADDR *found_addrp)
10072 {
10073 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10074 struct remote_state *rs = get_remote_state ();
10075 int max_size = get_memory_write_packet_size ();
10076 struct packet_config *packet =
10077 &remote_protocol_packets[PACKET_qSearch_memory];
10078 /* Number of packet bytes used to encode the pattern;
10079 this could be more than PATTERN_LEN due to escape characters. */
10080 int escaped_pattern_len;
10081 /* Amount of pattern that was encodable in the packet. */
10082 int used_pattern_len;
10083 int i;
10084 int found;
10085 ULONGEST found_addr;
10086
10087 /* Don't go to the target if we don't have to.
10088 This is done before checking packet->support to avoid the possibility that
10089 a success for this edge case means the facility works in general. */
10090 if (pattern_len > search_space_len)
10091 return 0;
10092 if (pattern_len == 0)
10093 {
10094 *found_addrp = start_addr;
10095 return 1;
10096 }
10097
10098 /* If we already know the packet isn't supported, fall back to the simple
10099 way of searching memory. */
10100
10101 if (packet_config_support (packet) == PACKET_DISABLE)
10102 {
10103 /* Target doesn't provided special support, fall back and use the
10104 standard support (copy memory and do the search here). */
10105 return simple_search_memory (ops, start_addr, search_space_len,
10106 pattern, pattern_len, found_addrp);
10107 }
10108
10109 /* Make sure the remote is pointing at the right process. */
10110 set_general_process ();
10111
10112 /* Insert header. */
10113 i = snprintf (rs->buf, max_size,
10114 "qSearch:memory:%s;%s;",
10115 phex_nz (start_addr, addr_size),
10116 phex_nz (search_space_len, sizeof (search_space_len)));
10117 max_size -= (i + 1);
10118
10119 /* Escape as much data as fits into rs->buf. */
10120 escaped_pattern_len =
10121 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10122 &used_pattern_len, max_size);
10123
10124 /* Bail if the pattern is too large. */
10125 if (used_pattern_len != pattern_len)
10126 error (_("Pattern is too large to transmit to remote target."));
10127
10128 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10129 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10130 || packet_ok (rs->buf, packet) != PACKET_OK)
10131 {
10132 /* The request may not have worked because the command is not
10133 supported. If so, fall back to the simple way. */
10134 if (packet->support == PACKET_DISABLE)
10135 {
10136 return simple_search_memory (ops, start_addr, search_space_len,
10137 pattern, pattern_len, found_addrp);
10138 }
10139 return -1;
10140 }
10141
10142 if (rs->buf[0] == '0')
10143 found = 0;
10144 else if (rs->buf[0] == '1')
10145 {
10146 found = 1;
10147 if (rs->buf[1] != ',')
10148 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10149 unpack_varlen_hex (rs->buf + 2, &found_addr);
10150 *found_addrp = found_addr;
10151 }
10152 else
10153 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10154
10155 return found;
10156 }
10157
10158 static void
10159 remote_rcmd (struct target_ops *self, const char *command,
10160 struct ui_file *outbuf)
10161 {
10162 struct remote_state *rs = get_remote_state ();
10163 char *p = rs->buf;
10164
10165 if (!rs->remote_desc)
10166 error (_("remote rcmd is only available after target open"));
10167
10168 /* Send a NULL command across as an empty command. */
10169 if (command == NULL)
10170 command = "";
10171
10172 /* The query prefix. */
10173 strcpy (rs->buf, "qRcmd,");
10174 p = strchr (rs->buf, '\0');
10175
10176 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10177 > get_remote_packet_size ())
10178 error (_("\"monitor\" command ``%s'' is too long."), command);
10179
10180 /* Encode the actual command. */
10181 bin2hex ((const gdb_byte *) command, p, strlen (command));
10182
10183 if (putpkt (rs->buf) < 0)
10184 error (_("Communication problem with target."));
10185
10186 /* get/display the response */
10187 while (1)
10188 {
10189 char *buf;
10190
10191 /* XXX - see also remote_get_noisy_reply(). */
10192 QUIT; /* Allow user to bail out with ^C. */
10193 rs->buf[0] = '\0';
10194 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10195 {
10196 /* Timeout. Continue to (try to) read responses.
10197 This is better than stopping with an error, assuming the stub
10198 is still executing the (long) monitor command.
10199 If needed, the user can interrupt gdb using C-c, obtaining
10200 an effect similar to stop on timeout. */
10201 continue;
10202 }
10203 buf = rs->buf;
10204 if (buf[0] == '\0')
10205 error (_("Target does not support this command."));
10206 if (buf[0] == 'O' && buf[1] != 'K')
10207 {
10208 remote_console_output (buf + 1); /* 'O' message from stub. */
10209 continue;
10210 }
10211 if (strcmp (buf, "OK") == 0)
10212 break;
10213 if (strlen (buf) == 3 && buf[0] == 'E'
10214 && isdigit (buf[1]) && isdigit (buf[2]))
10215 {
10216 error (_("Protocol error with Rcmd"));
10217 }
10218 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10219 {
10220 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10221
10222 fputc_unfiltered (c, outbuf);
10223 }
10224 break;
10225 }
10226 }
10227
10228 static VEC(mem_region_s) *
10229 remote_memory_map (struct target_ops *ops)
10230 {
10231 VEC(mem_region_s) *result = NULL;
10232 char *text = target_read_stralloc (&current_target,
10233 TARGET_OBJECT_MEMORY_MAP, NULL);
10234
10235 if (text)
10236 {
10237 struct cleanup *back_to = make_cleanup (xfree, text);
10238
10239 result = parse_memory_map (text);
10240 do_cleanups (back_to);
10241 }
10242
10243 return result;
10244 }
10245
10246 static void
10247 packet_command (char *args, int from_tty)
10248 {
10249 struct remote_state *rs = get_remote_state ();
10250
10251 if (!rs->remote_desc)
10252 error (_("command can only be used with remote target"));
10253
10254 if (!args)
10255 error (_("remote-packet command requires packet text as argument"));
10256
10257 puts_filtered ("sending: ");
10258 print_packet (args);
10259 puts_filtered ("\n");
10260 putpkt (args);
10261
10262 getpkt (&rs->buf, &rs->buf_size, 0);
10263 puts_filtered ("received: ");
10264 print_packet (rs->buf);
10265 puts_filtered ("\n");
10266 }
10267
10268 #if 0
10269 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10270
10271 static void display_thread_info (struct gdb_ext_thread_info *info);
10272
10273 static void threadset_test_cmd (char *cmd, int tty);
10274
10275 static void threadalive_test (char *cmd, int tty);
10276
10277 static void threadlist_test_cmd (char *cmd, int tty);
10278
10279 int get_and_display_threadinfo (threadref *ref);
10280
10281 static void threadinfo_test_cmd (char *cmd, int tty);
10282
10283 static int thread_display_step (threadref *ref, void *context);
10284
10285 static void threadlist_update_test_cmd (char *cmd, int tty);
10286
10287 static void init_remote_threadtests (void);
10288
10289 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10290
10291 static void
10292 threadset_test_cmd (char *cmd, int tty)
10293 {
10294 int sample_thread = SAMPLE_THREAD;
10295
10296 printf_filtered (_("Remote threadset test\n"));
10297 set_general_thread (sample_thread);
10298 }
10299
10300
10301 static void
10302 threadalive_test (char *cmd, int tty)
10303 {
10304 int sample_thread = SAMPLE_THREAD;
10305 int pid = ptid_get_pid (inferior_ptid);
10306 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10307
10308 if (remote_thread_alive (ptid))
10309 printf_filtered ("PASS: Thread alive test\n");
10310 else
10311 printf_filtered ("FAIL: Thread alive test\n");
10312 }
10313
10314 void output_threadid (char *title, threadref *ref);
10315
10316 void
10317 output_threadid (char *title, threadref *ref)
10318 {
10319 char hexid[20];
10320
10321 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10322 hexid[16] = 0;
10323 printf_filtered ("%s %s\n", title, (&hexid[0]));
10324 }
10325
10326 static void
10327 threadlist_test_cmd (char *cmd, int tty)
10328 {
10329 int startflag = 1;
10330 threadref nextthread;
10331 int done, result_count;
10332 threadref threadlist[3];
10333
10334 printf_filtered ("Remote Threadlist test\n");
10335 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10336 &result_count, &threadlist[0]))
10337 printf_filtered ("FAIL: threadlist test\n");
10338 else
10339 {
10340 threadref *scan = threadlist;
10341 threadref *limit = scan + result_count;
10342
10343 while (scan < limit)
10344 output_threadid (" thread ", scan++);
10345 }
10346 }
10347
10348 void
10349 display_thread_info (struct gdb_ext_thread_info *info)
10350 {
10351 output_threadid ("Threadid: ", &info->threadid);
10352 printf_filtered ("Name: %s\n ", info->shortname);
10353 printf_filtered ("State: %s\n", info->display);
10354 printf_filtered ("other: %s\n\n", info->more_display);
10355 }
10356
10357 int
10358 get_and_display_threadinfo (threadref *ref)
10359 {
10360 int result;
10361 int set;
10362 struct gdb_ext_thread_info threadinfo;
10363
10364 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10365 | TAG_MOREDISPLAY | TAG_DISPLAY;
10366 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10367 display_thread_info (&threadinfo);
10368 return result;
10369 }
10370
10371 static void
10372 threadinfo_test_cmd (char *cmd, int tty)
10373 {
10374 int athread = SAMPLE_THREAD;
10375 threadref thread;
10376 int set;
10377
10378 int_to_threadref (&thread, athread);
10379 printf_filtered ("Remote Threadinfo test\n");
10380 if (!get_and_display_threadinfo (&thread))
10381 printf_filtered ("FAIL cannot get thread info\n");
10382 }
10383
10384 static int
10385 thread_display_step (threadref *ref, void *context)
10386 {
10387 /* output_threadid(" threadstep ",ref); *//* simple test */
10388 return get_and_display_threadinfo (ref);
10389 }
10390
10391 static void
10392 threadlist_update_test_cmd (char *cmd, int tty)
10393 {
10394 printf_filtered ("Remote Threadlist update test\n");
10395 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10396 }
10397
10398 static void
10399 init_remote_threadtests (void)
10400 {
10401 add_com ("tlist", class_obscure, threadlist_test_cmd,
10402 _("Fetch and print the remote list of "
10403 "thread identifiers, one pkt only"));
10404 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10405 _("Fetch and display info about one thread"));
10406 add_com ("tset", class_obscure, threadset_test_cmd,
10407 _("Test setting to a different thread"));
10408 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10409 _("Iterate through updating all remote thread info"));
10410 add_com ("talive", class_obscure, threadalive_test,
10411 _(" Remote thread alive test "));
10412 }
10413
10414 #endif /* 0 */
10415
10416 /* Convert a thread ID to a string. Returns the string in a static
10417 buffer. */
10418
10419 static char *
10420 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10421 {
10422 static char buf[64];
10423 struct remote_state *rs = get_remote_state ();
10424
10425 if (ptid_equal (ptid, null_ptid))
10426 return normal_pid_to_str (ptid);
10427 else if (ptid_is_pid (ptid))
10428 {
10429 /* Printing an inferior target id. */
10430
10431 /* When multi-process extensions are off, there's no way in the
10432 remote protocol to know the remote process id, if there's any
10433 at all. There's one exception --- when we're connected with
10434 target extended-remote, and we manually attached to a process
10435 with "attach PID". We don't record anywhere a flag that
10436 allows us to distinguish that case from the case of
10437 connecting with extended-remote and the stub already being
10438 attached to a process, and reporting yes to qAttached, hence
10439 no smart special casing here. */
10440 if (!remote_multi_process_p (rs))
10441 {
10442 xsnprintf (buf, sizeof buf, "Remote target");
10443 return buf;
10444 }
10445
10446 return normal_pid_to_str (ptid);
10447 }
10448 else
10449 {
10450 if (ptid_equal (magic_null_ptid, ptid))
10451 xsnprintf (buf, sizeof buf, "Thread <main>");
10452 else if (rs->extended && remote_multi_process_p (rs))
10453 if (ptid_get_lwp (ptid) == 0)
10454 return normal_pid_to_str (ptid);
10455 else
10456 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10457 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10458 else
10459 xsnprintf (buf, sizeof buf, "Thread %ld",
10460 ptid_get_lwp (ptid));
10461 return buf;
10462 }
10463 }
10464
10465 /* Get the address of the thread local variable in OBJFILE which is
10466 stored at OFFSET within the thread local storage for thread PTID. */
10467
10468 static CORE_ADDR
10469 remote_get_thread_local_address (struct target_ops *ops,
10470 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10471 {
10472 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10473 {
10474 struct remote_state *rs = get_remote_state ();
10475 char *p = rs->buf;
10476 char *endp = rs->buf + get_remote_packet_size ();
10477 enum packet_result result;
10478
10479 strcpy (p, "qGetTLSAddr:");
10480 p += strlen (p);
10481 p = write_ptid (p, endp, ptid);
10482 *p++ = ',';
10483 p += hexnumstr (p, offset);
10484 *p++ = ',';
10485 p += hexnumstr (p, lm);
10486 *p++ = '\0';
10487
10488 putpkt (rs->buf);
10489 getpkt (&rs->buf, &rs->buf_size, 0);
10490 result = packet_ok (rs->buf,
10491 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10492 if (result == PACKET_OK)
10493 {
10494 ULONGEST result;
10495
10496 unpack_varlen_hex (rs->buf, &result);
10497 return result;
10498 }
10499 else if (result == PACKET_UNKNOWN)
10500 throw_error (TLS_GENERIC_ERROR,
10501 _("Remote target doesn't support qGetTLSAddr packet"));
10502 else
10503 throw_error (TLS_GENERIC_ERROR,
10504 _("Remote target failed to process qGetTLSAddr request"));
10505 }
10506 else
10507 throw_error (TLS_GENERIC_ERROR,
10508 _("TLS not supported or disabled on this target"));
10509 /* Not reached. */
10510 return 0;
10511 }
10512
10513 /* Provide thread local base, i.e. Thread Information Block address.
10514 Returns 1 if ptid is found and thread_local_base is non zero. */
10515
10516 static int
10517 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10518 {
10519 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10520 {
10521 struct remote_state *rs = get_remote_state ();
10522 char *p = rs->buf;
10523 char *endp = rs->buf + get_remote_packet_size ();
10524 enum packet_result result;
10525
10526 strcpy (p, "qGetTIBAddr:");
10527 p += strlen (p);
10528 p = write_ptid (p, endp, ptid);
10529 *p++ = '\0';
10530
10531 putpkt (rs->buf);
10532 getpkt (&rs->buf, &rs->buf_size, 0);
10533 result = packet_ok (rs->buf,
10534 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10535 if (result == PACKET_OK)
10536 {
10537 ULONGEST result;
10538
10539 unpack_varlen_hex (rs->buf, &result);
10540 if (addr)
10541 *addr = (CORE_ADDR) result;
10542 return 1;
10543 }
10544 else if (result == PACKET_UNKNOWN)
10545 error (_("Remote target doesn't support qGetTIBAddr packet"));
10546 else
10547 error (_("Remote target failed to process qGetTIBAddr request"));
10548 }
10549 else
10550 error (_("qGetTIBAddr not supported or disabled on this target"));
10551 /* Not reached. */
10552 return 0;
10553 }
10554
10555 /* Support for inferring a target description based on the current
10556 architecture and the size of a 'g' packet. While the 'g' packet
10557 can have any size (since optional registers can be left off the
10558 end), some sizes are easily recognizable given knowledge of the
10559 approximate architecture. */
10560
10561 struct remote_g_packet_guess
10562 {
10563 int bytes;
10564 const struct target_desc *tdesc;
10565 };
10566 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10567 DEF_VEC_O(remote_g_packet_guess_s);
10568
10569 struct remote_g_packet_data
10570 {
10571 VEC(remote_g_packet_guess_s) *guesses;
10572 };
10573
10574 static struct gdbarch_data *remote_g_packet_data_handle;
10575
10576 static void *
10577 remote_g_packet_data_init (struct obstack *obstack)
10578 {
10579 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10580 }
10581
10582 void
10583 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10584 const struct target_desc *tdesc)
10585 {
10586 struct remote_g_packet_data *data
10587 = ((struct remote_g_packet_data *)
10588 gdbarch_data (gdbarch, remote_g_packet_data_handle));
10589 struct remote_g_packet_guess new_guess, *guess;
10590 int ix;
10591
10592 gdb_assert (tdesc != NULL);
10593
10594 for (ix = 0;
10595 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10596 ix++)
10597 if (guess->bytes == bytes)
10598 internal_error (__FILE__, __LINE__,
10599 _("Duplicate g packet description added for size %d"),
10600 bytes);
10601
10602 new_guess.bytes = bytes;
10603 new_guess.tdesc = tdesc;
10604 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10605 }
10606
10607 /* Return 1 if remote_read_description would do anything on this target
10608 and architecture, 0 otherwise. */
10609
10610 static int
10611 remote_read_description_p (struct target_ops *target)
10612 {
10613 struct remote_g_packet_data *data
10614 = ((struct remote_g_packet_data *)
10615 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10616
10617 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10618 return 1;
10619
10620 return 0;
10621 }
10622
10623 static const struct target_desc *
10624 remote_read_description (struct target_ops *target)
10625 {
10626 struct remote_g_packet_data *data
10627 = ((struct remote_g_packet_data *)
10628 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10629
10630 /* Do not try this during initial connection, when we do not know
10631 whether there is a running but stopped thread. */
10632 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10633 return target->beneath->to_read_description (target->beneath);
10634
10635 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10636 {
10637 struct remote_g_packet_guess *guess;
10638 int ix;
10639 int bytes = send_g_packet ();
10640
10641 for (ix = 0;
10642 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10643 ix++)
10644 if (guess->bytes == bytes)
10645 return guess->tdesc;
10646
10647 /* We discard the g packet. A minor optimization would be to
10648 hold on to it, and fill the register cache once we have selected
10649 an architecture, but it's too tricky to do safely. */
10650 }
10651
10652 return target->beneath->to_read_description (target->beneath);
10653 }
10654
10655 /* Remote file transfer support. This is host-initiated I/O, not
10656 target-initiated; for target-initiated, see remote-fileio.c. */
10657
10658 /* If *LEFT is at least the length of STRING, copy STRING to
10659 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10660 decrease *LEFT. Otherwise raise an error. */
10661
10662 static void
10663 remote_buffer_add_string (char **buffer, int *left, char *string)
10664 {
10665 int len = strlen (string);
10666
10667 if (len > *left)
10668 error (_("Packet too long for target."));
10669
10670 memcpy (*buffer, string, len);
10671 *buffer += len;
10672 *left -= len;
10673
10674 /* NUL-terminate the buffer as a convenience, if there is
10675 room. */
10676 if (*left)
10677 **buffer = '\0';
10678 }
10679
10680 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10681 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10682 decrease *LEFT. Otherwise raise an error. */
10683
10684 static void
10685 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10686 int len)
10687 {
10688 if (2 * len > *left)
10689 error (_("Packet too long for target."));
10690
10691 bin2hex (bytes, *buffer, len);
10692 *buffer += 2 * len;
10693 *left -= 2 * len;
10694
10695 /* NUL-terminate the buffer as a convenience, if there is
10696 room. */
10697 if (*left)
10698 **buffer = '\0';
10699 }
10700
10701 /* If *LEFT is large enough, convert VALUE to hex and add it to
10702 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10703 decrease *LEFT. Otherwise raise an error. */
10704
10705 static void
10706 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10707 {
10708 int len = hexnumlen (value);
10709
10710 if (len > *left)
10711 error (_("Packet too long for target."));
10712
10713 hexnumstr (*buffer, value);
10714 *buffer += len;
10715 *left -= len;
10716
10717 /* NUL-terminate the buffer as a convenience, if there is
10718 room. */
10719 if (*left)
10720 **buffer = '\0';
10721 }
10722
10723 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10724 value, *REMOTE_ERRNO to the remote error number or zero if none
10725 was included, and *ATTACHMENT to point to the start of the annex
10726 if any. The length of the packet isn't needed here; there may
10727 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10728
10729 Return 0 if the packet could be parsed, -1 if it could not. If
10730 -1 is returned, the other variables may not be initialized. */
10731
10732 static int
10733 remote_hostio_parse_result (char *buffer, int *retcode,
10734 int *remote_errno, char **attachment)
10735 {
10736 char *p, *p2;
10737
10738 *remote_errno = 0;
10739 *attachment = NULL;
10740
10741 if (buffer[0] != 'F')
10742 return -1;
10743
10744 errno = 0;
10745 *retcode = strtol (&buffer[1], &p, 16);
10746 if (errno != 0 || p == &buffer[1])
10747 return -1;
10748
10749 /* Check for ",errno". */
10750 if (*p == ',')
10751 {
10752 errno = 0;
10753 *remote_errno = strtol (p + 1, &p2, 16);
10754 if (errno != 0 || p + 1 == p2)
10755 return -1;
10756 p = p2;
10757 }
10758
10759 /* Check for ";attachment". If there is no attachment, the
10760 packet should end here. */
10761 if (*p == ';')
10762 {
10763 *attachment = p + 1;
10764 return 0;
10765 }
10766 else if (*p == '\0')
10767 return 0;
10768 else
10769 return -1;
10770 }
10771
10772 /* Send a prepared I/O packet to the target and read its response.
10773 The prepared packet is in the global RS->BUF before this function
10774 is called, and the answer is there when we return.
10775
10776 COMMAND_BYTES is the length of the request to send, which may include
10777 binary data. WHICH_PACKET is the packet configuration to check
10778 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10779 is set to the error number and -1 is returned. Otherwise the value
10780 returned by the function is returned.
10781
10782 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10783 attachment is expected; an error will be reported if there's a
10784 mismatch. If one is found, *ATTACHMENT will be set to point into
10785 the packet buffer and *ATTACHMENT_LEN will be set to the
10786 attachment's length. */
10787
10788 static int
10789 remote_hostio_send_command (int command_bytes, int which_packet,
10790 int *remote_errno, char **attachment,
10791 int *attachment_len)
10792 {
10793 struct remote_state *rs = get_remote_state ();
10794 int ret, bytes_read;
10795 char *attachment_tmp;
10796
10797 if (!rs->remote_desc
10798 || packet_support (which_packet) == PACKET_DISABLE)
10799 {
10800 *remote_errno = FILEIO_ENOSYS;
10801 return -1;
10802 }
10803
10804 putpkt_binary (rs->buf, command_bytes);
10805 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10806
10807 /* If it timed out, something is wrong. Don't try to parse the
10808 buffer. */
10809 if (bytes_read < 0)
10810 {
10811 *remote_errno = FILEIO_EINVAL;
10812 return -1;
10813 }
10814
10815 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10816 {
10817 case PACKET_ERROR:
10818 *remote_errno = FILEIO_EINVAL;
10819 return -1;
10820 case PACKET_UNKNOWN:
10821 *remote_errno = FILEIO_ENOSYS;
10822 return -1;
10823 case PACKET_OK:
10824 break;
10825 }
10826
10827 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10828 &attachment_tmp))
10829 {
10830 *remote_errno = FILEIO_EINVAL;
10831 return -1;
10832 }
10833
10834 /* Make sure we saw an attachment if and only if we expected one. */
10835 if ((attachment_tmp == NULL && attachment != NULL)
10836 || (attachment_tmp != NULL && attachment == NULL))
10837 {
10838 *remote_errno = FILEIO_EINVAL;
10839 return -1;
10840 }
10841
10842 /* If an attachment was found, it must point into the packet buffer;
10843 work out how many bytes there were. */
10844 if (attachment_tmp != NULL)
10845 {
10846 *attachment = attachment_tmp;
10847 *attachment_len = bytes_read - (*attachment - rs->buf);
10848 }
10849
10850 return ret;
10851 }
10852
10853 /* Invalidate the readahead cache. */
10854
10855 static void
10856 readahead_cache_invalidate (void)
10857 {
10858 struct remote_state *rs = get_remote_state ();
10859
10860 rs->readahead_cache.fd = -1;
10861 }
10862
10863 /* Invalidate the readahead cache if it is holding data for FD. */
10864
10865 static void
10866 readahead_cache_invalidate_fd (int fd)
10867 {
10868 struct remote_state *rs = get_remote_state ();
10869
10870 if (rs->readahead_cache.fd == fd)
10871 rs->readahead_cache.fd = -1;
10872 }
10873
10874 /* Set the filesystem remote_hostio functions that take FILENAME
10875 arguments will use. Return 0 on success, or -1 if an error
10876 occurs (and set *REMOTE_ERRNO). */
10877
10878 static int
10879 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10880 {
10881 struct remote_state *rs = get_remote_state ();
10882 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10883 char *p = rs->buf;
10884 int left = get_remote_packet_size () - 1;
10885 char arg[9];
10886 int ret;
10887
10888 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10889 return 0;
10890
10891 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10892 return 0;
10893
10894 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10895
10896 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10897 remote_buffer_add_string (&p, &left, arg);
10898
10899 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10900 remote_errno, NULL, NULL);
10901
10902 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10903 return 0;
10904
10905 if (ret == 0)
10906 rs->fs_pid = required_pid;
10907
10908 return ret;
10909 }
10910
10911 /* Implementation of to_fileio_open. */
10912
10913 static int
10914 remote_hostio_open (struct target_ops *self,
10915 struct inferior *inf, const char *filename,
10916 int flags, int mode, int warn_if_slow,
10917 int *remote_errno)
10918 {
10919 struct remote_state *rs = get_remote_state ();
10920 char *p = rs->buf;
10921 int left = get_remote_packet_size () - 1;
10922
10923 if (warn_if_slow)
10924 {
10925 static int warning_issued = 0;
10926
10927 printf_unfiltered (_("Reading %s from remote target...\n"),
10928 filename);
10929
10930 if (!warning_issued)
10931 {
10932 warning (_("File transfers from remote targets can be slow."
10933 " Use \"set sysroot\" to access files locally"
10934 " instead."));
10935 warning_issued = 1;
10936 }
10937 }
10938
10939 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10940 return -1;
10941
10942 remote_buffer_add_string (&p, &left, "vFile:open:");
10943
10944 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10945 strlen (filename));
10946 remote_buffer_add_string (&p, &left, ",");
10947
10948 remote_buffer_add_int (&p, &left, flags);
10949 remote_buffer_add_string (&p, &left, ",");
10950
10951 remote_buffer_add_int (&p, &left, mode);
10952
10953 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10954 remote_errno, NULL, NULL);
10955 }
10956
10957 /* Implementation of to_fileio_pwrite. */
10958
10959 static int
10960 remote_hostio_pwrite (struct target_ops *self,
10961 int fd, const gdb_byte *write_buf, int len,
10962 ULONGEST offset, int *remote_errno)
10963 {
10964 struct remote_state *rs = get_remote_state ();
10965 char *p = rs->buf;
10966 int left = get_remote_packet_size ();
10967 int out_len;
10968
10969 readahead_cache_invalidate_fd (fd);
10970
10971 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10972
10973 remote_buffer_add_int (&p, &left, fd);
10974 remote_buffer_add_string (&p, &left, ",");
10975
10976 remote_buffer_add_int (&p, &left, offset);
10977 remote_buffer_add_string (&p, &left, ",");
10978
10979 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10980 get_remote_packet_size () - (p - rs->buf));
10981
10982 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10983 remote_errno, NULL, NULL);
10984 }
10985
10986 /* Helper for the implementation of to_fileio_pread. Read the file
10987 from the remote side with vFile:pread. */
10988
10989 static int
10990 remote_hostio_pread_vFile (struct target_ops *self,
10991 int fd, gdb_byte *read_buf, int len,
10992 ULONGEST offset, int *remote_errno)
10993 {
10994 struct remote_state *rs = get_remote_state ();
10995 char *p = rs->buf;
10996 char *attachment;
10997 int left = get_remote_packet_size ();
10998 int ret, attachment_len;
10999 int read_len;
11000
11001 remote_buffer_add_string (&p, &left, "vFile:pread:");
11002
11003 remote_buffer_add_int (&p, &left, fd);
11004 remote_buffer_add_string (&p, &left, ",");
11005
11006 remote_buffer_add_int (&p, &left, len);
11007 remote_buffer_add_string (&p, &left, ",");
11008
11009 remote_buffer_add_int (&p, &left, offset);
11010
11011 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11012 remote_errno, &attachment,
11013 &attachment_len);
11014
11015 if (ret < 0)
11016 return ret;
11017
11018 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11019 read_buf, len);
11020 if (read_len != ret)
11021 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11022
11023 return ret;
11024 }
11025
11026 /* Serve pread from the readahead cache. Returns number of bytes
11027 read, or 0 if the request can't be served from the cache. */
11028
11029 static int
11030 remote_hostio_pread_from_cache (struct remote_state *rs,
11031 int fd, gdb_byte *read_buf, size_t len,
11032 ULONGEST offset)
11033 {
11034 struct readahead_cache *cache = &rs->readahead_cache;
11035
11036 if (cache->fd == fd
11037 && cache->offset <= offset
11038 && offset < cache->offset + cache->bufsize)
11039 {
11040 ULONGEST max = cache->offset + cache->bufsize;
11041
11042 if (offset + len > max)
11043 len = max - offset;
11044
11045 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11046 return len;
11047 }
11048
11049 return 0;
11050 }
11051
11052 /* Implementation of to_fileio_pread. */
11053
11054 static int
11055 remote_hostio_pread (struct target_ops *self,
11056 int fd, gdb_byte *read_buf, int len,
11057 ULONGEST offset, int *remote_errno)
11058 {
11059 int ret;
11060 struct remote_state *rs = get_remote_state ();
11061 struct readahead_cache *cache = &rs->readahead_cache;
11062
11063 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11064 if (ret > 0)
11065 {
11066 cache->hit_count++;
11067
11068 if (remote_debug)
11069 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11070 pulongest (cache->hit_count));
11071 return ret;
11072 }
11073
11074 cache->miss_count++;
11075 if (remote_debug)
11076 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11077 pulongest (cache->miss_count));
11078
11079 cache->fd = fd;
11080 cache->offset = offset;
11081 cache->bufsize = get_remote_packet_size ();
11082 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11083
11084 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11085 cache->offset, remote_errno);
11086 if (ret <= 0)
11087 {
11088 readahead_cache_invalidate_fd (fd);
11089 return ret;
11090 }
11091
11092 cache->bufsize = ret;
11093 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11094 }
11095
11096 /* Implementation of to_fileio_close. */
11097
11098 static int
11099 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11100 {
11101 struct remote_state *rs = get_remote_state ();
11102 char *p = rs->buf;
11103 int left = get_remote_packet_size () - 1;
11104
11105 readahead_cache_invalidate_fd (fd);
11106
11107 remote_buffer_add_string (&p, &left, "vFile:close:");
11108
11109 remote_buffer_add_int (&p, &left, fd);
11110
11111 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11112 remote_errno, NULL, NULL);
11113 }
11114
11115 /* Implementation of to_fileio_unlink. */
11116
11117 static int
11118 remote_hostio_unlink (struct target_ops *self,
11119 struct inferior *inf, const char *filename,
11120 int *remote_errno)
11121 {
11122 struct remote_state *rs = get_remote_state ();
11123 char *p = rs->buf;
11124 int left = get_remote_packet_size () - 1;
11125
11126 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11127 return -1;
11128
11129 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11130
11131 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11132 strlen (filename));
11133
11134 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11135 remote_errno, NULL, NULL);
11136 }
11137
11138 /* Implementation of to_fileio_readlink. */
11139
11140 static char *
11141 remote_hostio_readlink (struct target_ops *self,
11142 struct inferior *inf, const char *filename,
11143 int *remote_errno)
11144 {
11145 struct remote_state *rs = get_remote_state ();
11146 char *p = rs->buf;
11147 char *attachment;
11148 int left = get_remote_packet_size ();
11149 int len, attachment_len;
11150 int read_len;
11151 char *ret;
11152
11153 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11154 return NULL;
11155
11156 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11157
11158 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11159 strlen (filename));
11160
11161 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11162 remote_errno, &attachment,
11163 &attachment_len);
11164
11165 if (len < 0)
11166 return NULL;
11167
11168 ret = (char *) xmalloc (len + 1);
11169
11170 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11171 (gdb_byte *) ret, len);
11172 if (read_len != len)
11173 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11174
11175 ret[len] = '\0';
11176 return ret;
11177 }
11178
11179 /* Implementation of to_fileio_fstat. */
11180
11181 static int
11182 remote_hostio_fstat (struct target_ops *self,
11183 int fd, struct stat *st,
11184 int *remote_errno)
11185 {
11186 struct remote_state *rs = get_remote_state ();
11187 char *p = rs->buf;
11188 int left = get_remote_packet_size ();
11189 int attachment_len, ret;
11190 char *attachment;
11191 struct fio_stat fst;
11192 int read_len;
11193
11194 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11195
11196 remote_buffer_add_int (&p, &left, fd);
11197
11198 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11199 remote_errno, &attachment,
11200 &attachment_len);
11201 if (ret < 0)
11202 {
11203 if (*remote_errno != FILEIO_ENOSYS)
11204 return ret;
11205
11206 /* Strictly we should return -1, ENOSYS here, but when
11207 "set sysroot remote:" was implemented in August 2008
11208 BFD's need for a stat function was sidestepped with
11209 this hack. This was not remedied until March 2015
11210 so we retain the previous behavior to avoid breaking
11211 compatibility.
11212
11213 Note that the memset is a March 2015 addition; older
11214 GDBs set st_size *and nothing else* so the structure
11215 would have garbage in all other fields. This might
11216 break something but retaining the previous behavior
11217 here would be just too wrong. */
11218
11219 memset (st, 0, sizeof (struct stat));
11220 st->st_size = INT_MAX;
11221 return 0;
11222 }
11223
11224 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11225 (gdb_byte *) &fst, sizeof (fst));
11226
11227 if (read_len != ret)
11228 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11229
11230 if (read_len != sizeof (fst))
11231 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11232 read_len, (int) sizeof (fst));
11233
11234 remote_fileio_to_host_stat (&fst, st);
11235
11236 return 0;
11237 }
11238
11239 /* Implementation of to_filesystem_is_local. */
11240
11241 static int
11242 remote_filesystem_is_local (struct target_ops *self)
11243 {
11244 /* Valgrind GDB presents itself as a remote target but works
11245 on the local filesystem: it does not implement remote get
11246 and users are not expected to set a sysroot. To handle
11247 this case we treat the remote filesystem as local if the
11248 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11249 does not support vFile:open. */
11250 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11251 {
11252 enum packet_support ps = packet_support (PACKET_vFile_open);
11253
11254 if (ps == PACKET_SUPPORT_UNKNOWN)
11255 {
11256 int fd, remote_errno;
11257
11258 /* Try opening a file to probe support. The supplied
11259 filename is irrelevant, we only care about whether
11260 the stub recognizes the packet or not. */
11261 fd = remote_hostio_open (self, NULL, "just probing",
11262 FILEIO_O_RDONLY, 0700, 0,
11263 &remote_errno);
11264
11265 if (fd >= 0)
11266 remote_hostio_close (self, fd, &remote_errno);
11267
11268 ps = packet_support (PACKET_vFile_open);
11269 }
11270
11271 if (ps == PACKET_DISABLE)
11272 {
11273 static int warning_issued = 0;
11274
11275 if (!warning_issued)
11276 {
11277 warning (_("remote target does not support file"
11278 " transfer, attempting to access files"
11279 " from local filesystem."));
11280 warning_issued = 1;
11281 }
11282
11283 return 1;
11284 }
11285 }
11286
11287 return 0;
11288 }
11289
11290 static int
11291 remote_fileio_errno_to_host (int errnum)
11292 {
11293 switch (errnum)
11294 {
11295 case FILEIO_EPERM:
11296 return EPERM;
11297 case FILEIO_ENOENT:
11298 return ENOENT;
11299 case FILEIO_EINTR:
11300 return EINTR;
11301 case FILEIO_EIO:
11302 return EIO;
11303 case FILEIO_EBADF:
11304 return EBADF;
11305 case FILEIO_EACCES:
11306 return EACCES;
11307 case FILEIO_EFAULT:
11308 return EFAULT;
11309 case FILEIO_EBUSY:
11310 return EBUSY;
11311 case FILEIO_EEXIST:
11312 return EEXIST;
11313 case FILEIO_ENODEV:
11314 return ENODEV;
11315 case FILEIO_ENOTDIR:
11316 return ENOTDIR;
11317 case FILEIO_EISDIR:
11318 return EISDIR;
11319 case FILEIO_EINVAL:
11320 return EINVAL;
11321 case FILEIO_ENFILE:
11322 return ENFILE;
11323 case FILEIO_EMFILE:
11324 return EMFILE;
11325 case FILEIO_EFBIG:
11326 return EFBIG;
11327 case FILEIO_ENOSPC:
11328 return ENOSPC;
11329 case FILEIO_ESPIPE:
11330 return ESPIPE;
11331 case FILEIO_EROFS:
11332 return EROFS;
11333 case FILEIO_ENOSYS:
11334 return ENOSYS;
11335 case FILEIO_ENAMETOOLONG:
11336 return ENAMETOOLONG;
11337 }
11338 return -1;
11339 }
11340
11341 static char *
11342 remote_hostio_error (int errnum)
11343 {
11344 int host_error = remote_fileio_errno_to_host (errnum);
11345
11346 if (host_error == -1)
11347 error (_("Unknown remote I/O error %d"), errnum);
11348 else
11349 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11350 }
11351
11352 static void
11353 remote_hostio_close_cleanup (void *opaque)
11354 {
11355 int fd = *(int *) opaque;
11356 int remote_errno;
11357
11358 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11359 }
11360
11361 void
11362 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11363 {
11364 struct cleanup *back_to, *close_cleanup;
11365 int retcode, fd, remote_errno, bytes, io_size;
11366 FILE *file;
11367 gdb_byte *buffer;
11368 int bytes_in_buffer;
11369 int saw_eof;
11370 ULONGEST offset;
11371 struct remote_state *rs = get_remote_state ();
11372
11373 if (!rs->remote_desc)
11374 error (_("command can only be used with remote target"));
11375
11376 file = gdb_fopen_cloexec (local_file, "rb");
11377 if (file == NULL)
11378 perror_with_name (local_file);
11379 back_to = make_cleanup_fclose (file);
11380
11381 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11382 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11383 | FILEIO_O_TRUNC),
11384 0700, 0, &remote_errno);
11385 if (fd == -1)
11386 remote_hostio_error (remote_errno);
11387
11388 /* Send up to this many bytes at once. They won't all fit in the
11389 remote packet limit, so we'll transfer slightly fewer. */
11390 io_size = get_remote_packet_size ();
11391 buffer = (gdb_byte *) xmalloc (io_size);
11392 make_cleanup (xfree, buffer);
11393
11394 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11395
11396 bytes_in_buffer = 0;
11397 saw_eof = 0;
11398 offset = 0;
11399 while (bytes_in_buffer || !saw_eof)
11400 {
11401 if (!saw_eof)
11402 {
11403 bytes = fread (buffer + bytes_in_buffer, 1,
11404 io_size - bytes_in_buffer,
11405 file);
11406 if (bytes == 0)
11407 {
11408 if (ferror (file))
11409 error (_("Error reading %s."), local_file);
11410 else
11411 {
11412 /* EOF. Unless there is something still in the
11413 buffer from the last iteration, we are done. */
11414 saw_eof = 1;
11415 if (bytes_in_buffer == 0)
11416 break;
11417 }
11418 }
11419 }
11420 else
11421 bytes = 0;
11422
11423 bytes += bytes_in_buffer;
11424 bytes_in_buffer = 0;
11425
11426 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11427 fd, buffer, bytes,
11428 offset, &remote_errno);
11429
11430 if (retcode < 0)
11431 remote_hostio_error (remote_errno);
11432 else if (retcode == 0)
11433 error (_("Remote write of %d bytes returned 0!"), bytes);
11434 else if (retcode < bytes)
11435 {
11436 /* Short write. Save the rest of the read data for the next
11437 write. */
11438 bytes_in_buffer = bytes - retcode;
11439 memmove (buffer, buffer + retcode, bytes_in_buffer);
11440 }
11441
11442 offset += retcode;
11443 }
11444
11445 discard_cleanups (close_cleanup);
11446 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11447 remote_hostio_error (remote_errno);
11448
11449 if (from_tty)
11450 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11451 do_cleanups (back_to);
11452 }
11453
11454 void
11455 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11456 {
11457 struct cleanup *back_to, *close_cleanup;
11458 int fd, remote_errno, bytes, io_size;
11459 FILE *file;
11460 gdb_byte *buffer;
11461 ULONGEST offset;
11462 struct remote_state *rs = get_remote_state ();
11463
11464 if (!rs->remote_desc)
11465 error (_("command can only be used with remote target"));
11466
11467 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11468 remote_file, FILEIO_O_RDONLY, 0, 0,
11469 &remote_errno);
11470 if (fd == -1)
11471 remote_hostio_error (remote_errno);
11472
11473 file = gdb_fopen_cloexec (local_file, "wb");
11474 if (file == NULL)
11475 perror_with_name (local_file);
11476 back_to = make_cleanup_fclose (file);
11477
11478 /* Send up to this many bytes at once. They won't all fit in the
11479 remote packet limit, so we'll transfer slightly fewer. */
11480 io_size = get_remote_packet_size ();
11481 buffer = (gdb_byte *) xmalloc (io_size);
11482 make_cleanup (xfree, buffer);
11483
11484 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11485
11486 offset = 0;
11487 while (1)
11488 {
11489 bytes = remote_hostio_pread (find_target_at (process_stratum),
11490 fd, buffer, io_size, offset, &remote_errno);
11491 if (bytes == 0)
11492 /* Success, but no bytes, means end-of-file. */
11493 break;
11494 if (bytes == -1)
11495 remote_hostio_error (remote_errno);
11496
11497 offset += bytes;
11498
11499 bytes = fwrite (buffer, 1, bytes, file);
11500 if (bytes == 0)
11501 perror_with_name (local_file);
11502 }
11503
11504 discard_cleanups (close_cleanup);
11505 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11506 remote_hostio_error (remote_errno);
11507
11508 if (from_tty)
11509 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11510 do_cleanups (back_to);
11511 }
11512
11513 void
11514 remote_file_delete (const char *remote_file, int from_tty)
11515 {
11516 int retcode, remote_errno;
11517 struct remote_state *rs = get_remote_state ();
11518
11519 if (!rs->remote_desc)
11520 error (_("command can only be used with remote target"));
11521
11522 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11523 NULL, remote_file, &remote_errno);
11524 if (retcode == -1)
11525 remote_hostio_error (remote_errno);
11526
11527 if (from_tty)
11528 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11529 }
11530
11531 static void
11532 remote_put_command (char *args, int from_tty)
11533 {
11534 struct cleanup *back_to;
11535 char **argv;
11536
11537 if (args == NULL)
11538 error_no_arg (_("file to put"));
11539
11540 argv = gdb_buildargv (args);
11541 back_to = make_cleanup_freeargv (argv);
11542 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11543 error (_("Invalid parameters to remote put"));
11544
11545 remote_file_put (argv[0], argv[1], from_tty);
11546
11547 do_cleanups (back_to);
11548 }
11549
11550 static void
11551 remote_get_command (char *args, int from_tty)
11552 {
11553 struct cleanup *back_to;
11554 char **argv;
11555
11556 if (args == NULL)
11557 error_no_arg (_("file to get"));
11558
11559 argv = gdb_buildargv (args);
11560 back_to = make_cleanup_freeargv (argv);
11561 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11562 error (_("Invalid parameters to remote get"));
11563
11564 remote_file_get (argv[0], argv[1], from_tty);
11565
11566 do_cleanups (back_to);
11567 }
11568
11569 static void
11570 remote_delete_command (char *args, int from_tty)
11571 {
11572 struct cleanup *back_to;
11573 char **argv;
11574
11575 if (args == NULL)
11576 error_no_arg (_("file to delete"));
11577
11578 argv = gdb_buildargv (args);
11579 back_to = make_cleanup_freeargv (argv);
11580 if (argv[0] == NULL || argv[1] != NULL)
11581 error (_("Invalid parameters to remote delete"));
11582
11583 remote_file_delete (argv[0], from_tty);
11584
11585 do_cleanups (back_to);
11586 }
11587
11588 static void
11589 remote_command (char *args, int from_tty)
11590 {
11591 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11592 }
11593
11594 static int
11595 remote_can_execute_reverse (struct target_ops *self)
11596 {
11597 if (packet_support (PACKET_bs) == PACKET_ENABLE
11598 || packet_support (PACKET_bc) == PACKET_ENABLE)
11599 return 1;
11600 else
11601 return 0;
11602 }
11603
11604 static int
11605 remote_supports_non_stop (struct target_ops *self)
11606 {
11607 return 1;
11608 }
11609
11610 static int
11611 remote_supports_disable_randomization (struct target_ops *self)
11612 {
11613 /* Only supported in extended mode. */
11614 return 0;
11615 }
11616
11617 static int
11618 remote_supports_multi_process (struct target_ops *self)
11619 {
11620 struct remote_state *rs = get_remote_state ();
11621
11622 /* Only extended-remote handles being attached to multiple
11623 processes, even though plain remote can use the multi-process
11624 thread id extensions, so that GDB knows the target process's
11625 PID. */
11626 return rs->extended && remote_multi_process_p (rs);
11627 }
11628
11629 static int
11630 remote_supports_cond_tracepoints (void)
11631 {
11632 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11633 }
11634
11635 static int
11636 remote_supports_cond_breakpoints (struct target_ops *self)
11637 {
11638 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11639 }
11640
11641 static int
11642 remote_supports_fast_tracepoints (void)
11643 {
11644 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11645 }
11646
11647 static int
11648 remote_supports_static_tracepoints (void)
11649 {
11650 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11651 }
11652
11653 static int
11654 remote_supports_install_in_trace (void)
11655 {
11656 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11657 }
11658
11659 static int
11660 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11661 {
11662 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11663 == PACKET_ENABLE);
11664 }
11665
11666 static int
11667 remote_supports_string_tracing (struct target_ops *self)
11668 {
11669 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11670 }
11671
11672 static int
11673 remote_can_run_breakpoint_commands (struct target_ops *self)
11674 {
11675 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11676 }
11677
11678 static void
11679 remote_trace_init (struct target_ops *self)
11680 {
11681 putpkt ("QTinit");
11682 remote_get_noisy_reply (&target_buf, &target_buf_size);
11683 if (strcmp (target_buf, "OK") != 0)
11684 error (_("Target does not support this command."));
11685 }
11686
11687 static void free_actions_list (char **actions_list);
11688 static void free_actions_list_cleanup_wrapper (void *);
11689 static void
11690 free_actions_list_cleanup_wrapper (void *al)
11691 {
11692 free_actions_list ((char **) al);
11693 }
11694
11695 static void
11696 free_actions_list (char **actions_list)
11697 {
11698 int ndx;
11699
11700 if (actions_list == 0)
11701 return;
11702
11703 for (ndx = 0; actions_list[ndx]; ndx++)
11704 xfree (actions_list[ndx]);
11705
11706 xfree (actions_list);
11707 }
11708
11709 /* Recursive routine to walk through command list including loops, and
11710 download packets for each command. */
11711
11712 static void
11713 remote_download_command_source (int num, ULONGEST addr,
11714 struct command_line *cmds)
11715 {
11716 struct remote_state *rs = get_remote_state ();
11717 struct command_line *cmd;
11718
11719 for (cmd = cmds; cmd; cmd = cmd->next)
11720 {
11721 QUIT; /* Allow user to bail out with ^C. */
11722 strcpy (rs->buf, "QTDPsrc:");
11723 encode_source_string (num, addr, "cmd", cmd->line,
11724 rs->buf + strlen (rs->buf),
11725 rs->buf_size - strlen (rs->buf));
11726 putpkt (rs->buf);
11727 remote_get_noisy_reply (&target_buf, &target_buf_size);
11728 if (strcmp (target_buf, "OK"))
11729 warning (_("Target does not support source download."));
11730
11731 if (cmd->control_type == while_control
11732 || cmd->control_type == while_stepping_control)
11733 {
11734 remote_download_command_source (num, addr, *cmd->body_list);
11735
11736 QUIT; /* Allow user to bail out with ^C. */
11737 strcpy (rs->buf, "QTDPsrc:");
11738 encode_source_string (num, addr, "cmd", "end",
11739 rs->buf + strlen (rs->buf),
11740 rs->buf_size - strlen (rs->buf));
11741 putpkt (rs->buf);
11742 remote_get_noisy_reply (&target_buf, &target_buf_size);
11743 if (strcmp (target_buf, "OK"))
11744 warning (_("Target does not support source download."));
11745 }
11746 }
11747 }
11748
11749 static void
11750 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11751 {
11752 #define BUF_SIZE 2048
11753
11754 CORE_ADDR tpaddr;
11755 char addrbuf[40];
11756 char buf[BUF_SIZE];
11757 char **tdp_actions;
11758 char **stepping_actions;
11759 int ndx;
11760 struct cleanup *old_chain = NULL;
11761 struct agent_expr *aexpr;
11762 struct cleanup *aexpr_chain = NULL;
11763 char *pkt;
11764 struct breakpoint *b = loc->owner;
11765 struct tracepoint *t = (struct tracepoint *) b;
11766
11767 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11768 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11769 tdp_actions);
11770 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11771 stepping_actions);
11772
11773 tpaddr = loc->address;
11774 sprintf_vma (addrbuf, tpaddr);
11775 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11776 addrbuf, /* address */
11777 (b->enable_state == bp_enabled ? 'E' : 'D'),
11778 t->step_count, t->pass_count);
11779 /* Fast tracepoints are mostly handled by the target, but we can
11780 tell the target how big of an instruction block should be moved
11781 around. */
11782 if (b->type == bp_fast_tracepoint)
11783 {
11784 /* Only test for support at download time; we may not know
11785 target capabilities at definition time. */
11786 if (remote_supports_fast_tracepoints ())
11787 {
11788 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11789 NULL))
11790 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11791 gdb_insn_length (loc->gdbarch, tpaddr));
11792 else
11793 /* If it passed validation at definition but fails now,
11794 something is very wrong. */
11795 internal_error (__FILE__, __LINE__,
11796 _("Fast tracepoint not "
11797 "valid during download"));
11798 }
11799 else
11800 /* Fast tracepoints are functionally identical to regular
11801 tracepoints, so don't take lack of support as a reason to
11802 give up on the trace run. */
11803 warning (_("Target does not support fast tracepoints, "
11804 "downloading %d as regular tracepoint"), b->number);
11805 }
11806 else if (b->type == bp_static_tracepoint)
11807 {
11808 /* Only test for support at download time; we may not know
11809 target capabilities at definition time. */
11810 if (remote_supports_static_tracepoints ())
11811 {
11812 struct static_tracepoint_marker marker;
11813
11814 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11815 strcat (buf, ":S");
11816 else
11817 error (_("Static tracepoint not valid during download"));
11818 }
11819 else
11820 /* Fast tracepoints are functionally identical to regular
11821 tracepoints, so don't take lack of support as a reason
11822 to give up on the trace run. */
11823 error (_("Target does not support static tracepoints"));
11824 }
11825 /* If the tracepoint has a conditional, make it into an agent
11826 expression and append to the definition. */
11827 if (loc->cond)
11828 {
11829 /* Only test support at download time, we may not know target
11830 capabilities at definition time. */
11831 if (remote_supports_cond_tracepoints ())
11832 {
11833 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11834 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11835 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11836 aexpr->len);
11837 pkt = buf + strlen (buf);
11838 for (ndx = 0; ndx < aexpr->len; ++ndx)
11839 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11840 *pkt = '\0';
11841 do_cleanups (aexpr_chain);
11842 }
11843 else
11844 warning (_("Target does not support conditional tracepoints, "
11845 "ignoring tp %d cond"), b->number);
11846 }
11847
11848 if (b->commands || *default_collect)
11849 strcat (buf, "-");
11850 putpkt (buf);
11851 remote_get_noisy_reply (&target_buf, &target_buf_size);
11852 if (strcmp (target_buf, "OK"))
11853 error (_("Target does not support tracepoints."));
11854
11855 /* do_single_steps (t); */
11856 if (tdp_actions)
11857 {
11858 for (ndx = 0; tdp_actions[ndx]; ndx++)
11859 {
11860 QUIT; /* Allow user to bail out with ^C. */
11861 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11862 b->number, addrbuf, /* address */
11863 tdp_actions[ndx],
11864 ((tdp_actions[ndx + 1] || stepping_actions)
11865 ? '-' : 0));
11866 putpkt (buf);
11867 remote_get_noisy_reply (&target_buf,
11868 &target_buf_size);
11869 if (strcmp (target_buf, "OK"))
11870 error (_("Error on target while setting tracepoints."));
11871 }
11872 }
11873 if (stepping_actions)
11874 {
11875 for (ndx = 0; stepping_actions[ndx]; ndx++)
11876 {
11877 QUIT; /* Allow user to bail out with ^C. */
11878 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11879 b->number, addrbuf, /* address */
11880 ((ndx == 0) ? "S" : ""),
11881 stepping_actions[ndx],
11882 (stepping_actions[ndx + 1] ? "-" : ""));
11883 putpkt (buf);
11884 remote_get_noisy_reply (&target_buf,
11885 &target_buf_size);
11886 if (strcmp (target_buf, "OK"))
11887 error (_("Error on target while setting tracepoints."));
11888 }
11889 }
11890
11891 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11892 {
11893 if (b->location != NULL)
11894 {
11895 strcpy (buf, "QTDPsrc:");
11896 encode_source_string (b->number, loc->address, "at",
11897 event_location_to_string (b->location),
11898 buf + strlen (buf), 2048 - strlen (buf));
11899 putpkt (buf);
11900 remote_get_noisy_reply (&target_buf, &target_buf_size);
11901 if (strcmp (target_buf, "OK"))
11902 warning (_("Target does not support source download."));
11903 }
11904 if (b->cond_string)
11905 {
11906 strcpy (buf, "QTDPsrc:");
11907 encode_source_string (b->number, loc->address,
11908 "cond", b->cond_string, buf + strlen (buf),
11909 2048 - strlen (buf));
11910 putpkt (buf);
11911 remote_get_noisy_reply (&target_buf, &target_buf_size);
11912 if (strcmp (target_buf, "OK"))
11913 warning (_("Target does not support source download."));
11914 }
11915 remote_download_command_source (b->number, loc->address,
11916 breakpoint_commands (b));
11917 }
11918
11919 do_cleanups (old_chain);
11920 }
11921
11922 static int
11923 remote_can_download_tracepoint (struct target_ops *self)
11924 {
11925 struct remote_state *rs = get_remote_state ();
11926 struct trace_status *ts;
11927 int status;
11928
11929 /* Don't try to install tracepoints until we've relocated our
11930 symbols, and fetched and merged the target's tracepoint list with
11931 ours. */
11932 if (rs->starting_up)
11933 return 0;
11934
11935 ts = current_trace_status ();
11936 status = remote_get_trace_status (self, ts);
11937
11938 if (status == -1 || !ts->running_known || !ts->running)
11939 return 0;
11940
11941 /* If we are in a tracing experiment, but remote stub doesn't support
11942 installing tracepoint in trace, we have to return. */
11943 if (!remote_supports_install_in_trace ())
11944 return 0;
11945
11946 return 1;
11947 }
11948
11949
11950 static void
11951 remote_download_trace_state_variable (struct target_ops *self,
11952 struct trace_state_variable *tsv)
11953 {
11954 struct remote_state *rs = get_remote_state ();
11955 char *p;
11956
11957 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11958 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11959 tsv->builtin);
11960 p = rs->buf + strlen (rs->buf);
11961 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11962 error (_("Trace state variable name too long for tsv definition packet"));
11963 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11964 *p++ = '\0';
11965 putpkt (rs->buf);
11966 remote_get_noisy_reply (&target_buf, &target_buf_size);
11967 if (*target_buf == '\0')
11968 error (_("Target does not support this command."));
11969 if (strcmp (target_buf, "OK") != 0)
11970 error (_("Error on target while downloading trace state variable."));
11971 }
11972
11973 static void
11974 remote_enable_tracepoint (struct target_ops *self,
11975 struct bp_location *location)
11976 {
11977 struct remote_state *rs = get_remote_state ();
11978 char addr_buf[40];
11979
11980 sprintf_vma (addr_buf, location->address);
11981 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11982 location->owner->number, addr_buf);
11983 putpkt (rs->buf);
11984 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11985 if (*rs->buf == '\0')
11986 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11987 if (strcmp (rs->buf, "OK") != 0)
11988 error (_("Error on target while enabling tracepoint."));
11989 }
11990
11991 static void
11992 remote_disable_tracepoint (struct target_ops *self,
11993 struct bp_location *location)
11994 {
11995 struct remote_state *rs = get_remote_state ();
11996 char addr_buf[40];
11997
11998 sprintf_vma (addr_buf, location->address);
11999 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12000 location->owner->number, addr_buf);
12001 putpkt (rs->buf);
12002 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12003 if (*rs->buf == '\0')
12004 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12005 if (strcmp (rs->buf, "OK") != 0)
12006 error (_("Error on target while disabling tracepoint."));
12007 }
12008
12009 static void
12010 remote_trace_set_readonly_regions (struct target_ops *self)
12011 {
12012 asection *s;
12013 bfd *abfd = NULL;
12014 bfd_size_type size;
12015 bfd_vma vma;
12016 int anysecs = 0;
12017 int offset = 0;
12018
12019 if (!exec_bfd)
12020 return; /* No information to give. */
12021
12022 strcpy (target_buf, "QTro");
12023 offset = strlen (target_buf);
12024 for (s = exec_bfd->sections; s; s = s->next)
12025 {
12026 char tmp1[40], tmp2[40];
12027 int sec_length;
12028
12029 if ((s->flags & SEC_LOAD) == 0 ||
12030 /* (s->flags & SEC_CODE) == 0 || */
12031 (s->flags & SEC_READONLY) == 0)
12032 continue;
12033
12034 anysecs = 1;
12035 vma = bfd_get_section_vma (abfd, s);
12036 size = bfd_get_section_size (s);
12037 sprintf_vma (tmp1, vma);
12038 sprintf_vma (tmp2, vma + size);
12039 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12040 if (offset + sec_length + 1 > target_buf_size)
12041 {
12042 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12043 warning (_("\
12044 Too many sections for read-only sections definition packet."));
12045 break;
12046 }
12047 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12048 tmp1, tmp2);
12049 offset += sec_length;
12050 }
12051 if (anysecs)
12052 {
12053 putpkt (target_buf);
12054 getpkt (&target_buf, &target_buf_size, 0);
12055 }
12056 }
12057
12058 static void
12059 remote_trace_start (struct target_ops *self)
12060 {
12061 putpkt ("QTStart");
12062 remote_get_noisy_reply (&target_buf, &target_buf_size);
12063 if (*target_buf == '\0')
12064 error (_("Target does not support this command."));
12065 if (strcmp (target_buf, "OK") != 0)
12066 error (_("Bogus reply from target: %s"), target_buf);
12067 }
12068
12069 static int
12070 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12071 {
12072 /* Initialize it just to avoid a GCC false warning. */
12073 char *p = NULL;
12074 /* FIXME we need to get register block size some other way. */
12075 extern int trace_regblock_size;
12076 enum packet_result result;
12077
12078 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12079 return -1;
12080
12081 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12082
12083 putpkt ("qTStatus");
12084
12085 TRY
12086 {
12087 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12088 }
12089 CATCH (ex, RETURN_MASK_ERROR)
12090 {
12091 if (ex.error != TARGET_CLOSE_ERROR)
12092 {
12093 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12094 return -1;
12095 }
12096 throw_exception (ex);
12097 }
12098 END_CATCH
12099
12100 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12101
12102 /* If the remote target doesn't do tracing, flag it. */
12103 if (result == PACKET_UNKNOWN)
12104 return -1;
12105
12106 /* We're working with a live target. */
12107 ts->filename = NULL;
12108
12109 if (*p++ != 'T')
12110 error (_("Bogus trace status reply from target: %s"), target_buf);
12111
12112 /* Function 'parse_trace_status' sets default value of each field of
12113 'ts' at first, so we don't have to do it here. */
12114 parse_trace_status (p, ts);
12115
12116 return ts->running;
12117 }
12118
12119 static void
12120 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12121 struct uploaded_tp *utp)
12122 {
12123 struct remote_state *rs = get_remote_state ();
12124 char *reply;
12125 struct bp_location *loc;
12126 struct tracepoint *tp = (struct tracepoint *) bp;
12127 size_t size = get_remote_packet_size ();
12128
12129 if (tp)
12130 {
12131 tp->base.hit_count = 0;
12132 tp->traceframe_usage = 0;
12133 for (loc = tp->base.loc; loc; loc = loc->next)
12134 {
12135 /* If the tracepoint was never downloaded, don't go asking for
12136 any status. */
12137 if (tp->number_on_target == 0)
12138 continue;
12139 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12140 phex_nz (loc->address, 0));
12141 putpkt (rs->buf);
12142 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12143 if (reply && *reply)
12144 {
12145 if (*reply == 'V')
12146 parse_tracepoint_status (reply + 1, bp, utp);
12147 }
12148 }
12149 }
12150 else if (utp)
12151 {
12152 utp->hit_count = 0;
12153 utp->traceframe_usage = 0;
12154 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12155 phex_nz (utp->addr, 0));
12156 putpkt (rs->buf);
12157 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12158 if (reply && *reply)
12159 {
12160 if (*reply == 'V')
12161 parse_tracepoint_status (reply + 1, bp, utp);
12162 }
12163 }
12164 }
12165
12166 static void
12167 remote_trace_stop (struct target_ops *self)
12168 {
12169 putpkt ("QTStop");
12170 remote_get_noisy_reply (&target_buf, &target_buf_size);
12171 if (*target_buf == '\0')
12172 error (_("Target does not support this command."));
12173 if (strcmp (target_buf, "OK") != 0)
12174 error (_("Bogus reply from target: %s"), target_buf);
12175 }
12176
12177 static int
12178 remote_trace_find (struct target_ops *self,
12179 enum trace_find_type type, int num,
12180 CORE_ADDR addr1, CORE_ADDR addr2,
12181 int *tpp)
12182 {
12183 struct remote_state *rs = get_remote_state ();
12184 char *endbuf = rs->buf + get_remote_packet_size ();
12185 char *p, *reply;
12186 int target_frameno = -1, target_tracept = -1;
12187
12188 /* Lookups other than by absolute frame number depend on the current
12189 trace selected, so make sure it is correct on the remote end
12190 first. */
12191 if (type != tfind_number)
12192 set_remote_traceframe ();
12193
12194 p = rs->buf;
12195 strcpy (p, "QTFrame:");
12196 p = strchr (p, '\0');
12197 switch (type)
12198 {
12199 case tfind_number:
12200 xsnprintf (p, endbuf - p, "%x", num);
12201 break;
12202 case tfind_pc:
12203 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12204 break;
12205 case tfind_tp:
12206 xsnprintf (p, endbuf - p, "tdp:%x", num);
12207 break;
12208 case tfind_range:
12209 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12210 phex_nz (addr2, 0));
12211 break;
12212 case tfind_outside:
12213 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12214 phex_nz (addr2, 0));
12215 break;
12216 default:
12217 error (_("Unknown trace find type %d"), type);
12218 }
12219
12220 putpkt (rs->buf);
12221 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12222 if (*reply == '\0')
12223 error (_("Target does not support this command."));
12224
12225 while (reply && *reply)
12226 switch (*reply)
12227 {
12228 case 'F':
12229 p = ++reply;
12230 target_frameno = (int) strtol (p, &reply, 16);
12231 if (reply == p)
12232 error (_("Unable to parse trace frame number"));
12233 /* Don't update our remote traceframe number cache on failure
12234 to select a remote traceframe. */
12235 if (target_frameno == -1)
12236 return -1;
12237 break;
12238 case 'T':
12239 p = ++reply;
12240 target_tracept = (int) strtol (p, &reply, 16);
12241 if (reply == p)
12242 error (_("Unable to parse tracepoint number"));
12243 break;
12244 case 'O': /* "OK"? */
12245 if (reply[1] == 'K' && reply[2] == '\0')
12246 reply += 2;
12247 else
12248 error (_("Bogus reply from target: %s"), reply);
12249 break;
12250 default:
12251 error (_("Bogus reply from target: %s"), reply);
12252 }
12253 if (tpp)
12254 *tpp = target_tracept;
12255
12256 rs->remote_traceframe_number = target_frameno;
12257 return target_frameno;
12258 }
12259
12260 static int
12261 remote_get_trace_state_variable_value (struct target_ops *self,
12262 int tsvnum, LONGEST *val)
12263 {
12264 struct remote_state *rs = get_remote_state ();
12265 char *reply;
12266 ULONGEST uval;
12267
12268 set_remote_traceframe ();
12269
12270 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12271 putpkt (rs->buf);
12272 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12273 if (reply && *reply)
12274 {
12275 if (*reply == 'V')
12276 {
12277 unpack_varlen_hex (reply + 1, &uval);
12278 *val = (LONGEST) uval;
12279 return 1;
12280 }
12281 }
12282 return 0;
12283 }
12284
12285 static int
12286 remote_save_trace_data (struct target_ops *self, const char *filename)
12287 {
12288 struct remote_state *rs = get_remote_state ();
12289 char *p, *reply;
12290
12291 p = rs->buf;
12292 strcpy (p, "QTSave:");
12293 p += strlen (p);
12294 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12295 error (_("Remote file name too long for trace save packet"));
12296 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12297 *p++ = '\0';
12298 putpkt (rs->buf);
12299 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12300 if (*reply == '\0')
12301 error (_("Target does not support this command."));
12302 if (strcmp (reply, "OK") != 0)
12303 error (_("Bogus reply from target: %s"), reply);
12304 return 0;
12305 }
12306
12307 /* This is basically a memory transfer, but needs to be its own packet
12308 because we don't know how the target actually organizes its trace
12309 memory, plus we want to be able to ask for as much as possible, but
12310 not be unhappy if we don't get as much as we ask for. */
12311
12312 static LONGEST
12313 remote_get_raw_trace_data (struct target_ops *self,
12314 gdb_byte *buf, ULONGEST offset, LONGEST len)
12315 {
12316 struct remote_state *rs = get_remote_state ();
12317 char *reply;
12318 char *p;
12319 int rslt;
12320
12321 p = rs->buf;
12322 strcpy (p, "qTBuffer:");
12323 p += strlen (p);
12324 p += hexnumstr (p, offset);
12325 *p++ = ',';
12326 p += hexnumstr (p, len);
12327 *p++ = '\0';
12328
12329 putpkt (rs->buf);
12330 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12331 if (reply && *reply)
12332 {
12333 /* 'l' by itself means we're at the end of the buffer and
12334 there is nothing more to get. */
12335 if (*reply == 'l')
12336 return 0;
12337
12338 /* Convert the reply into binary. Limit the number of bytes to
12339 convert according to our passed-in buffer size, rather than
12340 what was returned in the packet; if the target is
12341 unexpectedly generous and gives us a bigger reply than we
12342 asked for, we don't want to crash. */
12343 rslt = hex2bin (target_buf, buf, len);
12344 return rslt;
12345 }
12346
12347 /* Something went wrong, flag as an error. */
12348 return -1;
12349 }
12350
12351 static void
12352 remote_set_disconnected_tracing (struct target_ops *self, int val)
12353 {
12354 struct remote_state *rs = get_remote_state ();
12355
12356 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12357 {
12358 char *reply;
12359
12360 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12361 putpkt (rs->buf);
12362 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12363 if (*reply == '\0')
12364 error (_("Target does not support this command."));
12365 if (strcmp (reply, "OK") != 0)
12366 error (_("Bogus reply from target: %s"), reply);
12367 }
12368 else if (val)
12369 warning (_("Target does not support disconnected tracing."));
12370 }
12371
12372 static int
12373 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12374 {
12375 struct thread_info *info = find_thread_ptid (ptid);
12376
12377 if (info && info->priv)
12378 return info->priv->core;
12379 return -1;
12380 }
12381
12382 static void
12383 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12384 {
12385 struct remote_state *rs = get_remote_state ();
12386 char *reply;
12387
12388 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12389 putpkt (rs->buf);
12390 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12391 if (*reply == '\0')
12392 error (_("Target does not support this command."));
12393 if (strcmp (reply, "OK") != 0)
12394 error (_("Bogus reply from target: %s"), reply);
12395 }
12396
12397 static struct traceframe_info *
12398 remote_traceframe_info (struct target_ops *self)
12399 {
12400 char *text;
12401
12402 text = target_read_stralloc (&current_target,
12403 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12404 if (text != NULL)
12405 {
12406 struct traceframe_info *info;
12407 struct cleanup *back_to = make_cleanup (xfree, text);
12408
12409 info = parse_traceframe_info (text);
12410 do_cleanups (back_to);
12411 return info;
12412 }
12413
12414 return NULL;
12415 }
12416
12417 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12418 instruction on which a fast tracepoint may be placed. Returns -1
12419 if the packet is not supported, and 0 if the minimum instruction
12420 length is unknown. */
12421
12422 static int
12423 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12424 {
12425 struct remote_state *rs = get_remote_state ();
12426 char *reply;
12427
12428 /* If we're not debugging a process yet, the IPA can't be
12429 loaded. */
12430 if (!target_has_execution)
12431 return 0;
12432
12433 /* Make sure the remote is pointing at the right process. */
12434 set_general_process ();
12435
12436 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12437 putpkt (rs->buf);
12438 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12439 if (*reply == '\0')
12440 return -1;
12441 else
12442 {
12443 ULONGEST min_insn_len;
12444
12445 unpack_varlen_hex (reply, &min_insn_len);
12446
12447 return (int) min_insn_len;
12448 }
12449 }
12450
12451 static void
12452 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12453 {
12454 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12455 {
12456 struct remote_state *rs = get_remote_state ();
12457 char *buf = rs->buf;
12458 char *endbuf = rs->buf + get_remote_packet_size ();
12459 enum packet_result result;
12460
12461 gdb_assert (val >= 0 || val == -1);
12462 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12463 /* Send -1 as literal "-1" to avoid host size dependency. */
12464 if (val < 0)
12465 {
12466 *buf++ = '-';
12467 buf += hexnumstr (buf, (ULONGEST) -val);
12468 }
12469 else
12470 buf += hexnumstr (buf, (ULONGEST) val);
12471
12472 putpkt (rs->buf);
12473 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12474 result = packet_ok (rs->buf,
12475 &remote_protocol_packets[PACKET_QTBuffer_size]);
12476
12477 if (result != PACKET_OK)
12478 warning (_("Bogus reply from target: %s"), rs->buf);
12479 }
12480 }
12481
12482 static int
12483 remote_set_trace_notes (struct target_ops *self,
12484 const char *user, const char *notes,
12485 const char *stop_notes)
12486 {
12487 struct remote_state *rs = get_remote_state ();
12488 char *reply;
12489 char *buf = rs->buf;
12490 char *endbuf = rs->buf + get_remote_packet_size ();
12491 int nbytes;
12492
12493 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12494 if (user)
12495 {
12496 buf += xsnprintf (buf, endbuf - buf, "user:");
12497 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12498 buf += 2 * nbytes;
12499 *buf++ = ';';
12500 }
12501 if (notes)
12502 {
12503 buf += xsnprintf (buf, endbuf - buf, "notes:");
12504 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12505 buf += 2 * nbytes;
12506 *buf++ = ';';
12507 }
12508 if (stop_notes)
12509 {
12510 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12511 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12512 buf += 2 * nbytes;
12513 *buf++ = ';';
12514 }
12515 /* Ensure the buffer is terminated. */
12516 *buf = '\0';
12517
12518 putpkt (rs->buf);
12519 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12520 if (*reply == '\0')
12521 return 0;
12522
12523 if (strcmp (reply, "OK") != 0)
12524 error (_("Bogus reply from target: %s"), reply);
12525
12526 return 1;
12527 }
12528
12529 static int
12530 remote_use_agent (struct target_ops *self, int use)
12531 {
12532 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12533 {
12534 struct remote_state *rs = get_remote_state ();
12535
12536 /* If the stub supports QAgent. */
12537 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12538 putpkt (rs->buf);
12539 getpkt (&rs->buf, &rs->buf_size, 0);
12540
12541 if (strcmp (rs->buf, "OK") == 0)
12542 {
12543 use_agent = use;
12544 return 1;
12545 }
12546 }
12547
12548 return 0;
12549 }
12550
12551 static int
12552 remote_can_use_agent (struct target_ops *self)
12553 {
12554 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12555 }
12556
12557 struct btrace_target_info
12558 {
12559 /* The ptid of the traced thread. */
12560 ptid_t ptid;
12561
12562 /* The obtained branch trace configuration. */
12563 struct btrace_config conf;
12564 };
12565
12566 /* Reset our idea of our target's btrace configuration. */
12567
12568 static void
12569 remote_btrace_reset (void)
12570 {
12571 struct remote_state *rs = get_remote_state ();
12572
12573 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12574 }
12575
12576 /* Check whether the target supports branch tracing. */
12577
12578 static int
12579 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12580 {
12581 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12582 return 0;
12583 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12584 return 0;
12585
12586 switch (format)
12587 {
12588 case BTRACE_FORMAT_NONE:
12589 return 0;
12590
12591 case BTRACE_FORMAT_BTS:
12592 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12593
12594 case BTRACE_FORMAT_PT:
12595 /* The trace is decoded on the host. Even if our target supports it,
12596 we still need to have libipt to decode the trace. */
12597 #if defined (HAVE_LIBIPT)
12598 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12599 #else /* !defined (HAVE_LIBIPT) */
12600 return 0;
12601 #endif /* !defined (HAVE_LIBIPT) */
12602 }
12603
12604 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12605 }
12606
12607 /* Synchronize the configuration with the target. */
12608
12609 static void
12610 btrace_sync_conf (const struct btrace_config *conf)
12611 {
12612 struct packet_config *packet;
12613 struct remote_state *rs;
12614 char *buf, *pos, *endbuf;
12615
12616 rs = get_remote_state ();
12617 buf = rs->buf;
12618 endbuf = buf + get_remote_packet_size ();
12619
12620 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12621 if (packet_config_support (packet) == PACKET_ENABLE
12622 && conf->bts.size != rs->btrace_config.bts.size)
12623 {
12624 pos = buf;
12625 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12626 conf->bts.size);
12627
12628 putpkt (buf);
12629 getpkt (&buf, &rs->buf_size, 0);
12630
12631 if (packet_ok (buf, packet) == PACKET_ERROR)
12632 {
12633 if (buf[0] == 'E' && buf[1] == '.')
12634 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12635 else
12636 error (_("Failed to configure the BTS buffer size."));
12637 }
12638
12639 rs->btrace_config.bts.size = conf->bts.size;
12640 }
12641
12642 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12643 if (packet_config_support (packet) == PACKET_ENABLE
12644 && conf->pt.size != rs->btrace_config.pt.size)
12645 {
12646 pos = buf;
12647 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12648 conf->pt.size);
12649
12650 putpkt (buf);
12651 getpkt (&buf, &rs->buf_size, 0);
12652
12653 if (packet_ok (buf, packet) == PACKET_ERROR)
12654 {
12655 if (buf[0] == 'E' && buf[1] == '.')
12656 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12657 else
12658 error (_("Failed to configure the trace buffer size."));
12659 }
12660
12661 rs->btrace_config.pt.size = conf->pt.size;
12662 }
12663 }
12664
12665 /* Read the current thread's btrace configuration from the target and
12666 store it into CONF. */
12667
12668 static void
12669 btrace_read_config (struct btrace_config *conf)
12670 {
12671 char *xml;
12672
12673 xml = target_read_stralloc (&current_target,
12674 TARGET_OBJECT_BTRACE_CONF, "");
12675 if (xml != NULL)
12676 {
12677 struct cleanup *cleanup;
12678
12679 cleanup = make_cleanup (xfree, xml);
12680 parse_xml_btrace_conf (conf, xml);
12681 do_cleanups (cleanup);
12682 }
12683 }
12684
12685 /* Enable branch tracing. */
12686
12687 static struct btrace_target_info *
12688 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12689 const struct btrace_config *conf)
12690 {
12691 struct btrace_target_info *tinfo = NULL;
12692 struct packet_config *packet = NULL;
12693 struct remote_state *rs = get_remote_state ();
12694 char *buf = rs->buf;
12695 char *endbuf = rs->buf + get_remote_packet_size ();
12696
12697 switch (conf->format)
12698 {
12699 case BTRACE_FORMAT_BTS:
12700 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12701 break;
12702
12703 case BTRACE_FORMAT_PT:
12704 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12705 break;
12706 }
12707
12708 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12709 error (_("Target does not support branch tracing."));
12710
12711 btrace_sync_conf (conf);
12712
12713 set_general_thread (ptid);
12714
12715 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12716 putpkt (rs->buf);
12717 getpkt (&rs->buf, &rs->buf_size, 0);
12718
12719 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12720 {
12721 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12722 error (_("Could not enable branch tracing for %s: %s"),
12723 target_pid_to_str (ptid), rs->buf + 2);
12724 else
12725 error (_("Could not enable branch tracing for %s."),
12726 target_pid_to_str (ptid));
12727 }
12728
12729 tinfo = XCNEW (struct btrace_target_info);
12730 tinfo->ptid = ptid;
12731
12732 /* If we fail to read the configuration, we lose some information, but the
12733 tracing itself is not impacted. */
12734 TRY
12735 {
12736 btrace_read_config (&tinfo->conf);
12737 }
12738 CATCH (err, RETURN_MASK_ERROR)
12739 {
12740 if (err.message != NULL)
12741 warning ("%s", err.message);
12742 }
12743 END_CATCH
12744
12745 return tinfo;
12746 }
12747
12748 /* Disable branch tracing. */
12749
12750 static void
12751 remote_disable_btrace (struct target_ops *self,
12752 struct btrace_target_info *tinfo)
12753 {
12754 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12755 struct remote_state *rs = get_remote_state ();
12756 char *buf = rs->buf;
12757 char *endbuf = rs->buf + get_remote_packet_size ();
12758
12759 if (packet_config_support (packet) != PACKET_ENABLE)
12760 error (_("Target does not support branch tracing."));
12761
12762 set_general_thread (tinfo->ptid);
12763
12764 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12765 putpkt (rs->buf);
12766 getpkt (&rs->buf, &rs->buf_size, 0);
12767
12768 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12769 {
12770 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12771 error (_("Could not disable branch tracing for %s: %s"),
12772 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12773 else
12774 error (_("Could not disable branch tracing for %s."),
12775 target_pid_to_str (tinfo->ptid));
12776 }
12777
12778 xfree (tinfo);
12779 }
12780
12781 /* Teardown branch tracing. */
12782
12783 static void
12784 remote_teardown_btrace (struct target_ops *self,
12785 struct btrace_target_info *tinfo)
12786 {
12787 /* We must not talk to the target during teardown. */
12788 xfree (tinfo);
12789 }
12790
12791 /* Read the branch trace. */
12792
12793 static enum btrace_error
12794 remote_read_btrace (struct target_ops *self,
12795 struct btrace_data *btrace,
12796 struct btrace_target_info *tinfo,
12797 enum btrace_read_type type)
12798 {
12799 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12800 struct remote_state *rs = get_remote_state ();
12801 struct cleanup *cleanup;
12802 const char *annex;
12803 char *xml;
12804
12805 if (packet_config_support (packet) != PACKET_ENABLE)
12806 error (_("Target does not support branch tracing."));
12807
12808 #if !defined(HAVE_LIBEXPAT)
12809 error (_("Cannot process branch tracing result. XML parsing not supported."));
12810 #endif
12811
12812 switch (type)
12813 {
12814 case BTRACE_READ_ALL:
12815 annex = "all";
12816 break;
12817 case BTRACE_READ_NEW:
12818 annex = "new";
12819 break;
12820 case BTRACE_READ_DELTA:
12821 annex = "delta";
12822 break;
12823 default:
12824 internal_error (__FILE__, __LINE__,
12825 _("Bad branch tracing read type: %u."),
12826 (unsigned int) type);
12827 }
12828
12829 xml = target_read_stralloc (&current_target,
12830 TARGET_OBJECT_BTRACE, annex);
12831 if (xml == NULL)
12832 return BTRACE_ERR_UNKNOWN;
12833
12834 cleanup = make_cleanup (xfree, xml);
12835 parse_xml_btrace (btrace, xml);
12836 do_cleanups (cleanup);
12837
12838 return BTRACE_ERR_NONE;
12839 }
12840
12841 static const struct btrace_config *
12842 remote_btrace_conf (struct target_ops *self,
12843 const struct btrace_target_info *tinfo)
12844 {
12845 return &tinfo->conf;
12846 }
12847
12848 static int
12849 remote_augmented_libraries_svr4_read (struct target_ops *self)
12850 {
12851 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12852 == PACKET_ENABLE);
12853 }
12854
12855 /* Implementation of to_load. */
12856
12857 static void
12858 remote_load (struct target_ops *self, const char *name, int from_tty)
12859 {
12860 generic_load (name, from_tty);
12861 }
12862
12863 /* Accepts an integer PID; returns a string representing a file that
12864 can be opened on the remote side to get the symbols for the child
12865 process. Returns NULL if the operation is not supported. */
12866
12867 static char *
12868 remote_pid_to_exec_file (struct target_ops *self, int pid)
12869 {
12870 static char *filename = NULL;
12871 struct inferior *inf;
12872 char *annex = NULL;
12873
12874 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12875 return NULL;
12876
12877 if (filename != NULL)
12878 xfree (filename);
12879
12880 inf = find_inferior_pid (pid);
12881 if (inf == NULL)
12882 internal_error (__FILE__, __LINE__,
12883 _("not currently attached to process %d"), pid);
12884
12885 if (!inf->fake_pid_p)
12886 {
12887 const int annex_size = 9;
12888
12889 annex = (char *) alloca (annex_size);
12890 xsnprintf (annex, annex_size, "%x", pid);
12891 }
12892
12893 filename = target_read_stralloc (&current_target,
12894 TARGET_OBJECT_EXEC_FILE, annex);
12895
12896 return filename;
12897 }
12898
12899 /* Implement the to_can_do_single_step target_ops method. */
12900
12901 static int
12902 remote_can_do_single_step (struct target_ops *ops)
12903 {
12904 /* We can only tell whether target supports single step or not by
12905 supported s and S vCont actions if the stub supports vContSupported
12906 feature. If the stub doesn't support vContSupported feature,
12907 we have conservatively to think target doesn't supports single
12908 step. */
12909 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12910 {
12911 struct remote_state *rs = get_remote_state ();
12912
12913 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12914 remote_vcont_probe (rs);
12915
12916 return rs->supports_vCont.s && rs->supports_vCont.S;
12917 }
12918 else
12919 return 0;
12920 }
12921
12922 static void
12923 init_remote_ops (void)
12924 {
12925 remote_ops.to_shortname = "remote";
12926 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12927 remote_ops.to_doc =
12928 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12929 Specify the serial device it is connected to\n\
12930 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12931 remote_ops.to_open = remote_open;
12932 remote_ops.to_close = remote_close;
12933 remote_ops.to_detach = remote_detach;
12934 remote_ops.to_disconnect = remote_disconnect;
12935 remote_ops.to_resume = remote_resume;
12936 remote_ops.to_wait = remote_wait;
12937 remote_ops.to_fetch_registers = remote_fetch_registers;
12938 remote_ops.to_store_registers = remote_store_registers;
12939 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12940 remote_ops.to_files_info = remote_files_info;
12941 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12942 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12943 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12944 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12945 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12946 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12947 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12948 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12949 remote_ops.to_watchpoint_addr_within_range =
12950 remote_watchpoint_addr_within_range;
12951 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12952 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12953 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12954 remote_ops.to_region_ok_for_hw_watchpoint
12955 = remote_region_ok_for_hw_watchpoint;
12956 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12957 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12958 remote_ops.to_kill = remote_kill;
12959 remote_ops.to_load = remote_load;
12960 remote_ops.to_mourn_inferior = remote_mourn;
12961 remote_ops.to_pass_signals = remote_pass_signals;
12962 remote_ops.to_program_signals = remote_program_signals;
12963 remote_ops.to_thread_alive = remote_thread_alive;
12964 remote_ops.to_thread_name = remote_thread_name;
12965 remote_ops.to_update_thread_list = remote_update_thread_list;
12966 remote_ops.to_pid_to_str = remote_pid_to_str;
12967 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12968 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12969 remote_ops.to_stop = remote_stop;
12970 remote_ops.to_interrupt = remote_interrupt;
12971 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12972 remote_ops.to_xfer_partial = remote_xfer_partial;
12973 remote_ops.to_rcmd = remote_rcmd;
12974 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12975 remote_ops.to_log_command = serial_log_command;
12976 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12977 remote_ops.to_stratum = process_stratum;
12978 remote_ops.to_has_all_memory = default_child_has_all_memory;
12979 remote_ops.to_has_memory = default_child_has_memory;
12980 remote_ops.to_has_stack = default_child_has_stack;
12981 remote_ops.to_has_registers = default_child_has_registers;
12982 remote_ops.to_has_execution = default_child_has_execution;
12983 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12984 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12985 remote_ops.to_magic = OPS_MAGIC;
12986 remote_ops.to_memory_map = remote_memory_map;
12987 remote_ops.to_flash_erase = remote_flash_erase;
12988 remote_ops.to_flash_done = remote_flash_done;
12989 remote_ops.to_read_description = remote_read_description;
12990 remote_ops.to_search_memory = remote_search_memory;
12991 remote_ops.to_can_async_p = remote_can_async_p;
12992 remote_ops.to_is_async_p = remote_is_async_p;
12993 remote_ops.to_async = remote_async;
12994 remote_ops.to_thread_events = remote_thread_events;
12995 remote_ops.to_can_do_single_step = remote_can_do_single_step;
12996 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12997 remote_ops.to_terminal_ours = remote_terminal_ours;
12998 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12999 remote_ops.to_supports_multi_process = remote_supports_multi_process;
13000 remote_ops.to_supports_disable_randomization
13001 = remote_supports_disable_randomization;
13002 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13003 remote_ops.to_fileio_open = remote_hostio_open;
13004 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13005 remote_ops.to_fileio_pread = remote_hostio_pread;
13006 remote_ops.to_fileio_fstat = remote_hostio_fstat;
13007 remote_ops.to_fileio_close = remote_hostio_close;
13008 remote_ops.to_fileio_unlink = remote_hostio_unlink;
13009 remote_ops.to_fileio_readlink = remote_hostio_readlink;
13010 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13011 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13012 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13013 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13014 remote_ops.to_trace_init = remote_trace_init;
13015 remote_ops.to_download_tracepoint = remote_download_tracepoint;
13016 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13017 remote_ops.to_download_trace_state_variable
13018 = remote_download_trace_state_variable;
13019 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13020 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13021 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13022 remote_ops.to_trace_start = remote_trace_start;
13023 remote_ops.to_get_trace_status = remote_get_trace_status;
13024 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13025 remote_ops.to_trace_stop = remote_trace_stop;
13026 remote_ops.to_trace_find = remote_trace_find;
13027 remote_ops.to_get_trace_state_variable_value
13028 = remote_get_trace_state_variable_value;
13029 remote_ops.to_save_trace_data = remote_save_trace_data;
13030 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13031 remote_ops.to_upload_trace_state_variables
13032 = remote_upload_trace_state_variables;
13033 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13034 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13035 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13036 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13037 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13038 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13039 remote_ops.to_core_of_thread = remote_core_of_thread;
13040 remote_ops.to_verify_memory = remote_verify_memory;
13041 remote_ops.to_get_tib_address = remote_get_tib_address;
13042 remote_ops.to_set_permissions = remote_set_permissions;
13043 remote_ops.to_static_tracepoint_marker_at
13044 = remote_static_tracepoint_marker_at;
13045 remote_ops.to_static_tracepoint_markers_by_strid
13046 = remote_static_tracepoint_markers_by_strid;
13047 remote_ops.to_traceframe_info = remote_traceframe_info;
13048 remote_ops.to_use_agent = remote_use_agent;
13049 remote_ops.to_can_use_agent = remote_can_use_agent;
13050 remote_ops.to_supports_btrace = remote_supports_btrace;
13051 remote_ops.to_enable_btrace = remote_enable_btrace;
13052 remote_ops.to_disable_btrace = remote_disable_btrace;
13053 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13054 remote_ops.to_read_btrace = remote_read_btrace;
13055 remote_ops.to_btrace_conf = remote_btrace_conf;
13056 remote_ops.to_augmented_libraries_svr4_read =
13057 remote_augmented_libraries_svr4_read;
13058 }
13059
13060 /* Set up the extended remote vector by making a copy of the standard
13061 remote vector and adding to it. */
13062
13063 static void
13064 init_extended_remote_ops (void)
13065 {
13066 extended_remote_ops = remote_ops;
13067
13068 extended_remote_ops.to_shortname = "extended-remote";
13069 extended_remote_ops.to_longname =
13070 "Extended remote serial target in gdb-specific protocol";
13071 extended_remote_ops.to_doc =
13072 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13073 Specify the serial device it is connected to (e.g. /dev/ttya).";
13074 extended_remote_ops.to_open = extended_remote_open;
13075 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13076 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
13077 extended_remote_ops.to_detach = extended_remote_detach;
13078 extended_remote_ops.to_attach = extended_remote_attach;
13079 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13080 extended_remote_ops.to_kill = extended_remote_kill;
13081 extended_remote_ops.to_supports_disable_randomization
13082 = extended_remote_supports_disable_randomization;
13083 extended_remote_ops.to_follow_fork = remote_follow_fork;
13084 extended_remote_ops.to_follow_exec = remote_follow_exec;
13085 extended_remote_ops.to_insert_fork_catchpoint
13086 = remote_insert_fork_catchpoint;
13087 extended_remote_ops.to_remove_fork_catchpoint
13088 = remote_remove_fork_catchpoint;
13089 extended_remote_ops.to_insert_vfork_catchpoint
13090 = remote_insert_vfork_catchpoint;
13091 extended_remote_ops.to_remove_vfork_catchpoint
13092 = remote_remove_vfork_catchpoint;
13093 extended_remote_ops.to_insert_exec_catchpoint
13094 = remote_insert_exec_catchpoint;
13095 extended_remote_ops.to_remove_exec_catchpoint
13096 = remote_remove_exec_catchpoint;
13097 }
13098
13099 static int
13100 remote_can_async_p (struct target_ops *ops)
13101 {
13102 struct remote_state *rs = get_remote_state ();
13103
13104 if (!target_async_permitted)
13105 /* We only enable async when the user specifically asks for it. */
13106 return 0;
13107
13108 /* We're async whenever the serial device is. */
13109 return serial_can_async_p (rs->remote_desc);
13110 }
13111
13112 static int
13113 remote_is_async_p (struct target_ops *ops)
13114 {
13115 struct remote_state *rs = get_remote_state ();
13116
13117 if (!target_async_permitted)
13118 /* We only enable async when the user specifically asks for it. */
13119 return 0;
13120
13121 /* We're async whenever the serial device is. */
13122 return serial_is_async_p (rs->remote_desc);
13123 }
13124
13125 /* Pass the SERIAL event on and up to the client. One day this code
13126 will be able to delay notifying the client of an event until the
13127 point where an entire packet has been received. */
13128
13129 static serial_event_ftype remote_async_serial_handler;
13130
13131 static void
13132 remote_async_serial_handler (struct serial *scb, void *context)
13133 {
13134 struct remote_state *rs = (struct remote_state *) context;
13135
13136 /* Don't propogate error information up to the client. Instead let
13137 the client find out about the error by querying the target. */
13138 inferior_event_handler (INF_REG_EVENT, NULL);
13139 }
13140
13141 static void
13142 remote_async_inferior_event_handler (gdb_client_data data)
13143 {
13144 inferior_event_handler (INF_REG_EVENT, NULL);
13145 }
13146
13147 static void
13148 remote_async (struct target_ops *ops, int enable)
13149 {
13150 struct remote_state *rs = get_remote_state ();
13151
13152 if (enable)
13153 {
13154 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13155
13156 /* If there are pending events in the stop reply queue tell the
13157 event loop to process them. */
13158 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13159 mark_async_event_handler (remote_async_inferior_event_token);
13160 /* For simplicity, below we clear the pending events token
13161 without remembering whether it is marked, so here we always
13162 mark it. If there's actually no pending notification to
13163 process, this ends up being a no-op (other than a spurious
13164 event-loop wakeup). */
13165 if (target_is_non_stop_p ())
13166 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13167 }
13168 else
13169 {
13170 serial_async (rs->remote_desc, NULL, NULL);
13171 /* If the core is disabling async, it doesn't want to be
13172 disturbed with target events. Clear all async event sources
13173 too. */
13174 clear_async_event_handler (remote_async_inferior_event_token);
13175 if (target_is_non_stop_p ())
13176 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13177 }
13178 }
13179
13180 /* Implementation of the to_thread_events method. */
13181
13182 static void
13183 remote_thread_events (struct target_ops *ops, int enable)
13184 {
13185 struct remote_state *rs = get_remote_state ();
13186 size_t size = get_remote_packet_size ();
13187 char *p = rs->buf;
13188
13189 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13190 return;
13191
13192 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13193 putpkt (rs->buf);
13194 getpkt (&rs->buf, &rs->buf_size, 0);
13195
13196 switch (packet_ok (rs->buf,
13197 &remote_protocol_packets[PACKET_QThreadEvents]))
13198 {
13199 case PACKET_OK:
13200 if (strcmp (rs->buf, "OK") != 0)
13201 error (_("Remote refused setting thread events: %s"), rs->buf);
13202 break;
13203 case PACKET_ERROR:
13204 warning (_("Remote failure reply: %s"), rs->buf);
13205 break;
13206 case PACKET_UNKNOWN:
13207 break;
13208 }
13209 }
13210
13211 static void
13212 set_remote_cmd (char *args, int from_tty)
13213 {
13214 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13215 }
13216
13217 static void
13218 show_remote_cmd (char *args, int from_tty)
13219 {
13220 /* We can't just use cmd_show_list here, because we want to skip
13221 the redundant "show remote Z-packet" and the legacy aliases. */
13222 struct cleanup *showlist_chain;
13223 struct cmd_list_element *list = remote_show_cmdlist;
13224 struct ui_out *uiout = current_uiout;
13225
13226 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13227 for (; list != NULL; list = list->next)
13228 if (strcmp (list->name, "Z-packet") == 0)
13229 continue;
13230 else if (list->type == not_set_cmd)
13231 /* Alias commands are exactly like the original, except they
13232 don't have the normal type. */
13233 continue;
13234 else
13235 {
13236 struct cleanup *option_chain
13237 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13238
13239 ui_out_field_string (uiout, "name", list->name);
13240 ui_out_text (uiout, ": ");
13241 if (list->type == show_cmd)
13242 do_show_command ((char *) NULL, from_tty, list);
13243 else
13244 cmd_func (list, NULL, from_tty);
13245 /* Close the tuple. */
13246 do_cleanups (option_chain);
13247 }
13248
13249 /* Close the tuple. */
13250 do_cleanups (showlist_chain);
13251 }
13252
13253
13254 /* Function to be called whenever a new objfile (shlib) is detected. */
13255 static void
13256 remote_new_objfile (struct objfile *objfile)
13257 {
13258 struct remote_state *rs = get_remote_state ();
13259
13260 if (rs->remote_desc != 0) /* Have a remote connection. */
13261 remote_check_symbols ();
13262 }
13263
13264 /* Pull all the tracepoints defined on the target and create local
13265 data structures representing them. We don't want to create real
13266 tracepoints yet, we don't want to mess up the user's existing
13267 collection. */
13268
13269 static int
13270 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13271 {
13272 struct remote_state *rs = get_remote_state ();
13273 char *p;
13274
13275 /* Ask for a first packet of tracepoint definition. */
13276 putpkt ("qTfP");
13277 getpkt (&rs->buf, &rs->buf_size, 0);
13278 p = rs->buf;
13279 while (*p && *p != 'l')
13280 {
13281 parse_tracepoint_definition (p, utpp);
13282 /* Ask for another packet of tracepoint definition. */
13283 putpkt ("qTsP");
13284 getpkt (&rs->buf, &rs->buf_size, 0);
13285 p = rs->buf;
13286 }
13287 return 0;
13288 }
13289
13290 static int
13291 remote_upload_trace_state_variables (struct target_ops *self,
13292 struct uploaded_tsv **utsvp)
13293 {
13294 struct remote_state *rs = get_remote_state ();
13295 char *p;
13296
13297 /* Ask for a first packet of variable definition. */
13298 putpkt ("qTfV");
13299 getpkt (&rs->buf, &rs->buf_size, 0);
13300 p = rs->buf;
13301 while (*p && *p != 'l')
13302 {
13303 parse_tsv_definition (p, utsvp);
13304 /* Ask for another packet of variable definition. */
13305 putpkt ("qTsV");
13306 getpkt (&rs->buf, &rs->buf_size, 0);
13307 p = rs->buf;
13308 }
13309 return 0;
13310 }
13311
13312 /* The "set/show range-stepping" show hook. */
13313
13314 static void
13315 show_range_stepping (struct ui_file *file, int from_tty,
13316 struct cmd_list_element *c,
13317 const char *value)
13318 {
13319 fprintf_filtered (file,
13320 _("Debugger's willingness to use range stepping "
13321 "is %s.\n"), value);
13322 }
13323
13324 /* The "set/show range-stepping" set hook. */
13325
13326 static void
13327 set_range_stepping (char *ignore_args, int from_tty,
13328 struct cmd_list_element *c)
13329 {
13330 struct remote_state *rs = get_remote_state ();
13331
13332 /* Whene enabling, check whether range stepping is actually
13333 supported by the target, and warn if not. */
13334 if (use_range_stepping)
13335 {
13336 if (rs->remote_desc != NULL)
13337 {
13338 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13339 remote_vcont_probe (rs);
13340
13341 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13342 && rs->supports_vCont.r)
13343 return;
13344 }
13345
13346 warning (_("Range stepping is not supported by the current target"));
13347 }
13348 }
13349
13350 void
13351 _initialize_remote (void)
13352 {
13353 struct remote_state *rs;
13354 struct cmd_list_element *cmd;
13355 const char *cmd_name;
13356
13357 /* architecture specific data */
13358 remote_gdbarch_data_handle =
13359 gdbarch_data_register_post_init (init_remote_state);
13360 remote_g_packet_data_handle =
13361 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13362
13363 remote_pspace_data
13364 = register_program_space_data_with_cleanup (NULL,
13365 remote_pspace_data_cleanup);
13366
13367 /* Initialize the per-target state. At the moment there is only one
13368 of these, not one per target. Only one target is active at a
13369 time. */
13370 remote_state = new_remote_state ();
13371
13372 init_remote_ops ();
13373 add_target (&remote_ops);
13374
13375 init_extended_remote_ops ();
13376 add_target (&extended_remote_ops);
13377
13378 /* Hook into new objfile notification. */
13379 observer_attach_new_objfile (remote_new_objfile);
13380 /* We're no longer interested in notification events of an inferior
13381 when it exits. */
13382 observer_attach_inferior_exit (discard_pending_stop_replies);
13383
13384 /* Set up signal handlers. */
13385 async_sigint_remote_token =
13386 create_async_signal_handler (async_remote_interrupt, NULL);
13387 async_sigint_remote_twice_token =
13388 create_async_signal_handler (async_remote_interrupt_twice, NULL);
13389
13390 #if 0
13391 init_remote_threadtests ();
13392 #endif
13393
13394 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13395 /* set/show remote ... */
13396
13397 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13398 Remote protocol specific variables\n\
13399 Configure various remote-protocol specific variables such as\n\
13400 the packets being used"),
13401 &remote_set_cmdlist, "set remote ",
13402 0 /* allow-unknown */, &setlist);
13403 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13404 Remote protocol specific variables\n\
13405 Configure various remote-protocol specific variables such as\n\
13406 the packets being used"),
13407 &remote_show_cmdlist, "show remote ",
13408 0 /* allow-unknown */, &showlist);
13409
13410 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13411 Compare section data on target to the exec file.\n\
13412 Argument is a single section name (default: all loaded sections).\n\
13413 To compare only read-only loaded sections, specify the -r option."),
13414 &cmdlist);
13415
13416 add_cmd ("packet", class_maintenance, packet_command, _("\
13417 Send an arbitrary packet to a remote target.\n\
13418 maintenance packet TEXT\n\
13419 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13420 this command sends the string TEXT to the inferior, and displays the\n\
13421 response packet. GDB supplies the initial `$' character, and the\n\
13422 terminating `#' character and checksum."),
13423 &maintenancelist);
13424
13425 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13426 Set whether to send break if interrupted."), _("\
13427 Show whether to send break if interrupted."), _("\
13428 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13429 set_remotebreak, show_remotebreak,
13430 &setlist, &showlist);
13431 cmd_name = "remotebreak";
13432 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13433 deprecate_cmd (cmd, "set remote interrupt-sequence");
13434 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13435 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13436 deprecate_cmd (cmd, "show remote interrupt-sequence");
13437
13438 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13439 interrupt_sequence_modes, &interrupt_sequence_mode,
13440 _("\
13441 Set interrupt sequence to remote target."), _("\
13442 Show interrupt sequence to remote target."), _("\
13443 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13444 NULL, show_interrupt_sequence,
13445 &remote_set_cmdlist,
13446 &remote_show_cmdlist);
13447
13448 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13449 &interrupt_on_connect, _("\
13450 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13451 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13452 If set, interrupt sequence is sent to remote target."),
13453 NULL, NULL,
13454 &remote_set_cmdlist, &remote_show_cmdlist);
13455
13456 /* Install commands for configuring memory read/write packets. */
13457
13458 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13459 Set the maximum number of bytes per memory write packet (deprecated)."),
13460 &setlist);
13461 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13462 Show the maximum number of bytes per memory write packet (deprecated)."),
13463 &showlist);
13464 add_cmd ("memory-write-packet-size", no_class,
13465 set_memory_write_packet_size, _("\
13466 Set the maximum number of bytes per memory-write packet.\n\
13467 Specify the number of bytes in a packet or 0 (zero) for the\n\
13468 default packet size. The actual limit is further reduced\n\
13469 dependent on the target. Specify ``fixed'' to disable the\n\
13470 further restriction and ``limit'' to enable that restriction."),
13471 &remote_set_cmdlist);
13472 add_cmd ("memory-read-packet-size", no_class,
13473 set_memory_read_packet_size, _("\
13474 Set the maximum number of bytes per memory-read packet.\n\
13475 Specify the number of bytes in a packet or 0 (zero) for the\n\
13476 default packet size. The actual limit is further reduced\n\
13477 dependent on the target. Specify ``fixed'' to disable the\n\
13478 further restriction and ``limit'' to enable that restriction."),
13479 &remote_set_cmdlist);
13480 add_cmd ("memory-write-packet-size", no_class,
13481 show_memory_write_packet_size,
13482 _("Show the maximum number of bytes per memory-write packet."),
13483 &remote_show_cmdlist);
13484 add_cmd ("memory-read-packet-size", no_class,
13485 show_memory_read_packet_size,
13486 _("Show the maximum number of bytes per memory-read packet."),
13487 &remote_show_cmdlist);
13488
13489 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13490 &remote_hw_watchpoint_limit, _("\
13491 Set the maximum number of target hardware watchpoints."), _("\
13492 Show the maximum number of target hardware watchpoints."), _("\
13493 Specify a negative limit for unlimited."),
13494 NULL, NULL, /* FIXME: i18n: The maximum
13495 number of target hardware
13496 watchpoints is %s. */
13497 &remote_set_cmdlist, &remote_show_cmdlist);
13498 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13499 &remote_hw_watchpoint_length_limit, _("\
13500 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13501 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13502 Specify a negative limit for unlimited."),
13503 NULL, NULL, /* FIXME: i18n: The maximum
13504 length (in bytes) of a target
13505 hardware watchpoint is %s. */
13506 &remote_set_cmdlist, &remote_show_cmdlist);
13507 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13508 &remote_hw_breakpoint_limit, _("\
13509 Set the maximum number of target hardware breakpoints."), _("\
13510 Show the maximum number of target hardware breakpoints."), _("\
13511 Specify a negative limit for unlimited."),
13512 NULL, NULL, /* FIXME: i18n: The maximum
13513 number of target hardware
13514 breakpoints is %s. */
13515 &remote_set_cmdlist, &remote_show_cmdlist);
13516
13517 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13518 &remote_address_size, _("\
13519 Set the maximum size of the address (in bits) in a memory packet."), _("\
13520 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13521 NULL,
13522 NULL, /* FIXME: i18n: */
13523 &setlist, &showlist);
13524
13525 init_all_packet_configs ();
13526
13527 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13528 "X", "binary-download", 1);
13529
13530 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13531 "vCont", "verbose-resume", 0);
13532
13533 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13534 "QPassSignals", "pass-signals", 0);
13535
13536 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13537 "QProgramSignals", "program-signals", 0);
13538
13539 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13540 "qSymbol", "symbol-lookup", 0);
13541
13542 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13543 "P", "set-register", 1);
13544
13545 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13546 "p", "fetch-register", 1);
13547
13548 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13549 "Z0", "software-breakpoint", 0);
13550
13551 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13552 "Z1", "hardware-breakpoint", 0);
13553
13554 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13555 "Z2", "write-watchpoint", 0);
13556
13557 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13558 "Z3", "read-watchpoint", 0);
13559
13560 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13561 "Z4", "access-watchpoint", 0);
13562
13563 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13564 "qXfer:auxv:read", "read-aux-vector", 0);
13565
13566 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13567 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13568
13569 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13570 "qXfer:features:read", "target-features", 0);
13571
13572 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13573 "qXfer:libraries:read", "library-info", 0);
13574
13575 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13576 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13577
13578 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13579 "qXfer:memory-map:read", "memory-map", 0);
13580
13581 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13582 "qXfer:spu:read", "read-spu-object", 0);
13583
13584 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13585 "qXfer:spu:write", "write-spu-object", 0);
13586
13587 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13588 "qXfer:osdata:read", "osdata", 0);
13589
13590 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13591 "qXfer:threads:read", "threads", 0);
13592
13593 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13594 "qXfer:siginfo:read", "read-siginfo-object", 0);
13595
13596 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13597 "qXfer:siginfo:write", "write-siginfo-object", 0);
13598
13599 add_packet_config_cmd
13600 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13601 "qXfer:traceframe-info:read", "traceframe-info", 0);
13602
13603 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13604 "qXfer:uib:read", "unwind-info-block", 0);
13605
13606 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13607 "qGetTLSAddr", "get-thread-local-storage-address",
13608 0);
13609
13610 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13611 "qGetTIBAddr", "get-thread-information-block-address",
13612 0);
13613
13614 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13615 "bc", "reverse-continue", 0);
13616
13617 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13618 "bs", "reverse-step", 0);
13619
13620 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13621 "qSupported", "supported-packets", 0);
13622
13623 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13624 "qSearch:memory", "search-memory", 0);
13625
13626 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13627 "qTStatus", "trace-status", 0);
13628
13629 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13630 "vFile:setfs", "hostio-setfs", 0);
13631
13632 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13633 "vFile:open", "hostio-open", 0);
13634
13635 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13636 "vFile:pread", "hostio-pread", 0);
13637
13638 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13639 "vFile:pwrite", "hostio-pwrite", 0);
13640
13641 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13642 "vFile:close", "hostio-close", 0);
13643
13644 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13645 "vFile:unlink", "hostio-unlink", 0);
13646
13647 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13648 "vFile:readlink", "hostio-readlink", 0);
13649
13650 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13651 "vFile:fstat", "hostio-fstat", 0);
13652
13653 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13654 "vAttach", "attach", 0);
13655
13656 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13657 "vRun", "run", 0);
13658
13659 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13660 "QStartNoAckMode", "noack", 0);
13661
13662 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13663 "vKill", "kill", 0);
13664
13665 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13666 "qAttached", "query-attached", 0);
13667
13668 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13669 "ConditionalTracepoints",
13670 "conditional-tracepoints", 0);
13671
13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13673 "ConditionalBreakpoints",
13674 "conditional-breakpoints", 0);
13675
13676 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13677 "BreakpointCommands",
13678 "breakpoint-commands", 0);
13679
13680 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13681 "FastTracepoints", "fast-tracepoints", 0);
13682
13683 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13684 "TracepointSource", "TracepointSource", 0);
13685
13686 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13687 "QAllow", "allow", 0);
13688
13689 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13690 "StaticTracepoints", "static-tracepoints", 0);
13691
13692 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13693 "InstallInTrace", "install-in-trace", 0);
13694
13695 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13696 "qXfer:statictrace:read", "read-sdata-object", 0);
13697
13698 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13699 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13700
13701 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13702 "QDisableRandomization", "disable-randomization", 0);
13703
13704 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13705 "QAgent", "agent", 0);
13706
13707 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13708 "QTBuffer:size", "trace-buffer-size", 0);
13709
13710 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13711 "Qbtrace:off", "disable-btrace", 0);
13712
13713 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13714 "Qbtrace:bts", "enable-btrace-bts", 0);
13715
13716 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13717 "Qbtrace:pt", "enable-btrace-pt", 0);
13718
13719 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13720 "qXfer:btrace", "read-btrace", 0);
13721
13722 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13723 "qXfer:btrace-conf", "read-btrace-conf", 0);
13724
13725 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13726 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13727
13728 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13729 "multiprocess-feature", "multiprocess-feature", 0);
13730
13731 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13732 "swbreak-feature", "swbreak-feature", 0);
13733
13734 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13735 "hwbreak-feature", "hwbreak-feature", 0);
13736
13737 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13738 "fork-event-feature", "fork-event-feature", 0);
13739
13740 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13741 "vfork-event-feature", "vfork-event-feature", 0);
13742
13743 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13744 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13745
13746 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13747 "vContSupported", "verbose-resume-supported", 0);
13748
13749 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13750 "exec-event-feature", "exec-event-feature", 0);
13751
13752 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13753 "vCtrlC", "ctrl-c", 0);
13754
13755 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13756 "QThreadEvents", "thread-events", 0);
13757
13758 /* Assert that we've registered "set remote foo-packet" commands
13759 for all packet configs. */
13760 {
13761 int i;
13762
13763 for (i = 0; i < PACKET_MAX; i++)
13764 {
13765 /* Ideally all configs would have a command associated. Some
13766 still don't though. */
13767 int excepted;
13768
13769 switch (i)
13770 {
13771 case PACKET_QNonStop:
13772 case PACKET_EnableDisableTracepoints_feature:
13773 case PACKET_tracenz_feature:
13774 case PACKET_DisconnectedTracing_feature:
13775 case PACKET_augmented_libraries_svr4_read_feature:
13776 case PACKET_qCRC:
13777 /* Additions to this list need to be well justified:
13778 pre-existing packets are OK; new packets are not. */
13779 excepted = 1;
13780 break;
13781 default:
13782 excepted = 0;
13783 break;
13784 }
13785
13786 /* This catches both forgetting to add a config command, and
13787 forgetting to remove a packet from the exception list. */
13788 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13789 }
13790 }
13791
13792 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13793 Z sub-packet has its own set and show commands, but users may
13794 have sets to this variable in their .gdbinit files (or in their
13795 documentation). */
13796 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13797 &remote_Z_packet_detect, _("\
13798 Set use of remote protocol `Z' packets"), _("\
13799 Show use of remote protocol `Z' packets "), _("\
13800 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13801 packets."),
13802 set_remote_protocol_Z_packet_cmd,
13803 show_remote_protocol_Z_packet_cmd,
13804 /* FIXME: i18n: Use of remote protocol
13805 `Z' packets is %s. */
13806 &remote_set_cmdlist, &remote_show_cmdlist);
13807
13808 add_prefix_cmd ("remote", class_files, remote_command, _("\
13809 Manipulate files on the remote system\n\
13810 Transfer files to and from the remote target system."),
13811 &remote_cmdlist, "remote ",
13812 0 /* allow-unknown */, &cmdlist);
13813
13814 add_cmd ("put", class_files, remote_put_command,
13815 _("Copy a local file to the remote system."),
13816 &remote_cmdlist);
13817
13818 add_cmd ("get", class_files, remote_get_command,
13819 _("Copy a remote file to the local system."),
13820 &remote_cmdlist);
13821
13822 add_cmd ("delete", class_files, remote_delete_command,
13823 _("Delete a remote file."),
13824 &remote_cmdlist);
13825
13826 add_setshow_string_noescape_cmd ("exec-file", class_files,
13827 &remote_exec_file_var, _("\
13828 Set the remote pathname for \"run\""), _("\
13829 Show the remote pathname for \"run\""), NULL,
13830 set_remote_exec_file,
13831 show_remote_exec_file,
13832 &remote_set_cmdlist,
13833 &remote_show_cmdlist);
13834
13835 add_setshow_boolean_cmd ("range-stepping", class_run,
13836 &use_range_stepping, _("\
13837 Enable or disable range stepping."), _("\
13838 Show whether target-assisted range stepping is enabled."), _("\
13839 If on, and the target supports it, when stepping a source line, GDB\n\
13840 tells the target to step the corresponding range of addresses itself instead\n\
13841 of issuing multiple single-steps. This speeds up source level\n\
13842 stepping. If off, GDB always issues single-steps, even if range\n\
13843 stepping is supported by the target. The default is on."),
13844 set_range_stepping,
13845 show_range_stepping,
13846 &setlist,
13847 &showlist);
13848
13849 /* Eventually initialize fileio. See fileio.c */
13850 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13851
13852 /* Take advantage of the fact that the TID field is not used, to tag
13853 special ptids with it set to != 0. */
13854 magic_null_ptid = ptid_build (42000, -1, 1);
13855 not_sent_ptid = ptid_build (42000, -2, 1);
13856 any_thread_ptid = ptid_build (42000, 0, 1);
13857
13858 target_buf_size = 2048;
13859 target_buf = (char *) xmalloc (target_buf_size);
13860 }
13861