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