btrace: Resume recording after disconnect.
[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 #include "record-btrace.h"
74
75 /* Temp hacks for tracepoint encoding migration. */
76 static char *target_buf;
77 static long target_buf_size;
78
79 /* Per-program-space data key. */
80 static const struct program_space_data *remote_pspace_data;
81
82 /* The variable registered as the control variable used by the
83 remote exec-file commands. While the remote exec-file setting is
84 per-program-space, the set/show machinery uses this as the
85 location of the remote exec-file value. */
86 static char *remote_exec_file_var;
87
88 /* The size to align memory write packets, when practical. The protocol
89 does not guarantee any alignment, and gdb will generate short
90 writes and unaligned writes, but even as a best-effort attempt this
91 can improve bulk transfers. For instance, if a write is misaligned
92 relative to the target's data bus, the stub may need to make an extra
93 round trip fetching data from the target. This doesn't make a
94 huge difference, but it's easy to do, so we try to be helpful.
95
96 The alignment chosen is arbitrary; usually data bus width is
97 important here, not the possibly larger cache line size. */
98 enum { REMOTE_ALIGN_WRITES = 16 };
99
100 /* Prototypes for local functions. */
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 remote_files_info (struct target_ops *ignore);
106
107 static void remote_prepare_to_store (struct target_ops *self,
108 struct regcache *regcache);
109
110 static void remote_open_1 (const char *, int, struct target_ops *,
111 int extended_p);
112
113 static void remote_close (struct target_ops *self);
114
115 struct remote_state;
116
117 static int remote_vkill (int pid, struct remote_state *rs);
118
119 static void remote_kill_k (void);
120
121 static void remote_mourn (struct target_ops *ops);
122
123 static void extended_remote_restart (void);
124
125 static void remote_send (char **buf, long *sizeof_buf_p);
126
127 static int readchar (int timeout);
128
129 static void remote_serial_write (const char *str, int len);
130
131 static void remote_kill (struct target_ops *ops);
132
133 static int remote_can_async_p (struct target_ops *);
134
135 static int remote_is_async_p (struct target_ops *);
136
137 static void remote_async (struct target_ops *ops, int enable);
138
139 static void remote_thread_events (struct target_ops *ops, int enable);
140
141 static void interrupt_query (void);
142
143 static void set_general_thread (struct ptid ptid);
144 static void set_continue_thread (struct ptid ptid);
145
146 static void get_offsets (void);
147
148 static void skip_frame (void);
149
150 static long read_frame (char **buf_p, long *sizeof_buf);
151
152 static int hexnumlen (ULONGEST num);
153
154 static void init_remote_ops (void);
155
156 static void init_extended_remote_ops (void);
157
158 static void remote_stop (struct target_ops *self, ptid_t);
159
160 static int stubhex (int ch);
161
162 static int hexnumstr (char *, ULONGEST);
163
164 static int hexnumnstr (char *, ULONGEST, int);
165
166 static CORE_ADDR remote_address_masked (CORE_ADDR);
167
168 static void print_packet (const char *);
169
170 static void compare_sections_command (char *, int);
171
172 static void packet_command (char *, int);
173
174 static int stub_unpack_int (char *buff, int fieldlength);
175
176 static ptid_t remote_current_thread (ptid_t oldptid);
177
178 static int putpkt_binary (const char *buf, int cnt);
179
180 static void check_binary_download (CORE_ADDR addr);
181
182 struct packet_config;
183
184 static void show_packet_config_cmd (struct packet_config *config);
185
186 static void show_remote_protocol_packet_cmd (struct ui_file *file,
187 int from_tty,
188 struct cmd_list_element *c,
189 const char *value);
190
191 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
192 static ptid_t read_ptid (char *buf, char **obuf);
193
194 static void remote_set_permissions (struct target_ops *self);
195
196 static int remote_get_trace_status (struct target_ops *self,
197 struct trace_status *ts);
198
199 static int remote_upload_tracepoints (struct target_ops *self,
200 struct uploaded_tp **utpp);
201
202 static int remote_upload_trace_state_variables (struct target_ops *self,
203 struct uploaded_tsv **utsvp);
204
205 static void remote_query_supported (void);
206
207 static void remote_check_symbols (void);
208
209 void _initialize_remote (void);
210
211 struct stop_reply;
212 static void stop_reply_xfree (struct stop_reply *);
213 static void remote_parse_stop_reply (char *, struct stop_reply *);
214 static void push_stop_reply (struct stop_reply *);
215 static void discard_pending_stop_replies_in_queue (struct remote_state *);
216 static int peek_stop_reply (ptid_t ptid);
217
218 struct threads_listing_context;
219 static void remove_new_fork_children (struct threads_listing_context *);
220
221 static void remote_async_inferior_event_handler (gdb_client_data);
222
223 static void remote_terminal_ours (struct target_ops *self);
224
225 static int remote_read_description_p (struct target_ops *target);
226
227 static void remote_console_output (char *msg);
228
229 static int remote_supports_cond_breakpoints (struct target_ops *self);
230
231 static int remote_can_run_breakpoint_commands (struct target_ops *self);
232
233 static void remote_btrace_reset (void);
234
235 static void remote_btrace_maybe_reopen (void);
236
237 static int stop_reply_queue_length (void);
238
239 static void readahead_cache_invalidate (void);
240
241 static void remote_unpush_and_throw (void);
242
243 /* For "remote". */
244
245 static struct cmd_list_element *remote_cmdlist;
246
247 /* For "set remote" and "show remote". */
248
249 static struct cmd_list_element *remote_set_cmdlist;
250 static struct cmd_list_element *remote_show_cmdlist;
251
252 /* Stub vCont actions support.
253
254 Each field is a boolean flag indicating whether the stub reports
255 support for the corresponding action. */
256
257 struct vCont_action_support
258 {
259 /* vCont;t */
260 int t;
261
262 /* vCont;r */
263 int r;
264
265 /* vCont;s */
266 int s;
267
268 /* vCont;S */
269 int S;
270 };
271
272 /* Controls whether GDB is willing to use range stepping. */
273
274 static int use_range_stepping = 1;
275
276 #define OPAQUETHREADBYTES 8
277
278 /* a 64 bit opaque identifier */
279 typedef unsigned char threadref[OPAQUETHREADBYTES];
280
281 /* About this many threadisds fit in a packet. */
282
283 #define MAXTHREADLISTRESULTS 32
284
285 /* Data for the vFile:pread readahead cache. */
286
287 struct readahead_cache
288 {
289 /* The file descriptor for the file that is being cached. -1 if the
290 cache is invalid. */
291 int fd;
292
293 /* The offset into the file that the cache buffer corresponds
294 to. */
295 ULONGEST offset;
296
297 /* The buffer holding the cache contents. */
298 gdb_byte *buf;
299 /* The buffer's size. We try to read as much as fits into a packet
300 at a time. */
301 size_t bufsize;
302
303 /* Cache hit and miss counters. */
304 ULONGEST hit_count;
305 ULONGEST miss_count;
306 };
307
308 /* Description of the remote protocol state for the currently
309 connected target. This is per-target state, and independent of the
310 selected architecture. */
311
312 struct remote_state
313 {
314 /* A buffer to use for incoming packets, and its current size. The
315 buffer is grown dynamically for larger incoming packets.
316 Outgoing packets may also be constructed in this buffer.
317 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
318 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
319 packets. */
320 char *buf;
321 long buf_size;
322
323 /* True if we're going through initial connection setup (finding out
324 about the remote side's threads, relocating symbols, etc.). */
325 int starting_up;
326
327 /* If we negotiated packet size explicitly (and thus can bypass
328 heuristics for the largest packet size that will not overflow
329 a buffer in the stub), this will be set to that packet size.
330 Otherwise zero, meaning to use the guessed size. */
331 long explicit_packet_size;
332
333 /* remote_wait is normally called when the target is running and
334 waits for a stop reply packet. But sometimes we need to call it
335 when the target is already stopped. We can send a "?" packet
336 and have remote_wait read the response. Or, if we already have
337 the response, we can stash it in BUF and tell remote_wait to
338 skip calling getpkt. This flag is set when BUF contains a
339 stop reply packet and the target is not waiting. */
340 int cached_wait_status;
341
342 /* True, if in no ack mode. That is, neither GDB nor the stub will
343 expect acks from each other. The connection is assumed to be
344 reliable. */
345 int noack_mode;
346
347 /* True if we're connected in extended remote mode. */
348 int extended;
349
350 /* True if we resumed the target and we're waiting for the target to
351 stop. In the mean time, we can't start another command/query.
352 The remote server wouldn't be ready to process it, so we'd
353 timeout waiting for a reply that would never come and eventually
354 we'd close the connection. This can happen in asynchronous mode
355 because we allow GDB commands while the target is running. */
356 int waiting_for_stop_reply;
357
358 /* The status of the stub support for the various vCont actions. */
359 struct vCont_action_support supports_vCont;
360
361 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
362 responded to that. */
363 int ctrlc_pending_p;
364
365 /* True if we saw a Ctrl-C while reading or writing from/to the
366 remote descriptor. At that point it is not safe to send a remote
367 interrupt packet, so we instead remember we saw the Ctrl-C and
368 process it once we're done with sending/receiving the current
369 packet, which should be shortly. If however that takes too long,
370 and the user presses Ctrl-C again, we offer to disconnect. */
371 int got_ctrlc_during_io;
372
373 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
374 remote_open knows that we don't have a file open when the program
375 starts. */
376 struct serial *remote_desc;
377
378 /* These are the threads which we last sent to the remote system. The
379 TID member will be -1 for all or -2 for not sent yet. */
380 ptid_t general_thread;
381 ptid_t continue_thread;
382
383 /* This is the traceframe which we last selected on the remote system.
384 It will be -1 if no traceframe is selected. */
385 int remote_traceframe_number;
386
387 char *last_pass_packet;
388
389 /* The last QProgramSignals packet sent to the target. We bypass
390 sending a new program signals list down to the target if the new
391 packet is exactly the same as the last we sent. IOW, we only let
392 the target know about program signals list changes. */
393 char *last_program_signals_packet;
394
395 enum gdb_signal last_sent_signal;
396
397 int last_sent_step;
398
399 /* The execution direction of the last resume we got. */
400 enum exec_direction_kind last_resume_exec_dir;
401
402 char *finished_object;
403 char *finished_annex;
404 ULONGEST finished_offset;
405
406 /* Should we try the 'ThreadInfo' query packet?
407
408 This variable (NOT available to the user: auto-detect only!)
409 determines whether GDB will use the new, simpler "ThreadInfo"
410 query or the older, more complex syntax for thread queries.
411 This is an auto-detect variable (set to true at each connect,
412 and set to false when the target fails to recognize it). */
413 int use_threadinfo_query;
414 int use_threadextra_query;
415
416 threadref echo_nextthread;
417 threadref nextthread;
418 threadref resultthreadlist[MAXTHREADLISTRESULTS];
419
420 /* The state of remote notification. */
421 struct remote_notif_state *notif_state;
422
423 /* The branch trace configuration. */
424 struct btrace_config btrace_config;
425
426 /* The argument to the last "vFile:setfs:" packet we sent, used
427 to avoid sending repeated unnecessary "vFile:setfs:" packets.
428 Initialized to -1 to indicate that no "vFile:setfs:" packet
429 has yet been sent. */
430 int fs_pid;
431
432 /* A readahead cache for vFile:pread. Often, reading a binary
433 involves a sequence of small reads. E.g., when parsing an ELF
434 file. A readahead cache helps mostly the case of remote
435 debugging on a connection with higher latency, due to the
436 request/reply nature of the RSP. We only cache data for a single
437 file descriptor at a time. */
438 struct readahead_cache readahead_cache;
439 };
440
441 /* Private data that we'll store in (struct thread_info)->private. */
442 struct private_thread_info
443 {
444 char *extra;
445 char *name;
446 int core;
447
448 /* Whether the target stopped for a breakpoint/watchpoint. */
449 enum target_stop_reason stop_reason;
450
451 /* This is set to the data address of the access causing the target
452 to stop for a watchpoint. */
453 CORE_ADDR watch_data_address;
454 };
455
456 static void
457 free_private_thread_info (struct private_thread_info *info)
458 {
459 xfree (info->extra);
460 xfree (info->name);
461 xfree (info);
462 }
463
464 /* This data could be associated with a target, but we do not always
465 have access to the current target when we need it, so for now it is
466 static. This will be fine for as long as only one target is in use
467 at a time. */
468 static struct remote_state *remote_state;
469
470 static struct remote_state *
471 get_remote_state_raw (void)
472 {
473 return remote_state;
474 }
475
476 /* Allocate a new struct remote_state with xmalloc, initialize it, and
477 return it. */
478
479 static struct remote_state *
480 new_remote_state (void)
481 {
482 struct remote_state *result = XCNEW (struct remote_state);
483
484 /* The default buffer size is unimportant; it will be expanded
485 whenever a larger buffer is needed. */
486 result->buf_size = 400;
487 result->buf = (char *) xmalloc (result->buf_size);
488 result->remote_traceframe_number = -1;
489 result->last_sent_signal = GDB_SIGNAL_0;
490 result->last_resume_exec_dir = EXEC_FORWARD;
491 result->fs_pid = -1;
492
493 return result;
494 }
495
496 /* Description of the remote protocol for a given architecture. */
497
498 struct packet_reg
499 {
500 long offset; /* Offset into G packet. */
501 long regnum; /* GDB's internal register number. */
502 LONGEST pnum; /* Remote protocol register number. */
503 int in_g_packet; /* Always part of G packet. */
504 /* long size in bytes; == register_size (target_gdbarch (), regnum);
505 at present. */
506 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
507 at present. */
508 };
509
510 struct remote_arch_state
511 {
512 /* Description of the remote protocol registers. */
513 long sizeof_g_packet;
514
515 /* Description of the remote protocol registers indexed by REGNUM
516 (making an array gdbarch_num_regs in size). */
517 struct packet_reg *regs;
518
519 /* This is the size (in chars) of the first response to the ``g''
520 packet. It is used as a heuristic when determining the maximum
521 size of memory-read and memory-write packets. A target will
522 typically only reserve a buffer large enough to hold the ``g''
523 packet. The size does not include packet overhead (headers and
524 trailers). */
525 long actual_register_packet_size;
526
527 /* This is the maximum size (in chars) of a non read/write packet.
528 It is also used as a cap on the size of read/write packets. */
529 long remote_packet_size;
530 };
531
532 /* Utility: generate error from an incoming stub packet. */
533 static void
534 trace_error (char *buf)
535 {
536 if (*buf++ != 'E')
537 return; /* not an error msg */
538 switch (*buf)
539 {
540 case '1': /* malformed packet error */
541 if (*++buf == '0') /* general case: */
542 error (_("remote.c: error in outgoing packet."));
543 else
544 error (_("remote.c: error in outgoing packet at field #%ld."),
545 strtol (buf, NULL, 16));
546 default:
547 error (_("Target returns error code '%s'."), buf);
548 }
549 }
550
551 /* Utility: wait for reply from stub, while accepting "O" packets. */
552 static char *
553 remote_get_noisy_reply (char **buf_p,
554 long *sizeof_buf)
555 {
556 do /* Loop on reply from remote stub. */
557 {
558 char *buf;
559
560 QUIT; /* Allow user to bail out with ^C. */
561 getpkt (buf_p, sizeof_buf, 0);
562 buf = *buf_p;
563 if (buf[0] == 'E')
564 trace_error (buf);
565 else if (startswith (buf, "qRelocInsn:"))
566 {
567 ULONGEST ul;
568 CORE_ADDR from, to, org_to;
569 char *p, *pp;
570 int adjusted_size = 0;
571 int relocated = 0;
572
573 p = buf + strlen ("qRelocInsn:");
574 pp = unpack_varlen_hex (p, &ul);
575 if (*pp != ';')
576 error (_("invalid qRelocInsn packet: %s"), buf);
577 from = ul;
578
579 p = pp + 1;
580 unpack_varlen_hex (p, &ul);
581 to = ul;
582
583 org_to = to;
584
585 TRY
586 {
587 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
588 relocated = 1;
589 }
590 CATCH (ex, RETURN_MASK_ALL)
591 {
592 if (ex.error == MEMORY_ERROR)
593 {
594 /* Propagate memory errors silently back to the
595 target. The stub may have limited the range of
596 addresses we can write to, for example. */
597 }
598 else
599 {
600 /* Something unexpectedly bad happened. Be verbose
601 so we can tell what, and propagate the error back
602 to the stub, so it doesn't get stuck waiting for
603 a response. */
604 exception_fprintf (gdb_stderr, ex,
605 _("warning: relocating instruction: "));
606 }
607 putpkt ("E01");
608 }
609 END_CATCH
610
611 if (relocated)
612 {
613 adjusted_size = to - org_to;
614
615 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
616 putpkt (buf);
617 }
618 }
619 else if (buf[0] == 'O' && buf[1] != 'K')
620 remote_console_output (buf + 1); /* 'O' message from stub */
621 else
622 return buf; /* Here's the actual reply. */
623 }
624 while (1);
625 }
626
627 /* Handle for retreving the remote protocol data from gdbarch. */
628 static struct gdbarch_data *remote_gdbarch_data_handle;
629
630 static struct remote_arch_state *
631 get_remote_arch_state (void)
632 {
633 gdb_assert (target_gdbarch () != NULL);
634 return ((struct remote_arch_state *)
635 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
636 }
637
638 /* Fetch the global remote target state. */
639
640 static struct remote_state *
641 get_remote_state (void)
642 {
643 /* Make sure that the remote architecture state has been
644 initialized, because doing so might reallocate rs->buf. Any
645 function which calls getpkt also needs to be mindful of changes
646 to rs->buf, but this call limits the number of places which run
647 into trouble. */
648 get_remote_arch_state ();
649
650 return get_remote_state_raw ();
651 }
652
653 /* Cleanup routine for the remote module's pspace data. */
654
655 static void
656 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
657 {
658 char *remote_exec_file = (char *) arg;
659
660 xfree (remote_exec_file);
661 }
662
663 /* Fetch the remote exec-file from the current program space. */
664
665 static const char *
666 get_remote_exec_file (void)
667 {
668 char *remote_exec_file;
669
670 remote_exec_file
671 = (char *) program_space_data (current_program_space,
672 remote_pspace_data);
673 if (remote_exec_file == NULL)
674 return "";
675
676 return remote_exec_file;
677 }
678
679 /* Set the remote exec file for PSPACE. */
680
681 static void
682 set_pspace_remote_exec_file (struct program_space *pspace,
683 char *remote_exec_file)
684 {
685 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
686
687 xfree (old_file);
688 set_program_space_data (pspace, remote_pspace_data,
689 xstrdup (remote_exec_file));
690 }
691
692 /* The "set/show remote exec-file" set command hook. */
693
694 static void
695 set_remote_exec_file (char *ignored, int from_tty,
696 struct cmd_list_element *c)
697 {
698 gdb_assert (remote_exec_file_var != NULL);
699 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
700 }
701
702 /* The "set/show remote exec-file" show command hook. */
703
704 static void
705 show_remote_exec_file (struct ui_file *file, int from_tty,
706 struct cmd_list_element *cmd, const char *value)
707 {
708 fprintf_filtered (file, "%s\n", remote_exec_file_var);
709 }
710
711 static int
712 compare_pnums (const void *lhs_, const void *rhs_)
713 {
714 const struct packet_reg * const *lhs
715 = (const struct packet_reg * const *) lhs_;
716 const struct packet_reg * const *rhs
717 = (const struct packet_reg * const *) rhs_;
718
719 if ((*lhs)->pnum < (*rhs)->pnum)
720 return -1;
721 else if ((*lhs)->pnum == (*rhs)->pnum)
722 return 0;
723 else
724 return 1;
725 }
726
727 static int
728 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
729 {
730 int regnum, num_remote_regs, offset;
731 struct packet_reg **remote_regs;
732
733 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
734 {
735 struct packet_reg *r = &regs[regnum];
736
737 if (register_size (gdbarch, regnum) == 0)
738 /* Do not try to fetch zero-sized (placeholder) registers. */
739 r->pnum = -1;
740 else
741 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
742
743 r->regnum = regnum;
744 }
745
746 /* Define the g/G packet format as the contents of each register
747 with a remote protocol number, in order of ascending protocol
748 number. */
749
750 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
751 for (num_remote_regs = 0, regnum = 0;
752 regnum < gdbarch_num_regs (gdbarch);
753 regnum++)
754 if (regs[regnum].pnum != -1)
755 remote_regs[num_remote_regs++] = &regs[regnum];
756
757 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
758 compare_pnums);
759
760 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
761 {
762 remote_regs[regnum]->in_g_packet = 1;
763 remote_regs[regnum]->offset = offset;
764 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
765 }
766
767 return offset;
768 }
769
770 /* Given the architecture described by GDBARCH, return the remote
771 protocol register's number and the register's offset in the g/G
772 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
773 If the target does not have a mapping for REGNUM, return false,
774 otherwise, return true. */
775
776 int
777 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
778 int *pnum, int *poffset)
779 {
780 struct packet_reg *regs;
781 struct cleanup *old_chain;
782
783 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
784
785 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
786 old_chain = make_cleanup (xfree, regs);
787
788 map_regcache_remote_table (gdbarch, regs);
789
790 *pnum = regs[regnum].pnum;
791 *poffset = regs[regnum].offset;
792
793 do_cleanups (old_chain);
794
795 return *pnum != -1;
796 }
797
798 static void *
799 init_remote_state (struct gdbarch *gdbarch)
800 {
801 struct remote_state *rs = get_remote_state_raw ();
802 struct remote_arch_state *rsa;
803
804 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
805
806 /* Use the architecture to build a regnum<->pnum table, which will be
807 1:1 unless a feature set specifies otherwise. */
808 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
809 gdbarch_num_regs (gdbarch),
810 struct packet_reg);
811
812 /* Record the maximum possible size of the g packet - it may turn out
813 to be smaller. */
814 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
815
816 /* Default maximum number of characters in a packet body. Many
817 remote stubs have a hardwired buffer size of 400 bytes
818 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
819 as the maximum packet-size to ensure that the packet and an extra
820 NUL character can always fit in the buffer. This stops GDB
821 trashing stubs that try to squeeze an extra NUL into what is
822 already a full buffer (As of 1999-12-04 that was most stubs). */
823 rsa->remote_packet_size = 400 - 1;
824
825 /* This one is filled in when a ``g'' packet is received. */
826 rsa->actual_register_packet_size = 0;
827
828 /* Should rsa->sizeof_g_packet needs more space than the
829 default, adjust the size accordingly. Remember that each byte is
830 encoded as two characters. 32 is the overhead for the packet
831 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
832 (``$NN:G...#NN'') is a better guess, the below has been padded a
833 little. */
834 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
835 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
836
837 /* Make sure that the packet buffer is plenty big enough for
838 this architecture. */
839 if (rs->buf_size < rsa->remote_packet_size)
840 {
841 rs->buf_size = 2 * rsa->remote_packet_size;
842 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
843 }
844
845 return rsa;
846 }
847
848 /* Return the current allowed size of a remote packet. This is
849 inferred from the current architecture, and should be used to
850 limit the length of outgoing packets. */
851 static long
852 get_remote_packet_size (void)
853 {
854 struct remote_state *rs = get_remote_state ();
855 struct remote_arch_state *rsa = get_remote_arch_state ();
856
857 if (rs->explicit_packet_size)
858 return rs->explicit_packet_size;
859
860 return rsa->remote_packet_size;
861 }
862
863 static struct packet_reg *
864 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
865 {
866 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
867 return NULL;
868 else
869 {
870 struct packet_reg *r = &rsa->regs[regnum];
871
872 gdb_assert (r->regnum == regnum);
873 return r;
874 }
875 }
876
877 static struct packet_reg *
878 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
879 {
880 int i;
881
882 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
883 {
884 struct packet_reg *r = &rsa->regs[i];
885
886 if (r->pnum == pnum)
887 return r;
888 }
889 return NULL;
890 }
891
892 static struct target_ops remote_ops;
893
894 static struct target_ops extended_remote_ops;
895
896 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
897 ``forever'' still use the normal timeout mechanism. This is
898 currently used by the ASYNC code to guarentee that target reads
899 during the initial connect always time-out. Once getpkt has been
900 modified to return a timeout indication and, in turn
901 remote_wait()/wait_for_inferior() have gained a timeout parameter
902 this can go away. */
903 static int wait_forever_enabled_p = 1;
904
905 /* Allow the user to specify what sequence to send to the remote
906 when he requests a program interruption: Although ^C is usually
907 what remote systems expect (this is the default, here), it is
908 sometimes preferable to send a break. On other systems such
909 as the Linux kernel, a break followed by g, which is Magic SysRq g
910 is required in order to interrupt the execution. */
911 const char interrupt_sequence_control_c[] = "Ctrl-C";
912 const char interrupt_sequence_break[] = "BREAK";
913 const char interrupt_sequence_break_g[] = "BREAK-g";
914 static const char *const interrupt_sequence_modes[] =
915 {
916 interrupt_sequence_control_c,
917 interrupt_sequence_break,
918 interrupt_sequence_break_g,
919 NULL
920 };
921 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
922
923 static void
924 show_interrupt_sequence (struct ui_file *file, int from_tty,
925 struct cmd_list_element *c,
926 const char *value)
927 {
928 if (interrupt_sequence_mode == interrupt_sequence_control_c)
929 fprintf_filtered (file,
930 _("Send the ASCII ETX character (Ctrl-c) "
931 "to the remote target to interrupt the "
932 "execution of the program.\n"));
933 else if (interrupt_sequence_mode == interrupt_sequence_break)
934 fprintf_filtered (file,
935 _("send a break signal to the remote target "
936 "to interrupt the execution of the program.\n"));
937 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
938 fprintf_filtered (file,
939 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
940 "the remote target to interrupt the execution "
941 "of Linux kernel.\n"));
942 else
943 internal_error (__FILE__, __LINE__,
944 _("Invalid value for interrupt_sequence_mode: %s."),
945 interrupt_sequence_mode);
946 }
947
948 /* This boolean variable specifies whether interrupt_sequence is sent
949 to the remote target when gdb connects to it.
950 This is mostly needed when you debug the Linux kernel: The Linux kernel
951 expects BREAK g which is Magic SysRq g for connecting gdb. */
952 static int interrupt_on_connect = 0;
953
954 /* This variable is used to implement the "set/show remotebreak" commands.
955 Since these commands are now deprecated in favor of "set/show remote
956 interrupt-sequence", it no longer has any effect on the code. */
957 static int remote_break;
958
959 static void
960 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
961 {
962 if (remote_break)
963 interrupt_sequence_mode = interrupt_sequence_break;
964 else
965 interrupt_sequence_mode = interrupt_sequence_control_c;
966 }
967
968 static void
969 show_remotebreak (struct ui_file *file, int from_tty,
970 struct cmd_list_element *c,
971 const char *value)
972 {
973 }
974
975 /* This variable sets the number of bits in an address that are to be
976 sent in a memory ("M" or "m") packet. Normally, after stripping
977 leading zeros, the entire address would be sent. This variable
978 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
979 initial implementation of remote.c restricted the address sent in
980 memory packets to ``host::sizeof long'' bytes - (typically 32
981 bits). Consequently, for 64 bit targets, the upper 32 bits of an
982 address was never sent. Since fixing this bug may cause a break in
983 some remote targets this variable is principly provided to
984 facilitate backward compatibility. */
985
986 static unsigned int remote_address_size;
987
988 /* Temporary to track who currently owns the terminal. See
989 remote_terminal_* for more details. */
990
991 static int remote_async_terminal_ours_p;
992
993 \f
994 /* User configurable variables for the number of characters in a
995 memory read/write packet. MIN (rsa->remote_packet_size,
996 rsa->sizeof_g_packet) is the default. Some targets need smaller
997 values (fifo overruns, et.al.) and some users need larger values
998 (speed up transfers). The variables ``preferred_*'' (the user
999 request), ``current_*'' (what was actually set) and ``forced_*''
1000 (Positive - a soft limit, negative - a hard limit). */
1001
1002 struct memory_packet_config
1003 {
1004 char *name;
1005 long size;
1006 int fixed_p;
1007 };
1008
1009 /* The default max memory-write-packet-size. The 16k is historical.
1010 (It came from older GDB's using alloca for buffers and the
1011 knowledge (folklore?) that some hosts don't cope very well with
1012 large alloca calls.) */
1013 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1014
1015 /* The minimum remote packet size for memory transfers. Ensures we
1016 can write at least one byte. */
1017 #define MIN_MEMORY_PACKET_SIZE 20
1018
1019 /* Compute the current size of a read/write packet. Since this makes
1020 use of ``actual_register_packet_size'' the computation is dynamic. */
1021
1022 static long
1023 get_memory_packet_size (struct memory_packet_config *config)
1024 {
1025 struct remote_state *rs = get_remote_state ();
1026 struct remote_arch_state *rsa = get_remote_arch_state ();
1027
1028 long what_they_get;
1029 if (config->fixed_p)
1030 {
1031 if (config->size <= 0)
1032 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1033 else
1034 what_they_get = config->size;
1035 }
1036 else
1037 {
1038 what_they_get = get_remote_packet_size ();
1039 /* Limit the packet to the size specified by the user. */
1040 if (config->size > 0
1041 && what_they_get > config->size)
1042 what_they_get = config->size;
1043
1044 /* Limit it to the size of the targets ``g'' response unless we have
1045 permission from the stub to use a larger packet size. */
1046 if (rs->explicit_packet_size == 0
1047 && rsa->actual_register_packet_size > 0
1048 && what_they_get > rsa->actual_register_packet_size)
1049 what_they_get = rsa->actual_register_packet_size;
1050 }
1051 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1052 what_they_get = MIN_MEMORY_PACKET_SIZE;
1053
1054 /* Make sure there is room in the global buffer for this packet
1055 (including its trailing NUL byte). */
1056 if (rs->buf_size < what_they_get + 1)
1057 {
1058 rs->buf_size = 2 * what_they_get;
1059 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1060 }
1061
1062 return what_they_get;
1063 }
1064
1065 /* Update the size of a read/write packet. If they user wants
1066 something really big then do a sanity check. */
1067
1068 static void
1069 set_memory_packet_size (char *args, struct memory_packet_config *config)
1070 {
1071 int fixed_p = config->fixed_p;
1072 long size = config->size;
1073
1074 if (args == NULL)
1075 error (_("Argument required (integer, `fixed' or `limited')."));
1076 else if (strcmp (args, "hard") == 0
1077 || strcmp (args, "fixed") == 0)
1078 fixed_p = 1;
1079 else if (strcmp (args, "soft") == 0
1080 || strcmp (args, "limit") == 0)
1081 fixed_p = 0;
1082 else
1083 {
1084 char *end;
1085
1086 size = strtoul (args, &end, 0);
1087 if (args == end)
1088 error (_("Invalid %s (bad syntax)."), config->name);
1089
1090 /* Instead of explicitly capping the size of a packet to or
1091 disallowing it, the user is allowed to set the size to
1092 something arbitrarily large. */
1093 }
1094
1095 /* So that the query shows the correct value. */
1096 if (size <= 0)
1097 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1098
1099 /* Extra checks? */
1100 if (fixed_p && !config->fixed_p)
1101 {
1102 if (! query (_("The target may not be able to correctly handle a %s\n"
1103 "of %ld bytes. Change the packet size? "),
1104 config->name, size))
1105 error (_("Packet size not changed."));
1106 }
1107 /* Update the config. */
1108 config->fixed_p = fixed_p;
1109 config->size = size;
1110 }
1111
1112 static void
1113 show_memory_packet_size (struct memory_packet_config *config)
1114 {
1115 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1116 if (config->fixed_p)
1117 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1118 get_memory_packet_size (config));
1119 else
1120 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1121 get_memory_packet_size (config));
1122 }
1123
1124 static struct memory_packet_config memory_write_packet_config =
1125 {
1126 "memory-write-packet-size",
1127 };
1128
1129 static void
1130 set_memory_write_packet_size (char *args, int from_tty)
1131 {
1132 set_memory_packet_size (args, &memory_write_packet_config);
1133 }
1134
1135 static void
1136 show_memory_write_packet_size (char *args, int from_tty)
1137 {
1138 show_memory_packet_size (&memory_write_packet_config);
1139 }
1140
1141 static long
1142 get_memory_write_packet_size (void)
1143 {
1144 return get_memory_packet_size (&memory_write_packet_config);
1145 }
1146
1147 static struct memory_packet_config memory_read_packet_config =
1148 {
1149 "memory-read-packet-size",
1150 };
1151
1152 static void
1153 set_memory_read_packet_size (char *args, int from_tty)
1154 {
1155 set_memory_packet_size (args, &memory_read_packet_config);
1156 }
1157
1158 static void
1159 show_memory_read_packet_size (char *args, int from_tty)
1160 {
1161 show_memory_packet_size (&memory_read_packet_config);
1162 }
1163
1164 static long
1165 get_memory_read_packet_size (void)
1166 {
1167 long size = get_memory_packet_size (&memory_read_packet_config);
1168
1169 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1170 extra buffer size argument before the memory read size can be
1171 increased beyond this. */
1172 if (size > get_remote_packet_size ())
1173 size = get_remote_packet_size ();
1174 return size;
1175 }
1176
1177 \f
1178 /* Generic configuration support for packets the stub optionally
1179 supports. Allows the user to specify the use of the packet as well
1180 as allowing GDB to auto-detect support in the remote stub. */
1181
1182 enum packet_support
1183 {
1184 PACKET_SUPPORT_UNKNOWN = 0,
1185 PACKET_ENABLE,
1186 PACKET_DISABLE
1187 };
1188
1189 struct packet_config
1190 {
1191 const char *name;
1192 const char *title;
1193
1194 /* If auto, GDB auto-detects support for this packet or feature,
1195 either through qSupported, or by trying the packet and looking
1196 at the response. If true, GDB assumes the target supports this
1197 packet. If false, the packet is disabled. Configs that don't
1198 have an associated command always have this set to auto. */
1199 enum auto_boolean detect;
1200
1201 /* Does the target support this packet? */
1202 enum packet_support support;
1203 };
1204
1205 /* Analyze a packet's return value and update the packet config
1206 accordingly. */
1207
1208 enum packet_result
1209 {
1210 PACKET_ERROR,
1211 PACKET_OK,
1212 PACKET_UNKNOWN
1213 };
1214
1215 static enum packet_support packet_config_support (struct packet_config *config);
1216 static enum packet_support packet_support (int packet);
1217
1218 static void
1219 show_packet_config_cmd (struct packet_config *config)
1220 {
1221 char *support = "internal-error";
1222
1223 switch (packet_config_support (config))
1224 {
1225 case PACKET_ENABLE:
1226 support = "enabled";
1227 break;
1228 case PACKET_DISABLE:
1229 support = "disabled";
1230 break;
1231 case PACKET_SUPPORT_UNKNOWN:
1232 support = "unknown";
1233 break;
1234 }
1235 switch (config->detect)
1236 {
1237 case AUTO_BOOLEAN_AUTO:
1238 printf_filtered (_("Support for the `%s' packet "
1239 "is auto-detected, currently %s.\n"),
1240 config->name, support);
1241 break;
1242 case AUTO_BOOLEAN_TRUE:
1243 case AUTO_BOOLEAN_FALSE:
1244 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1245 config->name, support);
1246 break;
1247 }
1248 }
1249
1250 static void
1251 add_packet_config_cmd (struct packet_config *config, const char *name,
1252 const char *title, int legacy)
1253 {
1254 char *set_doc;
1255 char *show_doc;
1256 char *cmd_name;
1257
1258 config->name = name;
1259 config->title = title;
1260 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1261 name, title);
1262 show_doc = xstrprintf ("Show current use of remote "
1263 "protocol `%s' (%s) packet",
1264 name, title);
1265 /* set/show TITLE-packet {auto,on,off} */
1266 cmd_name = xstrprintf ("%s-packet", title);
1267 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1268 &config->detect, set_doc,
1269 show_doc, NULL, /* help_doc */
1270 NULL,
1271 show_remote_protocol_packet_cmd,
1272 &remote_set_cmdlist, &remote_show_cmdlist);
1273 /* The command code copies the documentation strings. */
1274 xfree (set_doc);
1275 xfree (show_doc);
1276 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1277 if (legacy)
1278 {
1279 char *legacy_name;
1280
1281 legacy_name = xstrprintf ("%s-packet", name);
1282 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1283 &remote_set_cmdlist);
1284 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1285 &remote_show_cmdlist);
1286 }
1287 }
1288
1289 static enum packet_result
1290 packet_check_result (const char *buf)
1291 {
1292 if (buf[0] != '\0')
1293 {
1294 /* The stub recognized the packet request. Check that the
1295 operation succeeded. */
1296 if (buf[0] == 'E'
1297 && isxdigit (buf[1]) && isxdigit (buf[2])
1298 && buf[3] == '\0')
1299 /* "Enn" - definitly an error. */
1300 return PACKET_ERROR;
1301
1302 /* Always treat "E." as an error. This will be used for
1303 more verbose error messages, such as E.memtypes. */
1304 if (buf[0] == 'E' && buf[1] == '.')
1305 return PACKET_ERROR;
1306
1307 /* The packet may or may not be OK. Just assume it is. */
1308 return PACKET_OK;
1309 }
1310 else
1311 /* The stub does not support the packet. */
1312 return PACKET_UNKNOWN;
1313 }
1314
1315 static enum packet_result
1316 packet_ok (const char *buf, struct packet_config *config)
1317 {
1318 enum packet_result result;
1319
1320 if (config->detect != AUTO_BOOLEAN_TRUE
1321 && config->support == PACKET_DISABLE)
1322 internal_error (__FILE__, __LINE__,
1323 _("packet_ok: attempt to use a disabled packet"));
1324
1325 result = packet_check_result (buf);
1326 switch (result)
1327 {
1328 case PACKET_OK:
1329 case PACKET_ERROR:
1330 /* The stub recognized the packet request. */
1331 if (config->support == PACKET_SUPPORT_UNKNOWN)
1332 {
1333 if (remote_debug)
1334 fprintf_unfiltered (gdb_stdlog,
1335 "Packet %s (%s) is supported\n",
1336 config->name, config->title);
1337 config->support = PACKET_ENABLE;
1338 }
1339 break;
1340 case PACKET_UNKNOWN:
1341 /* The stub does not support the packet. */
1342 if (config->detect == AUTO_BOOLEAN_AUTO
1343 && config->support == PACKET_ENABLE)
1344 {
1345 /* If the stub previously indicated that the packet was
1346 supported then there is a protocol error. */
1347 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1348 config->name, config->title);
1349 }
1350 else if (config->detect == AUTO_BOOLEAN_TRUE)
1351 {
1352 /* The user set it wrong. */
1353 error (_("Enabled packet %s (%s) not recognized by stub"),
1354 config->name, config->title);
1355 }
1356
1357 if (remote_debug)
1358 fprintf_unfiltered (gdb_stdlog,
1359 "Packet %s (%s) is NOT supported\n",
1360 config->name, config->title);
1361 config->support = PACKET_DISABLE;
1362 break;
1363 }
1364
1365 return result;
1366 }
1367
1368 enum {
1369 PACKET_vCont = 0,
1370 PACKET_X,
1371 PACKET_qSymbol,
1372 PACKET_P,
1373 PACKET_p,
1374 PACKET_Z0,
1375 PACKET_Z1,
1376 PACKET_Z2,
1377 PACKET_Z3,
1378 PACKET_Z4,
1379 PACKET_vFile_setfs,
1380 PACKET_vFile_open,
1381 PACKET_vFile_pread,
1382 PACKET_vFile_pwrite,
1383 PACKET_vFile_close,
1384 PACKET_vFile_unlink,
1385 PACKET_vFile_readlink,
1386 PACKET_vFile_fstat,
1387 PACKET_qXfer_auxv,
1388 PACKET_qXfer_features,
1389 PACKET_qXfer_exec_file,
1390 PACKET_qXfer_libraries,
1391 PACKET_qXfer_libraries_svr4,
1392 PACKET_qXfer_memory_map,
1393 PACKET_qXfer_spu_read,
1394 PACKET_qXfer_spu_write,
1395 PACKET_qXfer_osdata,
1396 PACKET_qXfer_threads,
1397 PACKET_qXfer_statictrace_read,
1398 PACKET_qXfer_traceframe_info,
1399 PACKET_qXfer_uib,
1400 PACKET_qGetTIBAddr,
1401 PACKET_qGetTLSAddr,
1402 PACKET_qSupported,
1403 PACKET_qTStatus,
1404 PACKET_QPassSignals,
1405 PACKET_QCatchSyscalls,
1406 PACKET_QProgramSignals,
1407 PACKET_qCRC,
1408 PACKET_qSearch_memory,
1409 PACKET_vAttach,
1410 PACKET_vRun,
1411 PACKET_QStartNoAckMode,
1412 PACKET_vKill,
1413 PACKET_qXfer_siginfo_read,
1414 PACKET_qXfer_siginfo_write,
1415 PACKET_qAttached,
1416
1417 /* Support for conditional tracepoints. */
1418 PACKET_ConditionalTracepoints,
1419
1420 /* Support for target-side breakpoint conditions. */
1421 PACKET_ConditionalBreakpoints,
1422
1423 /* Support for target-side breakpoint commands. */
1424 PACKET_BreakpointCommands,
1425
1426 /* Support for fast tracepoints. */
1427 PACKET_FastTracepoints,
1428
1429 /* Support for static tracepoints. */
1430 PACKET_StaticTracepoints,
1431
1432 /* Support for installing tracepoints while a trace experiment is
1433 running. */
1434 PACKET_InstallInTrace,
1435
1436 PACKET_bc,
1437 PACKET_bs,
1438 PACKET_TracepointSource,
1439 PACKET_QAllow,
1440 PACKET_qXfer_fdpic,
1441 PACKET_QDisableRandomization,
1442 PACKET_QAgent,
1443 PACKET_QTBuffer_size,
1444 PACKET_Qbtrace_off,
1445 PACKET_Qbtrace_bts,
1446 PACKET_Qbtrace_pt,
1447 PACKET_qXfer_btrace,
1448
1449 /* Support for the QNonStop packet. */
1450 PACKET_QNonStop,
1451
1452 /* Support for the QThreadEvents packet. */
1453 PACKET_QThreadEvents,
1454
1455 /* Support for multi-process extensions. */
1456 PACKET_multiprocess_feature,
1457
1458 /* Support for enabling and disabling tracepoints while a trace
1459 experiment is running. */
1460 PACKET_EnableDisableTracepoints_feature,
1461
1462 /* Support for collecting strings using the tracenz bytecode. */
1463 PACKET_tracenz_feature,
1464
1465 /* Support for continuing to run a trace experiment while GDB is
1466 disconnected. */
1467 PACKET_DisconnectedTracing_feature,
1468
1469 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1470 PACKET_augmented_libraries_svr4_read_feature,
1471
1472 /* Support for the qXfer:btrace-conf:read packet. */
1473 PACKET_qXfer_btrace_conf,
1474
1475 /* Support for the Qbtrace-conf:bts:size packet. */
1476 PACKET_Qbtrace_conf_bts_size,
1477
1478 /* Support for swbreak+ feature. */
1479 PACKET_swbreak_feature,
1480
1481 /* Support for hwbreak+ feature. */
1482 PACKET_hwbreak_feature,
1483
1484 /* Support for fork events. */
1485 PACKET_fork_event_feature,
1486
1487 /* Support for vfork events. */
1488 PACKET_vfork_event_feature,
1489
1490 /* Support for the Qbtrace-conf:pt:size packet. */
1491 PACKET_Qbtrace_conf_pt_size,
1492
1493 /* Support for exec events. */
1494 PACKET_exec_event_feature,
1495
1496 /* Support for query supported vCont actions. */
1497 PACKET_vContSupported,
1498
1499 /* Support remote CTRL-C. */
1500 PACKET_vCtrlC,
1501
1502 /* Support TARGET_WAITKIND_NO_RESUMED. */
1503 PACKET_no_resumed,
1504
1505 PACKET_MAX
1506 };
1507
1508 static struct packet_config remote_protocol_packets[PACKET_MAX];
1509
1510 /* Returns the packet's corresponding "set remote foo-packet" command
1511 state. See struct packet_config for more details. */
1512
1513 static enum auto_boolean
1514 packet_set_cmd_state (int packet)
1515 {
1516 return remote_protocol_packets[packet].detect;
1517 }
1518
1519 /* Returns whether a given packet or feature is supported. This takes
1520 into account the state of the corresponding "set remote foo-packet"
1521 command, which may be used to bypass auto-detection. */
1522
1523 static enum packet_support
1524 packet_config_support (struct packet_config *config)
1525 {
1526 switch (config->detect)
1527 {
1528 case AUTO_BOOLEAN_TRUE:
1529 return PACKET_ENABLE;
1530 case AUTO_BOOLEAN_FALSE:
1531 return PACKET_DISABLE;
1532 case AUTO_BOOLEAN_AUTO:
1533 return config->support;
1534 default:
1535 gdb_assert_not_reached (_("bad switch"));
1536 }
1537 }
1538
1539 /* Same as packet_config_support, but takes the packet's enum value as
1540 argument. */
1541
1542 static enum packet_support
1543 packet_support (int packet)
1544 {
1545 struct packet_config *config = &remote_protocol_packets[packet];
1546
1547 return packet_config_support (config);
1548 }
1549
1550 static void
1551 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1552 struct cmd_list_element *c,
1553 const char *value)
1554 {
1555 struct packet_config *packet;
1556
1557 for (packet = remote_protocol_packets;
1558 packet < &remote_protocol_packets[PACKET_MAX];
1559 packet++)
1560 {
1561 if (&packet->detect == c->var)
1562 {
1563 show_packet_config_cmd (packet);
1564 return;
1565 }
1566 }
1567 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1568 c->name);
1569 }
1570
1571 /* Should we try one of the 'Z' requests? */
1572
1573 enum Z_packet_type
1574 {
1575 Z_PACKET_SOFTWARE_BP,
1576 Z_PACKET_HARDWARE_BP,
1577 Z_PACKET_WRITE_WP,
1578 Z_PACKET_READ_WP,
1579 Z_PACKET_ACCESS_WP,
1580 NR_Z_PACKET_TYPES
1581 };
1582
1583 /* For compatibility with older distributions. Provide a ``set remote
1584 Z-packet ...'' command that updates all the Z packet types. */
1585
1586 static enum auto_boolean remote_Z_packet_detect;
1587
1588 static void
1589 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1590 struct cmd_list_element *c)
1591 {
1592 int i;
1593
1594 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1595 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1596 }
1597
1598 static void
1599 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1600 struct cmd_list_element *c,
1601 const char *value)
1602 {
1603 int i;
1604
1605 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1606 {
1607 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1608 }
1609 }
1610
1611 /* Returns true if the multi-process extensions are in effect. */
1612
1613 static int
1614 remote_multi_process_p (struct remote_state *rs)
1615 {
1616 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1617 }
1618
1619 /* Returns true if fork events are supported. */
1620
1621 static int
1622 remote_fork_event_p (struct remote_state *rs)
1623 {
1624 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1625 }
1626
1627 /* Returns true if vfork events are supported. */
1628
1629 static int
1630 remote_vfork_event_p (struct remote_state *rs)
1631 {
1632 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1633 }
1634
1635 /* Returns true if exec events are supported. */
1636
1637 static int
1638 remote_exec_event_p (struct remote_state *rs)
1639 {
1640 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1641 }
1642
1643 /* Insert fork catchpoint target routine. If fork events are enabled
1644 then return success, nothing more to do. */
1645
1646 static int
1647 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1648 {
1649 struct remote_state *rs = get_remote_state ();
1650
1651 return !remote_fork_event_p (rs);
1652 }
1653
1654 /* Remove fork catchpoint target routine. Nothing to do, just
1655 return success. */
1656
1657 static int
1658 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1659 {
1660 return 0;
1661 }
1662
1663 /* Insert vfork catchpoint target routine. If vfork events are enabled
1664 then return success, nothing more to do. */
1665
1666 static int
1667 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1668 {
1669 struct remote_state *rs = get_remote_state ();
1670
1671 return !remote_vfork_event_p (rs);
1672 }
1673
1674 /* Remove vfork catchpoint target routine. Nothing to do, just
1675 return success. */
1676
1677 static int
1678 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1679 {
1680 return 0;
1681 }
1682
1683 /* Insert exec catchpoint target routine. If exec events are
1684 enabled, just return success. */
1685
1686 static int
1687 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1688 {
1689 struct remote_state *rs = get_remote_state ();
1690
1691 return !remote_exec_event_p (rs);
1692 }
1693
1694 /* Remove exec catchpoint target routine. Nothing to do, just
1695 return success. */
1696
1697 static int
1698 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1699 {
1700 return 0;
1701 }
1702
1703 \f
1704 /* Asynchronous signal handle registered as event loop source for
1705 when we have pending events ready to be passed to the core. */
1706
1707 static struct async_event_handler *remote_async_inferior_event_token;
1708
1709 \f
1710
1711 static ptid_t magic_null_ptid;
1712 static ptid_t not_sent_ptid;
1713 static ptid_t any_thread_ptid;
1714
1715 /* Find out if the stub attached to PID (and hence GDB should offer to
1716 detach instead of killing it when bailing out). */
1717
1718 static int
1719 remote_query_attached (int pid)
1720 {
1721 struct remote_state *rs = get_remote_state ();
1722 size_t size = get_remote_packet_size ();
1723
1724 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1725 return 0;
1726
1727 if (remote_multi_process_p (rs))
1728 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1729 else
1730 xsnprintf (rs->buf, size, "qAttached");
1731
1732 putpkt (rs->buf);
1733 getpkt (&rs->buf, &rs->buf_size, 0);
1734
1735 switch (packet_ok (rs->buf,
1736 &remote_protocol_packets[PACKET_qAttached]))
1737 {
1738 case PACKET_OK:
1739 if (strcmp (rs->buf, "1") == 0)
1740 return 1;
1741 break;
1742 case PACKET_ERROR:
1743 warning (_("Remote failure reply: %s"), rs->buf);
1744 break;
1745 case PACKET_UNKNOWN:
1746 break;
1747 }
1748
1749 return 0;
1750 }
1751
1752 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1753 has been invented by GDB, instead of reported by the target. Since
1754 we can be connected to a remote system before before knowing about
1755 any inferior, mark the target with execution when we find the first
1756 inferior. If ATTACHED is 1, then we had just attached to this
1757 inferior. If it is 0, then we just created this inferior. If it
1758 is -1, then try querying the remote stub to find out if it had
1759 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1760 attempt to open this inferior's executable as the main executable
1761 if no main executable is open already. */
1762
1763 static struct inferior *
1764 remote_add_inferior (int fake_pid_p, int pid, int attached,
1765 int try_open_exec)
1766 {
1767 struct inferior *inf;
1768
1769 /* Check whether this process we're learning about is to be
1770 considered attached, or if is to be considered to have been
1771 spawned by the stub. */
1772 if (attached == -1)
1773 attached = remote_query_attached (pid);
1774
1775 if (gdbarch_has_global_solist (target_gdbarch ()))
1776 {
1777 /* If the target shares code across all inferiors, then every
1778 attach adds a new inferior. */
1779 inf = add_inferior (pid);
1780
1781 /* ... and every inferior is bound to the same program space.
1782 However, each inferior may still have its own address
1783 space. */
1784 inf->aspace = maybe_new_address_space ();
1785 inf->pspace = current_program_space;
1786 }
1787 else
1788 {
1789 /* In the traditional debugging scenario, there's a 1-1 match
1790 between program/address spaces. We simply bind the inferior
1791 to the program space's address space. */
1792 inf = current_inferior ();
1793 inferior_appeared (inf, pid);
1794 }
1795
1796 inf->attach_flag = attached;
1797 inf->fake_pid_p = fake_pid_p;
1798
1799 /* If no main executable is currently open then attempt to
1800 open the file that was executed to create this inferior. */
1801 if (try_open_exec && get_exec_file (0) == NULL)
1802 exec_file_locate_attach (pid, 1);
1803
1804 return inf;
1805 }
1806
1807 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1808 according to RUNNING. */
1809
1810 static void
1811 remote_add_thread (ptid_t ptid, int running, int executing)
1812 {
1813 struct remote_state *rs = get_remote_state ();
1814
1815 /* GDB historically didn't pull threads in the initial connection
1816 setup. If the remote target doesn't even have a concept of
1817 threads (e.g., a bare-metal target), even if internally we
1818 consider that a single-threaded target, mentioning a new thread
1819 might be confusing to the user. Be silent then, preserving the
1820 age old behavior. */
1821 if (rs->starting_up)
1822 add_thread_silent (ptid);
1823 else
1824 add_thread (ptid);
1825
1826 set_executing (ptid, executing);
1827 set_running (ptid, running);
1828 }
1829
1830 /* Come here when we learn about a thread id from the remote target.
1831 It may be the first time we hear about such thread, so take the
1832 opportunity to add it to GDB's thread list. In case this is the
1833 first time we're noticing its corresponding inferior, add it to
1834 GDB's inferior list as well. EXECUTING indicates whether the
1835 thread is (internally) executing or stopped. */
1836
1837 static void
1838 remote_notice_new_inferior (ptid_t currthread, int executing)
1839 {
1840 /* In non-stop mode, we assume new found threads are (externally)
1841 running until proven otherwise with a stop reply. In all-stop,
1842 we can only get here if all threads are stopped. */
1843 int running = target_is_non_stop_p () ? 1 : 0;
1844
1845 /* If this is a new thread, add it to GDB's thread list.
1846 If we leave it up to WFI to do this, bad things will happen. */
1847
1848 if (in_thread_list (currthread) && is_exited (currthread))
1849 {
1850 /* We're seeing an event on a thread id we knew had exited.
1851 This has to be a new thread reusing the old id. Add it. */
1852 remote_add_thread (currthread, running, executing);
1853 return;
1854 }
1855
1856 if (!in_thread_list (currthread))
1857 {
1858 struct inferior *inf = NULL;
1859 int pid = ptid_get_pid (currthread);
1860
1861 if (ptid_is_pid (inferior_ptid)
1862 && pid == ptid_get_pid (inferior_ptid))
1863 {
1864 /* inferior_ptid has no thread member yet. This can happen
1865 with the vAttach -> remote_wait,"TAAthread:" path if the
1866 stub doesn't support qC. This is the first stop reported
1867 after an attach, so this is the main thread. Update the
1868 ptid in the thread list. */
1869 if (in_thread_list (pid_to_ptid (pid)))
1870 thread_change_ptid (inferior_ptid, currthread);
1871 else
1872 {
1873 remote_add_thread (currthread, running, executing);
1874 inferior_ptid = currthread;
1875 }
1876 return;
1877 }
1878
1879 if (ptid_equal (magic_null_ptid, inferior_ptid))
1880 {
1881 /* inferior_ptid is not set yet. This can happen with the
1882 vRun -> remote_wait,"TAAthread:" path if the stub
1883 doesn't support qC. This is the first stop reported
1884 after an attach, so this is the main thread. Update the
1885 ptid in the thread list. */
1886 thread_change_ptid (inferior_ptid, currthread);
1887 return;
1888 }
1889
1890 /* When connecting to a target remote, or to a target
1891 extended-remote which already was debugging an inferior, we
1892 may not know about it yet. Add it before adding its child
1893 thread, so notifications are emitted in a sensible order. */
1894 if (!in_inferior_list (ptid_get_pid (currthread)))
1895 {
1896 struct remote_state *rs = get_remote_state ();
1897 int fake_pid_p = !remote_multi_process_p (rs);
1898
1899 inf = remote_add_inferior (fake_pid_p,
1900 ptid_get_pid (currthread), -1, 1);
1901 }
1902
1903 /* This is really a new thread. Add it. */
1904 remote_add_thread (currthread, running, executing);
1905
1906 /* If we found a new inferior, let the common code do whatever
1907 it needs to with it (e.g., read shared libraries, insert
1908 breakpoints), unless we're just setting up an all-stop
1909 connection. */
1910 if (inf != NULL)
1911 {
1912 struct remote_state *rs = get_remote_state ();
1913
1914 if (!rs->starting_up)
1915 notice_new_inferior (currthread, executing, 0);
1916 }
1917 }
1918 }
1919
1920 /* Return the private thread data, creating it if necessary. */
1921
1922 static struct private_thread_info *
1923 demand_private_info (ptid_t ptid)
1924 {
1925 struct thread_info *info = find_thread_ptid (ptid);
1926
1927 gdb_assert (info);
1928
1929 if (!info->priv)
1930 {
1931 info->priv = XNEW (struct private_thread_info);
1932 info->private_dtor = free_private_thread_info;
1933 info->priv->core = -1;
1934 info->priv->extra = NULL;
1935 info->priv->name = NULL;
1936 }
1937
1938 return info->priv;
1939 }
1940
1941 /* Call this function as a result of
1942 1) A halt indication (T packet) containing a thread id
1943 2) A direct query of currthread
1944 3) Successful execution of set thread */
1945
1946 static void
1947 record_currthread (struct remote_state *rs, ptid_t currthread)
1948 {
1949 rs->general_thread = currthread;
1950 }
1951
1952 /* If 'QPassSignals' is supported, tell the remote stub what signals
1953 it can simply pass through to the inferior without reporting. */
1954
1955 static void
1956 remote_pass_signals (struct target_ops *self,
1957 int numsigs, unsigned char *pass_signals)
1958 {
1959 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1960 {
1961 char *pass_packet, *p;
1962 int count = 0, i;
1963 struct remote_state *rs = get_remote_state ();
1964
1965 gdb_assert (numsigs < 256);
1966 for (i = 0; i < numsigs; i++)
1967 {
1968 if (pass_signals[i])
1969 count++;
1970 }
1971 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1972 strcpy (pass_packet, "QPassSignals:");
1973 p = pass_packet + strlen (pass_packet);
1974 for (i = 0; i < numsigs; i++)
1975 {
1976 if (pass_signals[i])
1977 {
1978 if (i >= 16)
1979 *p++ = tohex (i >> 4);
1980 *p++ = tohex (i & 15);
1981 if (count)
1982 *p++ = ';';
1983 else
1984 break;
1985 count--;
1986 }
1987 }
1988 *p = 0;
1989 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1990 {
1991 putpkt (pass_packet);
1992 getpkt (&rs->buf, &rs->buf_size, 0);
1993 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1994 if (rs->last_pass_packet)
1995 xfree (rs->last_pass_packet);
1996 rs->last_pass_packet = pass_packet;
1997 }
1998 else
1999 xfree (pass_packet);
2000 }
2001 }
2002
2003 /* If 'QCatchSyscalls' is supported, tell the remote stub
2004 to report syscalls to GDB. */
2005
2006 static int
2007 remote_set_syscall_catchpoint (struct target_ops *self,
2008 int pid, int needed, int any_count,
2009 int table_size, int *table)
2010 {
2011 char *catch_packet;
2012 enum packet_result result;
2013 int n_sysno = 0;
2014
2015 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2016 {
2017 /* Not supported. */
2018 return 1;
2019 }
2020
2021 if (needed && !any_count)
2022 {
2023 int i;
2024
2025 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2026 for (i = 0; i < table_size; i++)
2027 {
2028 if (table[i] != 0)
2029 n_sysno++;
2030 }
2031 }
2032
2033 if (remote_debug)
2034 {
2035 fprintf_unfiltered (gdb_stdlog,
2036 "remote_set_syscall_catchpoint "
2037 "pid %d needed %d any_count %d n_sysno %d\n",
2038 pid, needed, any_count, n_sysno);
2039 }
2040
2041 if (needed)
2042 {
2043 /* Prepare a packet with the sysno list, assuming max 8+1
2044 characters for a sysno. If the resulting packet size is too
2045 big, fallback on the non-selective packet. */
2046 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2047
2048 catch_packet = (char *) xmalloc (maxpktsz);
2049 strcpy (catch_packet, "QCatchSyscalls:1");
2050 if (!any_count)
2051 {
2052 int i;
2053 char *p;
2054
2055 p = catch_packet;
2056 p += strlen (p);
2057
2058 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2059 for (i = 0; i < table_size; i++)
2060 {
2061 if (table[i] != 0)
2062 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2063 }
2064 }
2065 if (strlen (catch_packet) > get_remote_packet_size ())
2066 {
2067 /* catch_packet too big. Fallback to less efficient
2068 non selective mode, with GDB doing the filtering. */
2069 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2070 }
2071 }
2072 else
2073 catch_packet = xstrdup ("QCatchSyscalls:0");
2074
2075 {
2076 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2077 struct remote_state *rs = get_remote_state ();
2078
2079 putpkt (catch_packet);
2080 getpkt (&rs->buf, &rs->buf_size, 0);
2081 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2082 do_cleanups (old_chain);
2083 if (result == PACKET_OK)
2084 return 0;
2085 else
2086 return -1;
2087 }
2088 }
2089
2090 /* If 'QProgramSignals' is supported, tell the remote stub what
2091 signals it should pass through to the inferior when detaching. */
2092
2093 static void
2094 remote_program_signals (struct target_ops *self,
2095 int numsigs, unsigned char *signals)
2096 {
2097 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2098 {
2099 char *packet, *p;
2100 int count = 0, i;
2101 struct remote_state *rs = get_remote_state ();
2102
2103 gdb_assert (numsigs < 256);
2104 for (i = 0; i < numsigs; i++)
2105 {
2106 if (signals[i])
2107 count++;
2108 }
2109 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2110 strcpy (packet, "QProgramSignals:");
2111 p = packet + strlen (packet);
2112 for (i = 0; i < numsigs; i++)
2113 {
2114 if (signal_pass_state (i))
2115 {
2116 if (i >= 16)
2117 *p++ = tohex (i >> 4);
2118 *p++ = tohex (i & 15);
2119 if (count)
2120 *p++ = ';';
2121 else
2122 break;
2123 count--;
2124 }
2125 }
2126 *p = 0;
2127 if (!rs->last_program_signals_packet
2128 || strcmp (rs->last_program_signals_packet, packet) != 0)
2129 {
2130 putpkt (packet);
2131 getpkt (&rs->buf, &rs->buf_size, 0);
2132 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2133 xfree (rs->last_program_signals_packet);
2134 rs->last_program_signals_packet = packet;
2135 }
2136 else
2137 xfree (packet);
2138 }
2139 }
2140
2141 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2142 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2143 thread. If GEN is set, set the general thread, if not, then set
2144 the step/continue thread. */
2145 static void
2146 set_thread (struct ptid ptid, int gen)
2147 {
2148 struct remote_state *rs = get_remote_state ();
2149 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2150 char *buf = rs->buf;
2151 char *endbuf = rs->buf + get_remote_packet_size ();
2152
2153 if (ptid_equal (state, ptid))
2154 return;
2155
2156 *buf++ = 'H';
2157 *buf++ = gen ? 'g' : 'c';
2158 if (ptid_equal (ptid, magic_null_ptid))
2159 xsnprintf (buf, endbuf - buf, "0");
2160 else if (ptid_equal (ptid, any_thread_ptid))
2161 xsnprintf (buf, endbuf - buf, "0");
2162 else if (ptid_equal (ptid, minus_one_ptid))
2163 xsnprintf (buf, endbuf - buf, "-1");
2164 else
2165 write_ptid (buf, endbuf, ptid);
2166 putpkt (rs->buf);
2167 getpkt (&rs->buf, &rs->buf_size, 0);
2168 if (gen)
2169 rs->general_thread = ptid;
2170 else
2171 rs->continue_thread = ptid;
2172 }
2173
2174 static void
2175 set_general_thread (struct ptid ptid)
2176 {
2177 set_thread (ptid, 1);
2178 }
2179
2180 static void
2181 set_continue_thread (struct ptid ptid)
2182 {
2183 set_thread (ptid, 0);
2184 }
2185
2186 /* Change the remote current process. Which thread within the process
2187 ends up selected isn't important, as long as it is the same process
2188 as what INFERIOR_PTID points to.
2189
2190 This comes from that fact that there is no explicit notion of
2191 "selected process" in the protocol. The selected process for
2192 general operations is the process the selected general thread
2193 belongs to. */
2194
2195 static void
2196 set_general_process (void)
2197 {
2198 struct remote_state *rs = get_remote_state ();
2199
2200 /* If the remote can't handle multiple processes, don't bother. */
2201 if (!remote_multi_process_p (rs))
2202 return;
2203
2204 /* We only need to change the remote current thread if it's pointing
2205 at some other process. */
2206 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2207 set_general_thread (inferior_ptid);
2208 }
2209
2210 \f
2211 /* Return nonzero if this is the main thread that we made up ourselves
2212 to model non-threaded targets as single-threaded. */
2213
2214 static int
2215 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2216 {
2217 if (ptid_equal (ptid, magic_null_ptid))
2218 /* The main thread is always alive. */
2219 return 1;
2220
2221 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2222 /* The main thread is always alive. This can happen after a
2223 vAttach, if the remote side doesn't support
2224 multi-threading. */
2225 return 1;
2226
2227 return 0;
2228 }
2229
2230 /* Return nonzero if the thread PTID is still alive on the remote
2231 system. */
2232
2233 static int
2234 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2235 {
2236 struct remote_state *rs = get_remote_state ();
2237 char *p, *endp;
2238
2239 /* Check if this is a thread that we made up ourselves to model
2240 non-threaded targets as single-threaded. */
2241 if (remote_thread_always_alive (ops, ptid))
2242 return 1;
2243
2244 p = rs->buf;
2245 endp = rs->buf + get_remote_packet_size ();
2246
2247 *p++ = 'T';
2248 write_ptid (p, endp, ptid);
2249
2250 putpkt (rs->buf);
2251 getpkt (&rs->buf, &rs->buf_size, 0);
2252 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2253 }
2254
2255 /* Return a pointer to a thread name if we know it and NULL otherwise.
2256 The thread_info object owns the memory for the name. */
2257
2258 static const char *
2259 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2260 {
2261 if (info->priv != NULL)
2262 return info->priv->name;
2263
2264 return NULL;
2265 }
2266
2267 /* About these extended threadlist and threadinfo packets. They are
2268 variable length packets but, the fields within them are often fixed
2269 length. They are redundent enough to send over UDP as is the
2270 remote protocol in general. There is a matching unit test module
2271 in libstub. */
2272
2273 /* WARNING: This threadref data structure comes from the remote O.S.,
2274 libstub protocol encoding, and remote.c. It is not particularly
2275 changable. */
2276
2277 /* Right now, the internal structure is int. We want it to be bigger.
2278 Plan to fix this. */
2279
2280 typedef int gdb_threadref; /* Internal GDB thread reference. */
2281
2282 /* gdb_ext_thread_info is an internal GDB data structure which is
2283 equivalent to the reply of the remote threadinfo packet. */
2284
2285 struct gdb_ext_thread_info
2286 {
2287 threadref threadid; /* External form of thread reference. */
2288 int active; /* Has state interesting to GDB?
2289 regs, stack. */
2290 char display[256]; /* Brief state display, name,
2291 blocked/suspended. */
2292 char shortname[32]; /* To be used to name threads. */
2293 char more_display[256]; /* Long info, statistics, queue depth,
2294 whatever. */
2295 };
2296
2297 /* The volume of remote transfers can be limited by submitting
2298 a mask containing bits specifying the desired information.
2299 Use a union of these values as the 'selection' parameter to
2300 get_thread_info. FIXME: Make these TAG names more thread specific. */
2301
2302 #define TAG_THREADID 1
2303 #define TAG_EXISTS 2
2304 #define TAG_DISPLAY 4
2305 #define TAG_THREADNAME 8
2306 #define TAG_MOREDISPLAY 16
2307
2308 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2309
2310 static char *unpack_nibble (char *buf, int *val);
2311
2312 static char *unpack_byte (char *buf, int *value);
2313
2314 static char *pack_int (char *buf, int value);
2315
2316 static char *unpack_int (char *buf, int *value);
2317
2318 static char *unpack_string (char *src, char *dest, int length);
2319
2320 static char *pack_threadid (char *pkt, threadref *id);
2321
2322 static char *unpack_threadid (char *inbuf, threadref *id);
2323
2324 void int_to_threadref (threadref *id, int value);
2325
2326 static int threadref_to_int (threadref *ref);
2327
2328 static void copy_threadref (threadref *dest, threadref *src);
2329
2330 static int threadmatch (threadref *dest, threadref *src);
2331
2332 static char *pack_threadinfo_request (char *pkt, int mode,
2333 threadref *id);
2334
2335 static int remote_unpack_thread_info_response (char *pkt,
2336 threadref *expectedref,
2337 struct gdb_ext_thread_info
2338 *info);
2339
2340
2341 static int remote_get_threadinfo (threadref *threadid,
2342 int fieldset, /*TAG mask */
2343 struct gdb_ext_thread_info *info);
2344
2345 static char *pack_threadlist_request (char *pkt, int startflag,
2346 int threadcount,
2347 threadref *nextthread);
2348
2349 static int parse_threadlist_response (char *pkt,
2350 int result_limit,
2351 threadref *original_echo,
2352 threadref *resultlist,
2353 int *doneflag);
2354
2355 static int remote_get_threadlist (int startflag,
2356 threadref *nextthread,
2357 int result_limit,
2358 int *done,
2359 int *result_count,
2360 threadref *threadlist);
2361
2362 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2363
2364 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2365 void *context, int looplimit);
2366
2367 static int remote_newthread_step (threadref *ref, void *context);
2368
2369
2370 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2371 buffer we're allowed to write to. Returns
2372 BUF+CHARACTERS_WRITTEN. */
2373
2374 static char *
2375 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2376 {
2377 int pid, tid;
2378 struct remote_state *rs = get_remote_state ();
2379
2380 if (remote_multi_process_p (rs))
2381 {
2382 pid = ptid_get_pid (ptid);
2383 if (pid < 0)
2384 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2385 else
2386 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2387 }
2388 tid = ptid_get_lwp (ptid);
2389 if (tid < 0)
2390 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2391 else
2392 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2393
2394 return buf;
2395 }
2396
2397 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2398 passed the last parsed char. Returns null_ptid on error. */
2399
2400 static ptid_t
2401 read_ptid (char *buf, char **obuf)
2402 {
2403 char *p = buf;
2404 char *pp;
2405 ULONGEST pid = 0, tid = 0;
2406
2407 if (*p == 'p')
2408 {
2409 /* Multi-process ptid. */
2410 pp = unpack_varlen_hex (p + 1, &pid);
2411 if (*pp != '.')
2412 error (_("invalid remote ptid: %s"), p);
2413
2414 p = pp;
2415 pp = unpack_varlen_hex (p + 1, &tid);
2416 if (obuf)
2417 *obuf = pp;
2418 return ptid_build (pid, tid, 0);
2419 }
2420
2421 /* No multi-process. Just a tid. */
2422 pp = unpack_varlen_hex (p, &tid);
2423
2424 /* Return null_ptid when no thread id is found. */
2425 if (p == pp)
2426 {
2427 if (obuf)
2428 *obuf = pp;
2429 return null_ptid;
2430 }
2431
2432 /* Since the stub is not sending a process id, then default to
2433 what's in inferior_ptid, unless it's null at this point. If so,
2434 then since there's no way to know the pid of the reported
2435 threads, use the magic number. */
2436 if (ptid_equal (inferior_ptid, null_ptid))
2437 pid = ptid_get_pid (magic_null_ptid);
2438 else
2439 pid = ptid_get_pid (inferior_ptid);
2440
2441 if (obuf)
2442 *obuf = pp;
2443 return ptid_build (pid, tid, 0);
2444 }
2445
2446 static int
2447 stubhex (int ch)
2448 {
2449 if (ch >= 'a' && ch <= 'f')
2450 return ch - 'a' + 10;
2451 if (ch >= '0' && ch <= '9')
2452 return ch - '0';
2453 if (ch >= 'A' && ch <= 'F')
2454 return ch - 'A' + 10;
2455 return -1;
2456 }
2457
2458 static int
2459 stub_unpack_int (char *buff, int fieldlength)
2460 {
2461 int nibble;
2462 int retval = 0;
2463
2464 while (fieldlength)
2465 {
2466 nibble = stubhex (*buff++);
2467 retval |= nibble;
2468 fieldlength--;
2469 if (fieldlength)
2470 retval = retval << 4;
2471 }
2472 return retval;
2473 }
2474
2475 static char *
2476 unpack_nibble (char *buf, int *val)
2477 {
2478 *val = fromhex (*buf++);
2479 return buf;
2480 }
2481
2482 static char *
2483 unpack_byte (char *buf, int *value)
2484 {
2485 *value = stub_unpack_int (buf, 2);
2486 return buf + 2;
2487 }
2488
2489 static char *
2490 pack_int (char *buf, int value)
2491 {
2492 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2493 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2494 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2495 buf = pack_hex_byte (buf, (value & 0xff));
2496 return buf;
2497 }
2498
2499 static char *
2500 unpack_int (char *buf, int *value)
2501 {
2502 *value = stub_unpack_int (buf, 8);
2503 return buf + 8;
2504 }
2505
2506 #if 0 /* Currently unused, uncomment when needed. */
2507 static char *pack_string (char *pkt, char *string);
2508
2509 static char *
2510 pack_string (char *pkt, char *string)
2511 {
2512 char ch;
2513 int len;
2514
2515 len = strlen (string);
2516 if (len > 200)
2517 len = 200; /* Bigger than most GDB packets, junk??? */
2518 pkt = pack_hex_byte (pkt, len);
2519 while (len-- > 0)
2520 {
2521 ch = *string++;
2522 if ((ch == '\0') || (ch == '#'))
2523 ch = '*'; /* Protect encapsulation. */
2524 *pkt++ = ch;
2525 }
2526 return pkt;
2527 }
2528 #endif /* 0 (unused) */
2529
2530 static char *
2531 unpack_string (char *src, char *dest, int length)
2532 {
2533 while (length--)
2534 *dest++ = *src++;
2535 *dest = '\0';
2536 return src;
2537 }
2538
2539 static char *
2540 pack_threadid (char *pkt, threadref *id)
2541 {
2542 char *limit;
2543 unsigned char *altid;
2544
2545 altid = (unsigned char *) id;
2546 limit = pkt + BUF_THREAD_ID_SIZE;
2547 while (pkt < limit)
2548 pkt = pack_hex_byte (pkt, *altid++);
2549 return pkt;
2550 }
2551
2552
2553 static char *
2554 unpack_threadid (char *inbuf, threadref *id)
2555 {
2556 char *altref;
2557 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2558 int x, y;
2559
2560 altref = (char *) id;
2561
2562 while (inbuf < limit)
2563 {
2564 x = stubhex (*inbuf++);
2565 y = stubhex (*inbuf++);
2566 *altref++ = (x << 4) | y;
2567 }
2568 return inbuf;
2569 }
2570
2571 /* Externally, threadrefs are 64 bits but internally, they are still
2572 ints. This is due to a mismatch of specifications. We would like
2573 to use 64bit thread references internally. This is an adapter
2574 function. */
2575
2576 void
2577 int_to_threadref (threadref *id, int value)
2578 {
2579 unsigned char *scan;
2580
2581 scan = (unsigned char *) id;
2582 {
2583 int i = 4;
2584 while (i--)
2585 *scan++ = 0;
2586 }
2587 *scan++ = (value >> 24) & 0xff;
2588 *scan++ = (value >> 16) & 0xff;
2589 *scan++ = (value >> 8) & 0xff;
2590 *scan++ = (value & 0xff);
2591 }
2592
2593 static int
2594 threadref_to_int (threadref *ref)
2595 {
2596 int i, value = 0;
2597 unsigned char *scan;
2598
2599 scan = *ref;
2600 scan += 4;
2601 i = 4;
2602 while (i-- > 0)
2603 value = (value << 8) | ((*scan++) & 0xff);
2604 return value;
2605 }
2606
2607 static void
2608 copy_threadref (threadref *dest, threadref *src)
2609 {
2610 int i;
2611 unsigned char *csrc, *cdest;
2612
2613 csrc = (unsigned char *) src;
2614 cdest = (unsigned char *) dest;
2615 i = 8;
2616 while (i--)
2617 *cdest++ = *csrc++;
2618 }
2619
2620 static int
2621 threadmatch (threadref *dest, threadref *src)
2622 {
2623 /* Things are broken right now, so just assume we got a match. */
2624 #if 0
2625 unsigned char *srcp, *destp;
2626 int i, result;
2627 srcp = (char *) src;
2628 destp = (char *) dest;
2629
2630 result = 1;
2631 while (i-- > 0)
2632 result &= (*srcp++ == *destp++) ? 1 : 0;
2633 return result;
2634 #endif
2635 return 1;
2636 }
2637
2638 /*
2639 threadid:1, # always request threadid
2640 context_exists:2,
2641 display:4,
2642 unique_name:8,
2643 more_display:16
2644 */
2645
2646 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2647
2648 static char *
2649 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2650 {
2651 *pkt++ = 'q'; /* Info Query */
2652 *pkt++ = 'P'; /* process or thread info */
2653 pkt = pack_int (pkt, mode); /* mode */
2654 pkt = pack_threadid (pkt, id); /* threadid */
2655 *pkt = '\0'; /* terminate */
2656 return pkt;
2657 }
2658
2659 /* These values tag the fields in a thread info response packet. */
2660 /* Tagging the fields allows us to request specific fields and to
2661 add more fields as time goes by. */
2662
2663 #define TAG_THREADID 1 /* Echo the thread identifier. */
2664 #define TAG_EXISTS 2 /* Is this process defined enough to
2665 fetch registers and its stack? */
2666 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2667 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2668 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2669 the process. */
2670
2671 static int
2672 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2673 struct gdb_ext_thread_info *info)
2674 {
2675 struct remote_state *rs = get_remote_state ();
2676 int mask, length;
2677 int tag;
2678 threadref ref;
2679 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2680 int retval = 1;
2681
2682 /* info->threadid = 0; FIXME: implement zero_threadref. */
2683 info->active = 0;
2684 info->display[0] = '\0';
2685 info->shortname[0] = '\0';
2686 info->more_display[0] = '\0';
2687
2688 /* Assume the characters indicating the packet type have been
2689 stripped. */
2690 pkt = unpack_int (pkt, &mask); /* arg mask */
2691 pkt = unpack_threadid (pkt, &ref);
2692
2693 if (mask == 0)
2694 warning (_("Incomplete response to threadinfo request."));
2695 if (!threadmatch (&ref, expectedref))
2696 { /* This is an answer to a different request. */
2697 warning (_("ERROR RMT Thread info mismatch."));
2698 return 0;
2699 }
2700 copy_threadref (&info->threadid, &ref);
2701
2702 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2703
2704 /* Packets are terminated with nulls. */
2705 while ((pkt < limit) && mask && *pkt)
2706 {
2707 pkt = unpack_int (pkt, &tag); /* tag */
2708 pkt = unpack_byte (pkt, &length); /* length */
2709 if (!(tag & mask)) /* Tags out of synch with mask. */
2710 {
2711 warning (_("ERROR RMT: threadinfo tag mismatch."));
2712 retval = 0;
2713 break;
2714 }
2715 if (tag == TAG_THREADID)
2716 {
2717 if (length != 16)
2718 {
2719 warning (_("ERROR RMT: length of threadid is not 16."));
2720 retval = 0;
2721 break;
2722 }
2723 pkt = unpack_threadid (pkt, &ref);
2724 mask = mask & ~TAG_THREADID;
2725 continue;
2726 }
2727 if (tag == TAG_EXISTS)
2728 {
2729 info->active = stub_unpack_int (pkt, length);
2730 pkt += length;
2731 mask = mask & ~(TAG_EXISTS);
2732 if (length > 8)
2733 {
2734 warning (_("ERROR RMT: 'exists' length too long."));
2735 retval = 0;
2736 break;
2737 }
2738 continue;
2739 }
2740 if (tag == TAG_THREADNAME)
2741 {
2742 pkt = unpack_string (pkt, &info->shortname[0], length);
2743 mask = mask & ~TAG_THREADNAME;
2744 continue;
2745 }
2746 if (tag == TAG_DISPLAY)
2747 {
2748 pkt = unpack_string (pkt, &info->display[0], length);
2749 mask = mask & ~TAG_DISPLAY;
2750 continue;
2751 }
2752 if (tag == TAG_MOREDISPLAY)
2753 {
2754 pkt = unpack_string (pkt, &info->more_display[0], length);
2755 mask = mask & ~TAG_MOREDISPLAY;
2756 continue;
2757 }
2758 warning (_("ERROR RMT: unknown thread info tag."));
2759 break; /* Not a tag we know about. */
2760 }
2761 return retval;
2762 }
2763
2764 static int
2765 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2766 struct gdb_ext_thread_info *info)
2767 {
2768 struct remote_state *rs = get_remote_state ();
2769 int result;
2770
2771 pack_threadinfo_request (rs->buf, fieldset, threadid);
2772 putpkt (rs->buf);
2773 getpkt (&rs->buf, &rs->buf_size, 0);
2774
2775 if (rs->buf[0] == '\0')
2776 return 0;
2777
2778 result = remote_unpack_thread_info_response (rs->buf + 2,
2779 threadid, info);
2780 return result;
2781 }
2782
2783 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2784
2785 static char *
2786 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2787 threadref *nextthread)
2788 {
2789 *pkt++ = 'q'; /* info query packet */
2790 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2791 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2792 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2793 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2794 *pkt = '\0';
2795 return pkt;
2796 }
2797
2798 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2799
2800 static int
2801 parse_threadlist_response (char *pkt, int result_limit,
2802 threadref *original_echo, threadref *resultlist,
2803 int *doneflag)
2804 {
2805 struct remote_state *rs = get_remote_state ();
2806 char *limit;
2807 int count, resultcount, done;
2808
2809 resultcount = 0;
2810 /* Assume the 'q' and 'M chars have been stripped. */
2811 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2812 /* done parse past here */
2813 pkt = unpack_byte (pkt, &count); /* count field */
2814 pkt = unpack_nibble (pkt, &done);
2815 /* The first threadid is the argument threadid. */
2816 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2817 while ((count-- > 0) && (pkt < limit))
2818 {
2819 pkt = unpack_threadid (pkt, resultlist++);
2820 if (resultcount++ >= result_limit)
2821 break;
2822 }
2823 if (doneflag)
2824 *doneflag = done;
2825 return resultcount;
2826 }
2827
2828 /* Fetch the next batch of threads from the remote. Returns -1 if the
2829 qL packet is not supported, 0 on error and 1 on success. */
2830
2831 static int
2832 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2833 int *done, int *result_count, threadref *threadlist)
2834 {
2835 struct remote_state *rs = get_remote_state ();
2836 int result = 1;
2837
2838 /* Trancate result limit to be smaller than the packet size. */
2839 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2840 >= get_remote_packet_size ())
2841 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2842
2843 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2844 putpkt (rs->buf);
2845 getpkt (&rs->buf, &rs->buf_size, 0);
2846 if (*rs->buf == '\0')
2847 {
2848 /* Packet not supported. */
2849 return -1;
2850 }
2851
2852 *result_count =
2853 parse_threadlist_response (rs->buf + 2, result_limit,
2854 &rs->echo_nextthread, threadlist, done);
2855
2856 if (!threadmatch (&rs->echo_nextthread, nextthread))
2857 {
2858 /* FIXME: This is a good reason to drop the packet. */
2859 /* Possably, there is a duplicate response. */
2860 /* Possabilities :
2861 retransmit immediatly - race conditions
2862 retransmit after timeout - yes
2863 exit
2864 wait for packet, then exit
2865 */
2866 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2867 return 0; /* I choose simply exiting. */
2868 }
2869 if (*result_count <= 0)
2870 {
2871 if (*done != 1)
2872 {
2873 warning (_("RMT ERROR : failed to get remote thread list."));
2874 result = 0;
2875 }
2876 return result; /* break; */
2877 }
2878 if (*result_count > result_limit)
2879 {
2880 *result_count = 0;
2881 warning (_("RMT ERROR: threadlist response longer than requested."));
2882 return 0;
2883 }
2884 return result;
2885 }
2886
2887 /* Fetch the list of remote threads, with the qL packet, and call
2888 STEPFUNCTION for each thread found. Stops iterating and returns 1
2889 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2890 STEPFUNCTION returns false. If the packet is not supported,
2891 returns -1. */
2892
2893 static int
2894 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2895 int looplimit)
2896 {
2897 struct remote_state *rs = get_remote_state ();
2898 int done, i, result_count;
2899 int startflag = 1;
2900 int result = 1;
2901 int loopcount = 0;
2902
2903 done = 0;
2904 while (!done)
2905 {
2906 if (loopcount++ > looplimit)
2907 {
2908 result = 0;
2909 warning (_("Remote fetch threadlist -infinite loop-."));
2910 break;
2911 }
2912 result = remote_get_threadlist (startflag, &rs->nextthread,
2913 MAXTHREADLISTRESULTS,
2914 &done, &result_count,
2915 rs->resultthreadlist);
2916 if (result <= 0)
2917 break;
2918 /* Clear for later iterations. */
2919 startflag = 0;
2920 /* Setup to resume next batch of thread references, set nextthread. */
2921 if (result_count >= 1)
2922 copy_threadref (&rs->nextthread,
2923 &rs->resultthreadlist[result_count - 1]);
2924 i = 0;
2925 while (result_count--)
2926 {
2927 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2928 {
2929 result = 0;
2930 break;
2931 }
2932 }
2933 }
2934 return result;
2935 }
2936
2937 /* A thread found on the remote target. */
2938
2939 typedef struct thread_item
2940 {
2941 /* The thread's PTID. */
2942 ptid_t ptid;
2943
2944 /* The thread's extra info. May be NULL. */
2945 char *extra;
2946
2947 /* The thread's name. May be NULL. */
2948 char *name;
2949
2950 /* The core the thread was running on. -1 if not known. */
2951 int core;
2952 } thread_item_t;
2953 DEF_VEC_O(thread_item_t);
2954
2955 /* Context passed around to the various methods listing remote
2956 threads. As new threads are found, they're added to the ITEMS
2957 vector. */
2958
2959 struct threads_listing_context
2960 {
2961 /* The threads found on the remote target. */
2962 VEC (thread_item_t) *items;
2963 };
2964
2965 /* Discard the contents of the constructed thread listing context. */
2966
2967 static void
2968 clear_threads_listing_context (void *p)
2969 {
2970 struct threads_listing_context *context
2971 = (struct threads_listing_context *) p;
2972 int i;
2973 struct thread_item *item;
2974
2975 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2976 {
2977 xfree (item->extra);
2978 xfree (item->name);
2979 }
2980
2981 VEC_free (thread_item_t, context->items);
2982 }
2983
2984 /* Remove the thread specified as the related_pid field of WS
2985 from the CONTEXT list. */
2986
2987 static void
2988 threads_listing_context_remove (struct target_waitstatus *ws,
2989 struct threads_listing_context *context)
2990 {
2991 struct thread_item *item;
2992 int i;
2993 ptid_t child_ptid = ws->value.related_pid;
2994
2995 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2996 {
2997 if (ptid_equal (item->ptid, child_ptid))
2998 {
2999 VEC_ordered_remove (thread_item_t, context->items, i);
3000 break;
3001 }
3002 }
3003 }
3004
3005 static int
3006 remote_newthread_step (threadref *ref, void *data)
3007 {
3008 struct threads_listing_context *context
3009 = (struct threads_listing_context *) data;
3010 struct thread_item item;
3011 int pid = ptid_get_pid (inferior_ptid);
3012
3013 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3014 item.core = -1;
3015 item.name = NULL;
3016 item.extra = NULL;
3017
3018 VEC_safe_push (thread_item_t, context->items, &item);
3019
3020 return 1; /* continue iterator */
3021 }
3022
3023 #define CRAZY_MAX_THREADS 1000
3024
3025 static ptid_t
3026 remote_current_thread (ptid_t oldpid)
3027 {
3028 struct remote_state *rs = get_remote_state ();
3029
3030 putpkt ("qC");
3031 getpkt (&rs->buf, &rs->buf_size, 0);
3032 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3033 {
3034 char *obuf;
3035 ptid_t result;
3036
3037 result = read_ptid (&rs->buf[2], &obuf);
3038 if (*obuf != '\0' && remote_debug)
3039 fprintf_unfiltered (gdb_stdlog,
3040 "warning: garbage in qC reply\n");
3041
3042 return result;
3043 }
3044 else
3045 return oldpid;
3046 }
3047
3048 /* List remote threads using the deprecated qL packet. */
3049
3050 static int
3051 remote_get_threads_with_ql (struct target_ops *ops,
3052 struct threads_listing_context *context)
3053 {
3054 if (remote_threadlist_iterator (remote_newthread_step, context,
3055 CRAZY_MAX_THREADS) >= 0)
3056 return 1;
3057
3058 return 0;
3059 }
3060
3061 #if defined(HAVE_LIBEXPAT)
3062
3063 static void
3064 start_thread (struct gdb_xml_parser *parser,
3065 const struct gdb_xml_element *element,
3066 void *user_data, VEC(gdb_xml_value_s) *attributes)
3067 {
3068 struct threads_listing_context *data
3069 = (struct threads_listing_context *) user_data;
3070
3071 struct thread_item item;
3072 char *id;
3073 struct gdb_xml_value *attr;
3074
3075 id = (char *) xml_find_attribute (attributes, "id")->value;
3076 item.ptid = read_ptid (id, NULL);
3077
3078 attr = xml_find_attribute (attributes, "core");
3079 if (attr != NULL)
3080 item.core = *(ULONGEST *) attr->value;
3081 else
3082 item.core = -1;
3083
3084 attr = xml_find_attribute (attributes, "name");
3085 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3086
3087 item.extra = 0;
3088
3089 VEC_safe_push (thread_item_t, data->items, &item);
3090 }
3091
3092 static void
3093 end_thread (struct gdb_xml_parser *parser,
3094 const struct gdb_xml_element *element,
3095 void *user_data, const char *body_text)
3096 {
3097 struct threads_listing_context *data
3098 = (struct threads_listing_context *) user_data;
3099
3100 if (body_text && *body_text)
3101 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3102 }
3103
3104 const struct gdb_xml_attribute thread_attributes[] = {
3105 { "id", GDB_XML_AF_NONE, NULL, NULL },
3106 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3107 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3108 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3109 };
3110
3111 const struct gdb_xml_element thread_children[] = {
3112 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3113 };
3114
3115 const struct gdb_xml_element threads_children[] = {
3116 { "thread", thread_attributes, thread_children,
3117 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3118 start_thread, end_thread },
3119 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3120 };
3121
3122 const struct gdb_xml_element threads_elements[] = {
3123 { "threads", NULL, threads_children,
3124 GDB_XML_EF_NONE, NULL, NULL },
3125 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3126 };
3127
3128 #endif
3129
3130 /* List remote threads using qXfer:threads:read. */
3131
3132 static int
3133 remote_get_threads_with_qxfer (struct target_ops *ops,
3134 struct threads_listing_context *context)
3135 {
3136 #if defined(HAVE_LIBEXPAT)
3137 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3138 {
3139 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3140 struct cleanup *back_to = make_cleanup (xfree, xml);
3141
3142 if (xml != NULL && *xml != '\0')
3143 {
3144 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3145 threads_elements, xml, context);
3146 }
3147
3148 do_cleanups (back_to);
3149 return 1;
3150 }
3151 #endif
3152
3153 return 0;
3154 }
3155
3156 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3157
3158 static int
3159 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3160 struct threads_listing_context *context)
3161 {
3162 struct remote_state *rs = get_remote_state ();
3163
3164 if (rs->use_threadinfo_query)
3165 {
3166 char *bufp;
3167
3168 putpkt ("qfThreadInfo");
3169 getpkt (&rs->buf, &rs->buf_size, 0);
3170 bufp = rs->buf;
3171 if (bufp[0] != '\0') /* q packet recognized */
3172 {
3173 while (*bufp++ == 'm') /* reply contains one or more TID */
3174 {
3175 do
3176 {
3177 struct thread_item item;
3178
3179 item.ptid = read_ptid (bufp, &bufp);
3180 item.core = -1;
3181 item.name = NULL;
3182 item.extra = NULL;
3183
3184 VEC_safe_push (thread_item_t, context->items, &item);
3185 }
3186 while (*bufp++ == ','); /* comma-separated list */
3187 putpkt ("qsThreadInfo");
3188 getpkt (&rs->buf, &rs->buf_size, 0);
3189 bufp = rs->buf;
3190 }
3191 return 1;
3192 }
3193 else
3194 {
3195 /* Packet not recognized. */
3196 rs->use_threadinfo_query = 0;
3197 }
3198 }
3199
3200 return 0;
3201 }
3202
3203 /* Implement the to_update_thread_list function for the remote
3204 targets. */
3205
3206 static void
3207 remote_update_thread_list (struct target_ops *ops)
3208 {
3209 struct threads_listing_context context;
3210 struct cleanup *old_chain;
3211 int got_list = 0;
3212
3213 context.items = NULL;
3214 old_chain = make_cleanup (clear_threads_listing_context, &context);
3215
3216 /* We have a few different mechanisms to fetch the thread list. Try
3217 them all, starting with the most preferred one first, falling
3218 back to older methods. */
3219 if (remote_get_threads_with_qxfer (ops, &context)
3220 || remote_get_threads_with_qthreadinfo (ops, &context)
3221 || remote_get_threads_with_ql (ops, &context))
3222 {
3223 int i;
3224 struct thread_item *item;
3225 struct thread_info *tp, *tmp;
3226
3227 got_list = 1;
3228
3229 if (VEC_empty (thread_item_t, context.items)
3230 && remote_thread_always_alive (ops, inferior_ptid))
3231 {
3232 /* Some targets don't really support threads, but still
3233 reply an (empty) thread list in response to the thread
3234 listing packets, instead of replying "packet not
3235 supported". Exit early so we don't delete the main
3236 thread. */
3237 do_cleanups (old_chain);
3238 return;
3239 }
3240
3241 /* CONTEXT now holds the current thread list on the remote
3242 target end. Delete GDB-side threads no longer found on the
3243 target. */
3244 ALL_THREADS_SAFE (tp, tmp)
3245 {
3246 for (i = 0;
3247 VEC_iterate (thread_item_t, context.items, i, item);
3248 ++i)
3249 {
3250 if (ptid_equal (item->ptid, tp->ptid))
3251 break;
3252 }
3253
3254 if (i == VEC_length (thread_item_t, context.items))
3255 {
3256 /* Not found. */
3257 delete_thread (tp->ptid);
3258 }
3259 }
3260
3261 /* Remove any unreported fork child threads from CONTEXT so
3262 that we don't interfere with follow fork, which is where
3263 creation of such threads is handled. */
3264 remove_new_fork_children (&context);
3265
3266 /* And now add threads we don't know about yet to our list. */
3267 for (i = 0;
3268 VEC_iterate (thread_item_t, context.items, i, item);
3269 ++i)
3270 {
3271 if (!ptid_equal (item->ptid, null_ptid))
3272 {
3273 struct private_thread_info *info;
3274 /* In non-stop mode, we assume new found threads are
3275 executing until proven otherwise with a stop reply.
3276 In all-stop, we can only get here if all threads are
3277 stopped. */
3278 int executing = target_is_non_stop_p () ? 1 : 0;
3279
3280 remote_notice_new_inferior (item->ptid, executing);
3281
3282 info = demand_private_info (item->ptid);
3283 info->core = item->core;
3284 info->extra = item->extra;
3285 item->extra = NULL;
3286 info->name = item->name;
3287 item->name = NULL;
3288 }
3289 }
3290 }
3291
3292 if (!got_list)
3293 {
3294 /* If no thread listing method is supported, then query whether
3295 each known thread is alive, one by one, with the T packet.
3296 If the target doesn't support threads at all, then this is a
3297 no-op. See remote_thread_alive. */
3298 prune_threads ();
3299 }
3300
3301 do_cleanups (old_chain);
3302 }
3303
3304 /*
3305 * Collect a descriptive string about the given thread.
3306 * The target may say anything it wants to about the thread
3307 * (typically info about its blocked / runnable state, name, etc.).
3308 * This string will appear in the info threads display.
3309 *
3310 * Optional: targets are not required to implement this function.
3311 */
3312
3313 static char *
3314 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3315 {
3316 struct remote_state *rs = get_remote_state ();
3317 int result;
3318 int set;
3319 threadref id;
3320 struct gdb_ext_thread_info threadinfo;
3321 static char display_buf[100]; /* arbitrary... */
3322 int n = 0; /* position in display_buf */
3323
3324 if (rs->remote_desc == 0) /* paranoia */
3325 internal_error (__FILE__, __LINE__,
3326 _("remote_threads_extra_info"));
3327
3328 if (ptid_equal (tp->ptid, magic_null_ptid)
3329 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3330 /* This is the main thread which was added by GDB. The remote
3331 server doesn't know about it. */
3332 return NULL;
3333
3334 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3335 {
3336 struct thread_info *info = find_thread_ptid (tp->ptid);
3337
3338 if (info && info->priv)
3339 return info->priv->extra;
3340 else
3341 return NULL;
3342 }
3343
3344 if (rs->use_threadextra_query)
3345 {
3346 char *b = rs->buf;
3347 char *endb = rs->buf + get_remote_packet_size ();
3348
3349 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3350 b += strlen (b);
3351 write_ptid (b, endb, tp->ptid);
3352
3353 putpkt (rs->buf);
3354 getpkt (&rs->buf, &rs->buf_size, 0);
3355 if (rs->buf[0] != 0)
3356 {
3357 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3358 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3359 display_buf [result] = '\0';
3360 return display_buf;
3361 }
3362 }
3363
3364 /* If the above query fails, fall back to the old method. */
3365 rs->use_threadextra_query = 0;
3366 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3367 | TAG_MOREDISPLAY | TAG_DISPLAY;
3368 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3369 if (remote_get_threadinfo (&id, set, &threadinfo))
3370 if (threadinfo.active)
3371 {
3372 if (*threadinfo.shortname)
3373 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3374 " Name: %s,", threadinfo.shortname);
3375 if (*threadinfo.display)
3376 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3377 " State: %s,", threadinfo.display);
3378 if (*threadinfo.more_display)
3379 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3380 " Priority: %s", threadinfo.more_display);
3381
3382 if (n > 0)
3383 {
3384 /* For purely cosmetic reasons, clear up trailing commas. */
3385 if (',' == display_buf[n-1])
3386 display_buf[n-1] = ' ';
3387 return display_buf;
3388 }
3389 }
3390 return NULL;
3391 }
3392 \f
3393
3394 static int
3395 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3396 struct static_tracepoint_marker *marker)
3397 {
3398 struct remote_state *rs = get_remote_state ();
3399 char *p = rs->buf;
3400
3401 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3402 p += strlen (p);
3403 p += hexnumstr (p, addr);
3404 putpkt (rs->buf);
3405 getpkt (&rs->buf, &rs->buf_size, 0);
3406 p = rs->buf;
3407
3408 if (*p == 'E')
3409 error (_("Remote failure reply: %s"), p);
3410
3411 if (*p++ == 'm')
3412 {
3413 parse_static_tracepoint_marker_definition (p, &p, marker);
3414 return 1;
3415 }
3416
3417 return 0;
3418 }
3419
3420 static VEC(static_tracepoint_marker_p) *
3421 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3422 const char *strid)
3423 {
3424 struct remote_state *rs = get_remote_state ();
3425 VEC(static_tracepoint_marker_p) *markers = NULL;
3426 struct static_tracepoint_marker *marker = NULL;
3427 struct cleanup *old_chain;
3428 char *p;
3429
3430 /* Ask for a first packet of static tracepoint marker
3431 definition. */
3432 putpkt ("qTfSTM");
3433 getpkt (&rs->buf, &rs->buf_size, 0);
3434 p = rs->buf;
3435 if (*p == 'E')
3436 error (_("Remote failure reply: %s"), p);
3437
3438 old_chain = make_cleanup (free_current_marker, &marker);
3439
3440 while (*p++ == 'm')
3441 {
3442 if (marker == NULL)
3443 marker = XCNEW (struct static_tracepoint_marker);
3444
3445 do
3446 {
3447 parse_static_tracepoint_marker_definition (p, &p, marker);
3448
3449 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3450 {
3451 VEC_safe_push (static_tracepoint_marker_p,
3452 markers, marker);
3453 marker = NULL;
3454 }
3455 else
3456 {
3457 release_static_tracepoint_marker (marker);
3458 memset (marker, 0, sizeof (*marker));
3459 }
3460 }
3461 while (*p++ == ','); /* comma-separated list */
3462 /* Ask for another packet of static tracepoint definition. */
3463 putpkt ("qTsSTM");
3464 getpkt (&rs->buf, &rs->buf_size, 0);
3465 p = rs->buf;
3466 }
3467
3468 do_cleanups (old_chain);
3469 return markers;
3470 }
3471
3472 \f
3473 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3474
3475 static ptid_t
3476 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3477 {
3478 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3479 }
3480 \f
3481
3482 /* Restart the remote side; this is an extended protocol operation. */
3483
3484 static void
3485 extended_remote_restart (void)
3486 {
3487 struct remote_state *rs = get_remote_state ();
3488
3489 /* Send the restart command; for reasons I don't understand the
3490 remote side really expects a number after the "R". */
3491 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3492 putpkt (rs->buf);
3493
3494 remote_fileio_reset ();
3495 }
3496 \f
3497 /* Clean up connection to a remote debugger. */
3498
3499 static void
3500 remote_close (struct target_ops *self)
3501 {
3502 struct remote_state *rs = get_remote_state ();
3503
3504 if (rs->remote_desc == NULL)
3505 return; /* already closed */
3506
3507 /* Make sure we leave stdin registered in the event loop. */
3508 remote_terminal_ours (self);
3509
3510 serial_close (rs->remote_desc);
3511 rs->remote_desc = NULL;
3512
3513 /* We don't have a connection to the remote stub anymore. Get rid
3514 of all the inferiors and their threads we were controlling.
3515 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3516 will be unable to find the thread corresponding to (pid, 0, 0). */
3517 inferior_ptid = null_ptid;
3518 discard_all_inferiors ();
3519
3520 /* We are closing the remote target, so we should discard
3521 everything of this target. */
3522 discard_pending_stop_replies_in_queue (rs);
3523
3524 if (remote_async_inferior_event_token)
3525 delete_async_event_handler (&remote_async_inferior_event_token);
3526
3527 remote_notif_state_xfree (rs->notif_state);
3528
3529 trace_reset_local_state ();
3530 }
3531
3532 /* Query the remote side for the text, data and bss offsets. */
3533
3534 static void
3535 get_offsets (void)
3536 {
3537 struct remote_state *rs = get_remote_state ();
3538 char *buf;
3539 char *ptr;
3540 int lose, num_segments = 0, do_sections, do_segments;
3541 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3542 struct section_offsets *offs;
3543 struct symfile_segment_data *data;
3544
3545 if (symfile_objfile == NULL)
3546 return;
3547
3548 putpkt ("qOffsets");
3549 getpkt (&rs->buf, &rs->buf_size, 0);
3550 buf = rs->buf;
3551
3552 if (buf[0] == '\000')
3553 return; /* Return silently. Stub doesn't support
3554 this command. */
3555 if (buf[0] == 'E')
3556 {
3557 warning (_("Remote failure reply: %s"), buf);
3558 return;
3559 }
3560
3561 /* Pick up each field in turn. This used to be done with scanf, but
3562 scanf will make trouble if CORE_ADDR size doesn't match
3563 conversion directives correctly. The following code will work
3564 with any size of CORE_ADDR. */
3565 text_addr = data_addr = bss_addr = 0;
3566 ptr = buf;
3567 lose = 0;
3568
3569 if (startswith (ptr, "Text="))
3570 {
3571 ptr += 5;
3572 /* Don't use strtol, could lose on big values. */
3573 while (*ptr && *ptr != ';')
3574 text_addr = (text_addr << 4) + fromhex (*ptr++);
3575
3576 if (startswith (ptr, ";Data="))
3577 {
3578 ptr += 6;
3579 while (*ptr && *ptr != ';')
3580 data_addr = (data_addr << 4) + fromhex (*ptr++);
3581 }
3582 else
3583 lose = 1;
3584
3585 if (!lose && startswith (ptr, ";Bss="))
3586 {
3587 ptr += 5;
3588 while (*ptr && *ptr != ';')
3589 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3590
3591 if (bss_addr != data_addr)
3592 warning (_("Target reported unsupported offsets: %s"), buf);
3593 }
3594 else
3595 lose = 1;
3596 }
3597 else if (startswith (ptr, "TextSeg="))
3598 {
3599 ptr += 8;
3600 /* Don't use strtol, could lose on big values. */
3601 while (*ptr && *ptr != ';')
3602 text_addr = (text_addr << 4) + fromhex (*ptr++);
3603 num_segments = 1;
3604
3605 if (startswith (ptr, ";DataSeg="))
3606 {
3607 ptr += 9;
3608 while (*ptr && *ptr != ';')
3609 data_addr = (data_addr << 4) + fromhex (*ptr++);
3610 num_segments++;
3611 }
3612 }
3613 else
3614 lose = 1;
3615
3616 if (lose)
3617 error (_("Malformed response to offset query, %s"), buf);
3618 else if (*ptr != '\0')
3619 warning (_("Target reported unsupported offsets: %s"), buf);
3620
3621 offs = ((struct section_offsets *)
3622 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3623 memcpy (offs, symfile_objfile->section_offsets,
3624 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3625
3626 data = get_symfile_segment_data (symfile_objfile->obfd);
3627 do_segments = (data != NULL);
3628 do_sections = num_segments == 0;
3629
3630 if (num_segments > 0)
3631 {
3632 segments[0] = text_addr;
3633 segments[1] = data_addr;
3634 }
3635 /* If we have two segments, we can still try to relocate everything
3636 by assuming that the .text and .data offsets apply to the whole
3637 text and data segments. Convert the offsets given in the packet
3638 to base addresses for symfile_map_offsets_to_segments. */
3639 else if (data && data->num_segments == 2)
3640 {
3641 segments[0] = data->segment_bases[0] + text_addr;
3642 segments[1] = data->segment_bases[1] + data_addr;
3643 num_segments = 2;
3644 }
3645 /* If the object file has only one segment, assume that it is text
3646 rather than data; main programs with no writable data are rare,
3647 but programs with no code are useless. Of course the code might
3648 have ended up in the data segment... to detect that we would need
3649 the permissions here. */
3650 else if (data && data->num_segments == 1)
3651 {
3652 segments[0] = data->segment_bases[0] + text_addr;
3653 num_segments = 1;
3654 }
3655 /* There's no way to relocate by segment. */
3656 else
3657 do_segments = 0;
3658
3659 if (do_segments)
3660 {
3661 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3662 offs, num_segments, segments);
3663
3664 if (ret == 0 && !do_sections)
3665 error (_("Can not handle qOffsets TextSeg "
3666 "response with this symbol file"));
3667
3668 if (ret > 0)
3669 do_sections = 0;
3670 }
3671
3672 if (data)
3673 free_symfile_segment_data (data);
3674
3675 if (do_sections)
3676 {
3677 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3678
3679 /* This is a temporary kludge to force data and bss to use the
3680 same offsets because that's what nlmconv does now. The real
3681 solution requires changes to the stub and remote.c that I
3682 don't have time to do right now. */
3683
3684 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3685 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3686 }
3687
3688 objfile_relocate (symfile_objfile, offs);
3689 }
3690
3691 /* Send interrupt_sequence to remote target. */
3692 static void
3693 send_interrupt_sequence (void)
3694 {
3695 struct remote_state *rs = get_remote_state ();
3696
3697 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3698 remote_serial_write ("\x03", 1);
3699 else if (interrupt_sequence_mode == interrupt_sequence_break)
3700 serial_send_break (rs->remote_desc);
3701 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3702 {
3703 serial_send_break (rs->remote_desc);
3704 remote_serial_write ("g", 1);
3705 }
3706 else
3707 internal_error (__FILE__, __LINE__,
3708 _("Invalid value for interrupt_sequence_mode: %s."),
3709 interrupt_sequence_mode);
3710 }
3711
3712
3713 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3714 and extract the PTID. Returns NULL_PTID if not found. */
3715
3716 static ptid_t
3717 stop_reply_extract_thread (char *stop_reply)
3718 {
3719 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3720 {
3721 char *p;
3722
3723 /* Txx r:val ; r:val (...) */
3724 p = &stop_reply[3];
3725
3726 /* Look for "register" named "thread". */
3727 while (*p != '\0')
3728 {
3729 char *p1;
3730
3731 p1 = strchr (p, ':');
3732 if (p1 == NULL)
3733 return null_ptid;
3734
3735 if (strncmp (p, "thread", p1 - p) == 0)
3736 return read_ptid (++p1, &p);
3737
3738 p1 = strchr (p, ';');
3739 if (p1 == NULL)
3740 return null_ptid;
3741 p1++;
3742
3743 p = p1;
3744 }
3745 }
3746
3747 return null_ptid;
3748 }
3749
3750 /* Determine the remote side's current thread. If we have a stop
3751 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3752 "thread" register we can extract the current thread from. If not,
3753 ask the remote which is the current thread with qC. The former
3754 method avoids a roundtrip. */
3755
3756 static ptid_t
3757 get_current_thread (char *wait_status)
3758 {
3759 ptid_t ptid = null_ptid;
3760
3761 /* Note we don't use remote_parse_stop_reply as that makes use of
3762 the target architecture, which we haven't yet fully determined at
3763 this point. */
3764 if (wait_status != NULL)
3765 ptid = stop_reply_extract_thread (wait_status);
3766 if (ptid_equal (ptid, null_ptid))
3767 ptid = remote_current_thread (inferior_ptid);
3768
3769 return ptid;
3770 }
3771
3772 /* Query the remote target for which is the current thread/process,
3773 add it to our tables, and update INFERIOR_PTID. The caller is
3774 responsible for setting the state such that the remote end is ready
3775 to return the current thread.
3776
3777 This function is called after handling the '?' or 'vRun' packets,
3778 whose response is a stop reply from which we can also try
3779 extracting the thread. If the target doesn't support the explicit
3780 qC query, we infer the current thread from that stop reply, passed
3781 in in WAIT_STATUS, which may be NULL. */
3782
3783 static void
3784 add_current_inferior_and_thread (char *wait_status)
3785 {
3786 struct remote_state *rs = get_remote_state ();
3787 int fake_pid_p = 0;
3788 ptid_t ptid;
3789
3790 inferior_ptid = null_ptid;
3791
3792 /* Now, if we have thread information, update inferior_ptid. */
3793 ptid = get_current_thread (wait_status);
3794
3795 if (!ptid_equal (ptid, null_ptid))
3796 {
3797 if (!remote_multi_process_p (rs))
3798 fake_pid_p = 1;
3799
3800 inferior_ptid = ptid;
3801 }
3802 else
3803 {
3804 /* Without this, some commands which require an active target
3805 (such as kill) won't work. This variable serves (at least)
3806 double duty as both the pid of the target process (if it has
3807 such), and as a flag indicating that a target is active. */
3808 inferior_ptid = magic_null_ptid;
3809 fake_pid_p = 1;
3810 }
3811
3812 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3813
3814 /* Add the main thread. */
3815 add_thread_silent (inferior_ptid);
3816 }
3817
3818 /* Print info about a thread that was found already stopped on
3819 connection. */
3820
3821 static void
3822 print_one_stopped_thread (struct thread_info *thread)
3823 {
3824 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3825
3826 switch_to_thread (thread->ptid);
3827 stop_pc = get_frame_pc (get_current_frame ());
3828 set_current_sal_from_frame (get_current_frame ());
3829
3830 thread->suspend.waitstatus_pending_p = 0;
3831
3832 if (ws->kind == TARGET_WAITKIND_STOPPED)
3833 {
3834 enum gdb_signal sig = ws->value.sig;
3835
3836 if (signal_print_state (sig))
3837 observer_notify_signal_received (sig);
3838 }
3839 observer_notify_normal_stop (NULL, 1);
3840 }
3841
3842 /* Process all initial stop replies the remote side sent in response
3843 to the ? packet. These indicate threads that were already stopped
3844 on initial connection. We mark these threads as stopped and print
3845 their current frame before giving the user the prompt. */
3846
3847 static void
3848 process_initial_stop_replies (int from_tty)
3849 {
3850 int pending_stop_replies = stop_reply_queue_length ();
3851 struct inferior *inf;
3852 struct thread_info *thread;
3853 struct thread_info *selected = NULL;
3854 struct thread_info *lowest_stopped = NULL;
3855 struct thread_info *first = NULL;
3856
3857 /* Consume the initial pending events. */
3858 while (pending_stop_replies-- > 0)
3859 {
3860 ptid_t waiton_ptid = minus_one_ptid;
3861 ptid_t event_ptid;
3862 struct target_waitstatus ws;
3863 int ignore_event = 0;
3864 struct thread_info *thread;
3865
3866 memset (&ws, 0, sizeof (ws));
3867 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3868 if (remote_debug)
3869 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3870
3871 switch (ws.kind)
3872 {
3873 case TARGET_WAITKIND_IGNORE:
3874 case TARGET_WAITKIND_NO_RESUMED:
3875 case TARGET_WAITKIND_SIGNALLED:
3876 case TARGET_WAITKIND_EXITED:
3877 /* We shouldn't see these, but if we do, just ignore. */
3878 if (remote_debug)
3879 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3880 ignore_event = 1;
3881 break;
3882
3883 case TARGET_WAITKIND_EXECD:
3884 xfree (ws.value.execd_pathname);
3885 break;
3886 default:
3887 break;
3888 }
3889
3890 if (ignore_event)
3891 continue;
3892
3893 thread = find_thread_ptid (event_ptid);
3894
3895 if (ws.kind == TARGET_WAITKIND_STOPPED)
3896 {
3897 enum gdb_signal sig = ws.value.sig;
3898
3899 /* Stubs traditionally report SIGTRAP as initial signal,
3900 instead of signal 0. Suppress it. */
3901 if (sig == GDB_SIGNAL_TRAP)
3902 sig = GDB_SIGNAL_0;
3903 thread->suspend.stop_signal = sig;
3904 ws.value.sig = sig;
3905 }
3906
3907 thread->suspend.waitstatus = ws;
3908
3909 if (ws.kind != TARGET_WAITKIND_STOPPED
3910 || ws.value.sig != GDB_SIGNAL_0)
3911 thread->suspend.waitstatus_pending_p = 1;
3912
3913 set_executing (event_ptid, 0);
3914 set_running (event_ptid, 0);
3915 }
3916
3917 /* "Notice" the new inferiors before anything related to
3918 registers/memory. */
3919 ALL_INFERIORS (inf)
3920 {
3921 if (inf->pid == 0)
3922 continue;
3923
3924 inf->needs_setup = 1;
3925
3926 if (non_stop)
3927 {
3928 thread = any_live_thread_of_process (inf->pid);
3929 notice_new_inferior (thread->ptid,
3930 thread->state == THREAD_RUNNING,
3931 from_tty);
3932 }
3933 }
3934
3935 /* If all-stop on top of non-stop, pause all threads. Note this
3936 records the threads' stop pc, so must be done after "noticing"
3937 the inferiors. */
3938 if (!non_stop)
3939 {
3940 stop_all_threads ();
3941
3942 /* If all threads of an inferior were already stopped, we
3943 haven't setup the inferior yet. */
3944 ALL_INFERIORS (inf)
3945 {
3946 if (inf->pid == 0)
3947 continue;
3948
3949 if (inf->needs_setup)
3950 {
3951 thread = any_live_thread_of_process (inf->pid);
3952 switch_to_thread_no_regs (thread);
3953 setup_inferior (0);
3954 }
3955 }
3956 }
3957
3958 /* Now go over all threads that are stopped, and print their current
3959 frame. If all-stop, then if there's a signalled thread, pick
3960 that as current. */
3961 ALL_NON_EXITED_THREADS (thread)
3962 {
3963 if (first == NULL)
3964 first = thread;
3965
3966 if (!non_stop)
3967 set_running (thread->ptid, 0);
3968 else if (thread->state != THREAD_STOPPED)
3969 continue;
3970
3971 if (selected == NULL
3972 && thread->suspend.waitstatus_pending_p)
3973 selected = thread;
3974
3975 if (lowest_stopped == NULL
3976 || thread->inf->num < lowest_stopped->inf->num
3977 || thread->per_inf_num < lowest_stopped->per_inf_num)
3978 lowest_stopped = thread;
3979
3980 if (non_stop)
3981 print_one_stopped_thread (thread);
3982 }
3983
3984 /* In all-stop, we only print the status of one thread, and leave
3985 others with their status pending. */
3986 if (!non_stop)
3987 {
3988 thread = selected;
3989 if (thread == NULL)
3990 thread = lowest_stopped;
3991 if (thread == NULL)
3992 thread = first;
3993
3994 print_one_stopped_thread (thread);
3995 }
3996
3997 /* For "info program". */
3998 thread = inferior_thread ();
3999 if (thread->state == THREAD_STOPPED)
4000 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4001 }
4002
4003 /* Start the remote connection and sync state. */
4004
4005 static void
4006 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4007 {
4008 struct remote_state *rs = get_remote_state ();
4009 struct packet_config *noack_config;
4010 char *wait_status = NULL;
4011
4012 /* Signal other parts that we're going through the initial setup,
4013 and so things may not be stable yet. E.g., we don't try to
4014 install tracepoints until we've relocated symbols. Also, a
4015 Ctrl-C before we're connected and synced up can't interrupt the
4016 target. Instead, it offers to drop the (potentially wedged)
4017 connection. */
4018 rs->starting_up = 1;
4019
4020 QUIT;
4021
4022 if (interrupt_on_connect)
4023 send_interrupt_sequence ();
4024
4025 /* Ack any packet which the remote side has already sent. */
4026 remote_serial_write ("+", 1);
4027
4028 /* The first packet we send to the target is the optional "supported
4029 packets" request. If the target can answer this, it will tell us
4030 which later probes to skip. */
4031 remote_query_supported ();
4032
4033 /* If the stub wants to get a QAllow, compose one and send it. */
4034 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4035 remote_set_permissions (target);
4036
4037 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4038 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4039 as a reply to known packet. For packet "vFile:setfs:" it is an
4040 invalid reply and GDB would return error in
4041 remote_hostio_set_filesystem, making remote files access impossible.
4042 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4043 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4044 {
4045 const char v_mustreplyempty[] = "vMustReplyEmpty";
4046
4047 putpkt (v_mustreplyempty);
4048 getpkt (&rs->buf, &rs->buf_size, 0);
4049 if (strcmp (rs->buf, "OK") == 0)
4050 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4051 else if (strcmp (rs->buf, "") != 0)
4052 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4053 rs->buf);
4054 }
4055
4056 /* Next, we possibly activate noack mode.
4057
4058 If the QStartNoAckMode packet configuration is set to AUTO,
4059 enable noack mode if the stub reported a wish for it with
4060 qSupported.
4061
4062 If set to TRUE, then enable noack mode even if the stub didn't
4063 report it in qSupported. If the stub doesn't reply OK, the
4064 session ends with an error.
4065
4066 If FALSE, then don't activate noack mode, regardless of what the
4067 stub claimed should be the default with qSupported. */
4068
4069 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4070 if (packet_config_support (noack_config) != PACKET_DISABLE)
4071 {
4072 putpkt ("QStartNoAckMode");
4073 getpkt (&rs->buf, &rs->buf_size, 0);
4074 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4075 rs->noack_mode = 1;
4076 }
4077
4078 if (extended_p)
4079 {
4080 /* Tell the remote that we are using the extended protocol. */
4081 putpkt ("!");
4082 getpkt (&rs->buf, &rs->buf_size, 0);
4083 }
4084
4085 /* Let the target know which signals it is allowed to pass down to
4086 the program. */
4087 update_signals_program_target ();
4088
4089 /* Next, if the target can specify a description, read it. We do
4090 this before anything involving memory or registers. */
4091 target_find_description ();
4092
4093 /* Next, now that we know something about the target, update the
4094 address spaces in the program spaces. */
4095 update_address_spaces ();
4096
4097 /* On OSs where the list of libraries is global to all
4098 processes, we fetch them early. */
4099 if (gdbarch_has_global_solist (target_gdbarch ()))
4100 solib_add (NULL, from_tty, target, auto_solib_add);
4101
4102 if (target_is_non_stop_p ())
4103 {
4104 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4105 error (_("Non-stop mode requested, but remote "
4106 "does not support non-stop"));
4107
4108 putpkt ("QNonStop:1");
4109 getpkt (&rs->buf, &rs->buf_size, 0);
4110
4111 if (strcmp (rs->buf, "OK") != 0)
4112 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4113
4114 /* Find about threads and processes the stub is already
4115 controlling. We default to adding them in the running state.
4116 The '?' query below will then tell us about which threads are
4117 stopped. */
4118 remote_update_thread_list (target);
4119 }
4120 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4121 {
4122 /* Don't assume that the stub can operate in all-stop mode.
4123 Request it explicitly. */
4124 putpkt ("QNonStop:0");
4125 getpkt (&rs->buf, &rs->buf_size, 0);
4126
4127 if (strcmp (rs->buf, "OK") != 0)
4128 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4129 }
4130
4131 /* Upload TSVs regardless of whether the target is running or not. The
4132 remote stub, such as GDBserver, may have some predefined or builtin
4133 TSVs, even if the target is not running. */
4134 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4135 {
4136 struct uploaded_tsv *uploaded_tsvs = NULL;
4137
4138 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4139 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4140 }
4141
4142 /* Check whether the target is running now. */
4143 putpkt ("?");
4144 getpkt (&rs->buf, &rs->buf_size, 0);
4145
4146 if (!target_is_non_stop_p ())
4147 {
4148 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4149 {
4150 if (!extended_p)
4151 error (_("The target is not running (try extended-remote?)"));
4152
4153 /* We're connected, but not running. Drop out before we
4154 call start_remote. */
4155 rs->starting_up = 0;
4156 return;
4157 }
4158 else
4159 {
4160 /* Save the reply for later. */
4161 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4162 strcpy (wait_status, rs->buf);
4163 }
4164
4165 /* Fetch thread list. */
4166 target_update_thread_list ();
4167
4168 /* Let the stub know that we want it to return the thread. */
4169 set_continue_thread (minus_one_ptid);
4170
4171 if (thread_count () == 0)
4172 {
4173 /* Target has no concept of threads at all. GDB treats
4174 non-threaded target as single-threaded; add a main
4175 thread. */
4176 add_current_inferior_and_thread (wait_status);
4177 }
4178 else
4179 {
4180 /* We have thread information; select the thread the target
4181 says should be current. If we're reconnecting to a
4182 multi-threaded program, this will ideally be the thread
4183 that last reported an event before GDB disconnected. */
4184 inferior_ptid = get_current_thread (wait_status);
4185 if (ptid_equal (inferior_ptid, null_ptid))
4186 {
4187 /* Odd... The target was able to list threads, but not
4188 tell us which thread was current (no "thread"
4189 register in T stop reply?). Just pick the first
4190 thread in the thread list then. */
4191
4192 if (remote_debug)
4193 fprintf_unfiltered (gdb_stdlog,
4194 "warning: couldn't determine remote "
4195 "current thread; picking first in list.\n");
4196
4197 inferior_ptid = thread_list->ptid;
4198 }
4199 }
4200
4201 /* init_wait_for_inferior should be called before get_offsets in order
4202 to manage `inserted' flag in bp loc in a correct state.
4203 breakpoint_init_inferior, called from init_wait_for_inferior, set
4204 `inserted' flag to 0, while before breakpoint_re_set, called from
4205 start_remote, set `inserted' flag to 1. In the initialization of
4206 inferior, breakpoint_init_inferior should be called first, and then
4207 breakpoint_re_set can be called. If this order is broken, state of
4208 `inserted' flag is wrong, and cause some problems on breakpoint
4209 manipulation. */
4210 init_wait_for_inferior ();
4211
4212 get_offsets (); /* Get text, data & bss offsets. */
4213
4214 /* If we could not find a description using qXfer, and we know
4215 how to do it some other way, try again. This is not
4216 supported for non-stop; it could be, but it is tricky if
4217 there are no stopped threads when we connect. */
4218 if (remote_read_description_p (target)
4219 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4220 {
4221 target_clear_description ();
4222 target_find_description ();
4223 }
4224
4225 /* Use the previously fetched status. */
4226 gdb_assert (wait_status != NULL);
4227 strcpy (rs->buf, wait_status);
4228 rs->cached_wait_status = 1;
4229
4230 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4231 }
4232 else
4233 {
4234 /* Clear WFI global state. Do this before finding about new
4235 threads and inferiors, and setting the current inferior.
4236 Otherwise we would clear the proceed status of the current
4237 inferior when we want its stop_soon state to be preserved
4238 (see notice_new_inferior). */
4239 init_wait_for_inferior ();
4240
4241 /* In non-stop, we will either get an "OK", meaning that there
4242 are no stopped threads at this time; or, a regular stop
4243 reply. In the latter case, there may be more than one thread
4244 stopped --- we pull them all out using the vStopped
4245 mechanism. */
4246 if (strcmp (rs->buf, "OK") != 0)
4247 {
4248 struct notif_client *notif = &notif_client_stop;
4249
4250 /* remote_notif_get_pending_replies acks this one, and gets
4251 the rest out. */
4252 rs->notif_state->pending_event[notif_client_stop.id]
4253 = remote_notif_parse (notif, rs->buf);
4254 remote_notif_get_pending_events (notif);
4255 }
4256
4257 if (thread_count () == 0)
4258 {
4259 if (!extended_p)
4260 error (_("The target is not running (try extended-remote?)"));
4261
4262 /* We're connected, but not running. Drop out before we
4263 call start_remote. */
4264 rs->starting_up = 0;
4265 return;
4266 }
4267
4268 /* In non-stop mode, any cached wait status will be stored in
4269 the stop reply queue. */
4270 gdb_assert (wait_status == NULL);
4271
4272 /* Report all signals during attach/startup. */
4273 remote_pass_signals (target, 0, NULL);
4274
4275 /* If there are already stopped threads, mark them stopped and
4276 report their stops before giving the prompt to the user. */
4277 process_initial_stop_replies (from_tty);
4278
4279 if (target_can_async_p ())
4280 target_async (1);
4281 }
4282
4283 /* If we connected to a live target, do some additional setup. */
4284 if (target_has_execution)
4285 {
4286 if (symfile_objfile) /* No use without a symbol-file. */
4287 remote_check_symbols ();
4288 }
4289
4290 /* Possibly the target has been engaged in a trace run started
4291 previously; find out where things are at. */
4292 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4293 {
4294 struct uploaded_tp *uploaded_tps = NULL;
4295
4296 if (current_trace_status ()->running)
4297 printf_filtered (_("Trace is already running on the target.\n"));
4298
4299 remote_upload_tracepoints (target, &uploaded_tps);
4300
4301 merge_uploaded_tracepoints (&uploaded_tps);
4302 }
4303
4304 /* Possibly the target has been engaged in a btrace record started
4305 previously; find out where things are at. */
4306 remote_btrace_maybe_reopen ();
4307
4308 /* The thread and inferior lists are now synchronized with the
4309 target, our symbols have been relocated, and we're merged the
4310 target's tracepoints with ours. We're done with basic start
4311 up. */
4312 rs->starting_up = 0;
4313
4314 /* Maybe breakpoints are global and need to be inserted now. */
4315 if (breakpoints_should_be_inserted_now ())
4316 insert_breakpoints ();
4317 }
4318
4319 /* Open a connection to a remote debugger.
4320 NAME is the filename used for communication. */
4321
4322 static void
4323 remote_open (const char *name, int from_tty)
4324 {
4325 remote_open_1 (name, from_tty, &remote_ops, 0);
4326 }
4327
4328 /* Open a connection to a remote debugger using the extended
4329 remote gdb protocol. NAME is the filename used for communication. */
4330
4331 static void
4332 extended_remote_open (const char *name, int from_tty)
4333 {
4334 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4335 }
4336
4337 /* Reset all packets back to "unknown support". Called when opening a
4338 new connection to a remote target. */
4339
4340 static void
4341 reset_all_packet_configs_support (void)
4342 {
4343 int i;
4344
4345 for (i = 0; i < PACKET_MAX; i++)
4346 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4347 }
4348
4349 /* Initialize all packet configs. */
4350
4351 static void
4352 init_all_packet_configs (void)
4353 {
4354 int i;
4355
4356 for (i = 0; i < PACKET_MAX; i++)
4357 {
4358 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4359 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4360 }
4361 }
4362
4363 /* Symbol look-up. */
4364
4365 static void
4366 remote_check_symbols (void)
4367 {
4368 struct remote_state *rs = get_remote_state ();
4369 char *msg, *reply, *tmp;
4370 int end;
4371 long reply_size;
4372 struct cleanup *old_chain;
4373
4374 /* The remote side has no concept of inferiors that aren't running
4375 yet, it only knows about running processes. If we're connected
4376 but our current inferior is not running, we should not invite the
4377 remote target to request symbol lookups related to its
4378 (unrelated) current process. */
4379 if (!target_has_execution)
4380 return;
4381
4382 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4383 return;
4384
4385 /* Make sure the remote is pointing at the right process. Note
4386 there's no way to select "no process". */
4387 set_general_process ();
4388
4389 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4390 because we need both at the same time. */
4391 msg = (char *) xmalloc (get_remote_packet_size ());
4392 old_chain = make_cleanup (xfree, msg);
4393 reply = (char *) xmalloc (get_remote_packet_size ());
4394 make_cleanup (free_current_contents, &reply);
4395 reply_size = get_remote_packet_size ();
4396
4397 /* Invite target to request symbol lookups. */
4398
4399 putpkt ("qSymbol::");
4400 getpkt (&reply, &reply_size, 0);
4401 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4402
4403 while (startswith (reply, "qSymbol:"))
4404 {
4405 struct bound_minimal_symbol sym;
4406
4407 tmp = &reply[8];
4408 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4409 msg[end] = '\0';
4410 sym = lookup_minimal_symbol (msg, NULL, NULL);
4411 if (sym.minsym == NULL)
4412 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4413 else
4414 {
4415 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4416 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4417
4418 /* If this is a function address, return the start of code
4419 instead of any data function descriptor. */
4420 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4421 sym_addr,
4422 &current_target);
4423
4424 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4425 phex_nz (sym_addr, addr_size), &reply[8]);
4426 }
4427
4428 putpkt (msg);
4429 getpkt (&reply, &reply_size, 0);
4430 }
4431
4432 do_cleanups (old_chain);
4433 }
4434
4435 static struct serial *
4436 remote_serial_open (const char *name)
4437 {
4438 static int udp_warning = 0;
4439
4440 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4441 of in ser-tcp.c, because it is the remote protocol assuming that the
4442 serial connection is reliable and not the serial connection promising
4443 to be. */
4444 if (!udp_warning && startswith (name, "udp:"))
4445 {
4446 warning (_("The remote protocol may be unreliable over UDP.\n"
4447 "Some events may be lost, rendering further debugging "
4448 "impossible."));
4449 udp_warning = 1;
4450 }
4451
4452 return serial_open (name);
4453 }
4454
4455 /* Inform the target of our permission settings. The permission flags
4456 work without this, but if the target knows the settings, it can do
4457 a couple things. First, it can add its own check, to catch cases
4458 that somehow manage to get by the permissions checks in target
4459 methods. Second, if the target is wired to disallow particular
4460 settings (for instance, a system in the field that is not set up to
4461 be able to stop at a breakpoint), it can object to any unavailable
4462 permissions. */
4463
4464 void
4465 remote_set_permissions (struct target_ops *self)
4466 {
4467 struct remote_state *rs = get_remote_state ();
4468
4469 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4470 "WriteReg:%x;WriteMem:%x;"
4471 "InsertBreak:%x;InsertTrace:%x;"
4472 "InsertFastTrace:%x;Stop:%x",
4473 may_write_registers, may_write_memory,
4474 may_insert_breakpoints, may_insert_tracepoints,
4475 may_insert_fast_tracepoints, may_stop);
4476 putpkt (rs->buf);
4477 getpkt (&rs->buf, &rs->buf_size, 0);
4478
4479 /* If the target didn't like the packet, warn the user. Do not try
4480 to undo the user's settings, that would just be maddening. */
4481 if (strcmp (rs->buf, "OK") != 0)
4482 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4483 }
4484
4485 /* This type describes each known response to the qSupported
4486 packet. */
4487 struct protocol_feature
4488 {
4489 /* The name of this protocol feature. */
4490 const char *name;
4491
4492 /* The default for this protocol feature. */
4493 enum packet_support default_support;
4494
4495 /* The function to call when this feature is reported, or after
4496 qSupported processing if the feature is not supported.
4497 The first argument points to this structure. The second
4498 argument indicates whether the packet requested support be
4499 enabled, disabled, or probed (or the default, if this function
4500 is being called at the end of processing and this feature was
4501 not reported). The third argument may be NULL; if not NULL, it
4502 is a NUL-terminated string taken from the packet following
4503 this feature's name and an equals sign. */
4504 void (*func) (const struct protocol_feature *, enum packet_support,
4505 const char *);
4506
4507 /* The corresponding packet for this feature. Only used if
4508 FUNC is remote_supported_packet. */
4509 int packet;
4510 };
4511
4512 static void
4513 remote_supported_packet (const struct protocol_feature *feature,
4514 enum packet_support support,
4515 const char *argument)
4516 {
4517 if (argument)
4518 {
4519 warning (_("Remote qSupported response supplied an unexpected value for"
4520 " \"%s\"."), feature->name);
4521 return;
4522 }
4523
4524 remote_protocol_packets[feature->packet].support = support;
4525 }
4526
4527 static void
4528 remote_packet_size (const struct protocol_feature *feature,
4529 enum packet_support support, const char *value)
4530 {
4531 struct remote_state *rs = get_remote_state ();
4532
4533 int packet_size;
4534 char *value_end;
4535
4536 if (support != PACKET_ENABLE)
4537 return;
4538
4539 if (value == NULL || *value == '\0')
4540 {
4541 warning (_("Remote target reported \"%s\" without a size."),
4542 feature->name);
4543 return;
4544 }
4545
4546 errno = 0;
4547 packet_size = strtol (value, &value_end, 16);
4548 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4549 {
4550 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4551 feature->name, value);
4552 return;
4553 }
4554
4555 /* Record the new maximum packet size. */
4556 rs->explicit_packet_size = packet_size;
4557 }
4558
4559 static const struct protocol_feature remote_protocol_features[] = {
4560 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4561 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4562 PACKET_qXfer_auxv },
4563 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4564 PACKET_qXfer_exec_file },
4565 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4566 PACKET_qXfer_features },
4567 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4568 PACKET_qXfer_libraries },
4569 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4570 PACKET_qXfer_libraries_svr4 },
4571 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4572 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4573 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4574 PACKET_qXfer_memory_map },
4575 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4576 PACKET_qXfer_spu_read },
4577 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4578 PACKET_qXfer_spu_write },
4579 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4580 PACKET_qXfer_osdata },
4581 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4582 PACKET_qXfer_threads },
4583 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4584 PACKET_qXfer_traceframe_info },
4585 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4586 PACKET_QPassSignals },
4587 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4588 PACKET_QCatchSyscalls },
4589 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4590 PACKET_QProgramSignals },
4591 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4592 PACKET_QStartNoAckMode },
4593 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4594 PACKET_multiprocess_feature },
4595 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4596 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4597 PACKET_qXfer_siginfo_read },
4598 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4599 PACKET_qXfer_siginfo_write },
4600 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4601 PACKET_ConditionalTracepoints },
4602 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4603 PACKET_ConditionalBreakpoints },
4604 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4605 PACKET_BreakpointCommands },
4606 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4607 PACKET_FastTracepoints },
4608 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4609 PACKET_StaticTracepoints },
4610 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4611 PACKET_InstallInTrace},
4612 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4613 PACKET_DisconnectedTracing_feature },
4614 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4615 PACKET_bc },
4616 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4617 PACKET_bs },
4618 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4619 PACKET_TracepointSource },
4620 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4621 PACKET_QAllow },
4622 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4623 PACKET_EnableDisableTracepoints_feature },
4624 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4625 PACKET_qXfer_fdpic },
4626 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4627 PACKET_qXfer_uib },
4628 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4629 PACKET_QDisableRandomization },
4630 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4631 { "QTBuffer:size", PACKET_DISABLE,
4632 remote_supported_packet, PACKET_QTBuffer_size},
4633 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4634 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4635 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4636 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4637 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4638 PACKET_qXfer_btrace },
4639 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4640 PACKET_qXfer_btrace_conf },
4641 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4642 PACKET_Qbtrace_conf_bts_size },
4643 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4644 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4645 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4646 PACKET_fork_event_feature },
4647 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4648 PACKET_vfork_event_feature },
4649 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4650 PACKET_exec_event_feature },
4651 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4652 PACKET_Qbtrace_conf_pt_size },
4653 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4654 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4655 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4656 };
4657
4658 static char *remote_support_xml;
4659
4660 /* Register string appended to "xmlRegisters=" in qSupported query. */
4661
4662 void
4663 register_remote_support_xml (const char *xml)
4664 {
4665 #if defined(HAVE_LIBEXPAT)
4666 if (remote_support_xml == NULL)
4667 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4668 else
4669 {
4670 char *copy = xstrdup (remote_support_xml + 13);
4671 char *p = strtok (copy, ",");
4672
4673 do
4674 {
4675 if (strcmp (p, xml) == 0)
4676 {
4677 /* already there */
4678 xfree (copy);
4679 return;
4680 }
4681 }
4682 while ((p = strtok (NULL, ",")) != NULL);
4683 xfree (copy);
4684
4685 remote_support_xml = reconcat (remote_support_xml,
4686 remote_support_xml, ",", xml,
4687 (char *) NULL);
4688 }
4689 #endif
4690 }
4691
4692 static char *
4693 remote_query_supported_append (char *msg, const char *append)
4694 {
4695 if (msg)
4696 return reconcat (msg, msg, ";", append, (char *) NULL);
4697 else
4698 return xstrdup (append);
4699 }
4700
4701 static void
4702 remote_query_supported (void)
4703 {
4704 struct remote_state *rs = get_remote_state ();
4705 char *next;
4706 int i;
4707 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4708
4709 /* The packet support flags are handled differently for this packet
4710 than for most others. We treat an error, a disabled packet, and
4711 an empty response identically: any features which must be reported
4712 to be used will be automatically disabled. An empty buffer
4713 accomplishes this, since that is also the representation for a list
4714 containing no features. */
4715
4716 rs->buf[0] = 0;
4717 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4718 {
4719 char *q = NULL;
4720 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4721
4722 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4723 q = remote_query_supported_append (q, "multiprocess+");
4724
4725 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4726 q = remote_query_supported_append (q, "swbreak+");
4727 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4728 q = remote_query_supported_append (q, "hwbreak+");
4729
4730 q = remote_query_supported_append (q, "qRelocInsn+");
4731
4732 if (packet_set_cmd_state (PACKET_fork_event_feature)
4733 != AUTO_BOOLEAN_FALSE)
4734 q = remote_query_supported_append (q, "fork-events+");
4735 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4736 != AUTO_BOOLEAN_FALSE)
4737 q = remote_query_supported_append (q, "vfork-events+");
4738 if (packet_set_cmd_state (PACKET_exec_event_feature)
4739 != AUTO_BOOLEAN_FALSE)
4740 q = remote_query_supported_append (q, "exec-events+");
4741
4742 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4743 q = remote_query_supported_append (q, "vContSupported+");
4744
4745 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4746 q = remote_query_supported_append (q, "QThreadEvents+");
4747
4748 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4749 q = remote_query_supported_append (q, "no-resumed+");
4750
4751 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4752 the qSupported:xmlRegisters=i386 handling. */
4753 if (remote_support_xml != NULL)
4754 q = remote_query_supported_append (q, remote_support_xml);
4755
4756 q = reconcat (q, "qSupported:", q, (char *) NULL);
4757 putpkt (q);
4758
4759 do_cleanups (old_chain);
4760
4761 getpkt (&rs->buf, &rs->buf_size, 0);
4762
4763 /* If an error occured, warn, but do not return - just reset the
4764 buffer to empty and go on to disable features. */
4765 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4766 == PACKET_ERROR)
4767 {
4768 warning (_("Remote failure reply: %s"), rs->buf);
4769 rs->buf[0] = 0;
4770 }
4771 }
4772
4773 memset (seen, 0, sizeof (seen));
4774
4775 next = rs->buf;
4776 while (*next)
4777 {
4778 enum packet_support is_supported;
4779 char *p, *end, *name_end, *value;
4780
4781 /* First separate out this item from the rest of the packet. If
4782 there's another item after this, we overwrite the separator
4783 (terminated strings are much easier to work with). */
4784 p = next;
4785 end = strchr (p, ';');
4786 if (end == NULL)
4787 {
4788 end = p + strlen (p);
4789 next = end;
4790 }
4791 else
4792 {
4793 *end = '\0';
4794 next = end + 1;
4795
4796 if (end == p)
4797 {
4798 warning (_("empty item in \"qSupported\" response"));
4799 continue;
4800 }
4801 }
4802
4803 name_end = strchr (p, '=');
4804 if (name_end)
4805 {
4806 /* This is a name=value entry. */
4807 is_supported = PACKET_ENABLE;
4808 value = name_end + 1;
4809 *name_end = '\0';
4810 }
4811 else
4812 {
4813 value = NULL;
4814 switch (end[-1])
4815 {
4816 case '+':
4817 is_supported = PACKET_ENABLE;
4818 break;
4819
4820 case '-':
4821 is_supported = PACKET_DISABLE;
4822 break;
4823
4824 case '?':
4825 is_supported = PACKET_SUPPORT_UNKNOWN;
4826 break;
4827
4828 default:
4829 warning (_("unrecognized item \"%s\" "
4830 "in \"qSupported\" response"), p);
4831 continue;
4832 }
4833 end[-1] = '\0';
4834 }
4835
4836 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4837 if (strcmp (remote_protocol_features[i].name, p) == 0)
4838 {
4839 const struct protocol_feature *feature;
4840
4841 seen[i] = 1;
4842 feature = &remote_protocol_features[i];
4843 feature->func (feature, is_supported, value);
4844 break;
4845 }
4846 }
4847
4848 /* If we increased the packet size, make sure to increase the global
4849 buffer size also. We delay this until after parsing the entire
4850 qSupported packet, because this is the same buffer we were
4851 parsing. */
4852 if (rs->buf_size < rs->explicit_packet_size)
4853 {
4854 rs->buf_size = rs->explicit_packet_size;
4855 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4856 }
4857
4858 /* Handle the defaults for unmentioned features. */
4859 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4860 if (!seen[i])
4861 {
4862 const struct protocol_feature *feature;
4863
4864 feature = &remote_protocol_features[i];
4865 feature->func (feature, feature->default_support, NULL);
4866 }
4867 }
4868
4869 /* Serial QUIT handler for the remote serial descriptor.
4870
4871 Defers handling a Ctrl-C until we're done with the current
4872 command/response packet sequence, unless:
4873
4874 - We're setting up the connection. Don't send a remote interrupt
4875 request, as we're not fully synced yet. Quit immediately
4876 instead.
4877
4878 - The target has been resumed in the foreground
4879 (target_terminal_is_ours is false) with a synchronous resume
4880 packet, and we're blocked waiting for the stop reply, thus a
4881 Ctrl-C should be immediately sent to the target.
4882
4883 - We get a second Ctrl-C while still within the same serial read or
4884 write. In that case the serial is seemingly wedged --- offer to
4885 quit/disconnect.
4886
4887 - We see a second Ctrl-C without target response, after having
4888 previously interrupted the target. In that case the target/stub
4889 is probably wedged --- offer to quit/disconnect.
4890 */
4891
4892 static void
4893 remote_serial_quit_handler (void)
4894 {
4895 struct remote_state *rs = get_remote_state ();
4896
4897 if (check_quit_flag ())
4898 {
4899 /* If we're starting up, we're not fully synced yet. Quit
4900 immediately. */
4901 if (rs->starting_up)
4902 quit ();
4903 else if (rs->got_ctrlc_during_io)
4904 {
4905 if (query (_("The target is not responding to GDB commands.\n"
4906 "Stop debugging it? ")))
4907 remote_unpush_and_throw ();
4908 }
4909 /* If ^C has already been sent once, offer to disconnect. */
4910 else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4911 interrupt_query ();
4912 /* All-stop protocol, and blocked waiting for stop reply. Send
4913 an interrupt request. */
4914 else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4915 target_interrupt (inferior_ptid);
4916 else
4917 rs->got_ctrlc_during_io = 1;
4918 }
4919 }
4920
4921 /* Remove any of the remote.c targets from target stack. Upper targets depend
4922 on it so remove them first. */
4923
4924 static void
4925 remote_unpush_target (void)
4926 {
4927 pop_all_targets_at_and_above (process_stratum);
4928 }
4929
4930 static void
4931 remote_unpush_and_throw (void)
4932 {
4933 remote_unpush_target ();
4934 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4935 }
4936
4937 static void
4938 remote_open_1 (const char *name, int from_tty,
4939 struct target_ops *target, int extended_p)
4940 {
4941 struct remote_state *rs = get_remote_state ();
4942
4943 if (name == 0)
4944 error (_("To open a remote debug connection, you need to specify what\n"
4945 "serial device is attached to the remote system\n"
4946 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4947
4948 /* See FIXME above. */
4949 if (!target_async_permitted)
4950 wait_forever_enabled_p = 1;
4951
4952 /* If we're connected to a running target, target_preopen will kill it.
4953 Ask this question first, before target_preopen has a chance to kill
4954 anything. */
4955 if (rs->remote_desc != NULL && !have_inferiors ())
4956 {
4957 if (from_tty
4958 && !query (_("Already connected to a remote target. Disconnect? ")))
4959 error (_("Still connected."));
4960 }
4961
4962 /* Here the possibly existing remote target gets unpushed. */
4963 target_preopen (from_tty);
4964
4965 /* Make sure we send the passed signals list the next time we resume. */
4966 xfree (rs->last_pass_packet);
4967 rs->last_pass_packet = NULL;
4968
4969 /* Make sure we send the program signals list the next time we
4970 resume. */
4971 xfree (rs->last_program_signals_packet);
4972 rs->last_program_signals_packet = NULL;
4973
4974 remote_fileio_reset ();
4975 reopen_exec_file ();
4976 reread_symbols ();
4977
4978 rs->remote_desc = remote_serial_open (name);
4979 if (!rs->remote_desc)
4980 perror_with_name (name);
4981
4982 if (baud_rate != -1)
4983 {
4984 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4985 {
4986 /* The requested speed could not be set. Error out to
4987 top level after closing remote_desc. Take care to
4988 set remote_desc to NULL to avoid closing remote_desc
4989 more than once. */
4990 serial_close (rs->remote_desc);
4991 rs->remote_desc = NULL;
4992 perror_with_name (name);
4993 }
4994 }
4995
4996 serial_setparity (rs->remote_desc, serial_parity);
4997 serial_raw (rs->remote_desc);
4998
4999 /* If there is something sitting in the buffer we might take it as a
5000 response to a command, which would be bad. */
5001 serial_flush_input (rs->remote_desc);
5002
5003 if (from_tty)
5004 {
5005 puts_filtered ("Remote debugging using ");
5006 puts_filtered (name);
5007 puts_filtered ("\n");
5008 }
5009 push_target (target); /* Switch to using remote target now. */
5010
5011 /* Register extra event sources in the event loop. */
5012 remote_async_inferior_event_token
5013 = create_async_event_handler (remote_async_inferior_event_handler,
5014 NULL);
5015 rs->notif_state = remote_notif_state_allocate ();
5016
5017 /* Reset the target state; these things will be queried either by
5018 remote_query_supported or as they are needed. */
5019 reset_all_packet_configs_support ();
5020 rs->cached_wait_status = 0;
5021 rs->explicit_packet_size = 0;
5022 rs->noack_mode = 0;
5023 rs->extended = extended_p;
5024 rs->waiting_for_stop_reply = 0;
5025 rs->ctrlc_pending_p = 0;
5026 rs->got_ctrlc_during_io = 0;
5027
5028 rs->general_thread = not_sent_ptid;
5029 rs->continue_thread = not_sent_ptid;
5030 rs->remote_traceframe_number = -1;
5031
5032 rs->last_resume_exec_dir = EXEC_FORWARD;
5033
5034 /* Probe for ability to use "ThreadInfo" query, as required. */
5035 rs->use_threadinfo_query = 1;
5036 rs->use_threadextra_query = 1;
5037
5038 readahead_cache_invalidate ();
5039
5040 /* Start out by owning the terminal. */
5041 remote_async_terminal_ours_p = 1;
5042
5043 if (target_async_permitted)
5044 {
5045 /* FIXME: cagney/1999-09-23: During the initial connection it is
5046 assumed that the target is already ready and able to respond to
5047 requests. Unfortunately remote_start_remote() eventually calls
5048 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5049 around this. Eventually a mechanism that allows
5050 wait_for_inferior() to expect/get timeouts will be
5051 implemented. */
5052 wait_forever_enabled_p = 0;
5053 }
5054
5055 /* First delete any symbols previously loaded from shared libraries. */
5056 no_shared_libraries (NULL, 0);
5057
5058 /* Start afresh. */
5059 init_thread_list ();
5060
5061 /* Start the remote connection. If error() or QUIT, discard this
5062 target (we'd otherwise be in an inconsistent state) and then
5063 propogate the error on up the exception chain. This ensures that
5064 the caller doesn't stumble along blindly assuming that the
5065 function succeeded. The CLI doesn't have this problem but other
5066 UI's, such as MI do.
5067
5068 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5069 this function should return an error indication letting the
5070 caller restore the previous state. Unfortunately the command
5071 ``target remote'' is directly wired to this function making that
5072 impossible. On a positive note, the CLI side of this problem has
5073 been fixed - the function set_cmd_context() makes it possible for
5074 all the ``target ....'' commands to share a common callback
5075 function. See cli-dump.c. */
5076 {
5077
5078 TRY
5079 {
5080 remote_start_remote (from_tty, target, extended_p);
5081 }
5082 CATCH (ex, RETURN_MASK_ALL)
5083 {
5084 /* Pop the partially set up target - unless something else did
5085 already before throwing the exception. */
5086 if (rs->remote_desc != NULL)
5087 remote_unpush_target ();
5088 if (target_async_permitted)
5089 wait_forever_enabled_p = 1;
5090 throw_exception (ex);
5091 }
5092 END_CATCH
5093 }
5094
5095 remote_btrace_reset ();
5096
5097 if (target_async_permitted)
5098 wait_forever_enabled_p = 1;
5099 }
5100
5101 /* Detach the specified process. */
5102
5103 static void
5104 remote_detach_pid (int pid)
5105 {
5106 struct remote_state *rs = get_remote_state ();
5107
5108 if (remote_multi_process_p (rs))
5109 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5110 else
5111 strcpy (rs->buf, "D");
5112
5113 putpkt (rs->buf);
5114 getpkt (&rs->buf, &rs->buf_size, 0);
5115
5116 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5117 ;
5118 else if (rs->buf[0] == '\0')
5119 error (_("Remote doesn't know how to detach"));
5120 else
5121 error (_("Can't detach process."));
5122 }
5123
5124 /* This detaches a program to which we previously attached, using
5125 inferior_ptid to identify the process. After this is done, GDB
5126 can be used to debug some other program. We better not have left
5127 any breakpoints in the target program or it'll die when it hits
5128 one. */
5129
5130 static void
5131 remote_detach_1 (const char *args, int from_tty)
5132 {
5133 int pid = ptid_get_pid (inferior_ptid);
5134 struct remote_state *rs = get_remote_state ();
5135 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5136 int is_fork_parent;
5137
5138 if (args)
5139 error (_("Argument given to \"detach\" when remotely debugging."));
5140
5141 if (!target_has_execution)
5142 error (_("No process to detach from."));
5143
5144 target_announce_detach (from_tty);
5145
5146 /* Tell the remote target to detach. */
5147 remote_detach_pid (pid);
5148
5149 /* Exit only if this is the only active inferior. */
5150 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5151 puts_filtered (_("Ending remote debugging.\n"));
5152
5153 /* Check to see if we are detaching a fork parent. Note that if we
5154 are detaching a fork child, tp == NULL. */
5155 is_fork_parent = (tp != NULL
5156 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5157
5158 /* If doing detach-on-fork, we don't mourn, because that will delete
5159 breakpoints that should be available for the followed inferior. */
5160 if (!is_fork_parent)
5161 target_mourn_inferior ();
5162 else
5163 {
5164 inferior_ptid = null_ptid;
5165 detach_inferior (pid);
5166 }
5167 }
5168
5169 static void
5170 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5171 {
5172 remote_detach_1 (args, from_tty);
5173 }
5174
5175 static void
5176 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5177 {
5178 remote_detach_1 (args, from_tty);
5179 }
5180
5181 /* Target follow-fork function for remote targets. On entry, and
5182 at return, the current inferior is the fork parent.
5183
5184 Note that although this is currently only used for extended-remote,
5185 it is named remote_follow_fork in anticipation of using it for the
5186 remote target as well. */
5187
5188 static int
5189 remote_follow_fork (struct target_ops *ops, int follow_child,
5190 int detach_fork)
5191 {
5192 struct remote_state *rs = get_remote_state ();
5193 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5194
5195 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5196 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5197 {
5198 /* When following the parent and detaching the child, we detach
5199 the child here. For the case of following the child and
5200 detaching the parent, the detach is done in the target-
5201 independent follow fork code in infrun.c. We can't use
5202 target_detach when detaching an unfollowed child because
5203 the client side doesn't know anything about the child. */
5204 if (detach_fork && !follow_child)
5205 {
5206 /* Detach the fork child. */
5207 ptid_t child_ptid;
5208 pid_t child_pid;
5209
5210 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5211 child_pid = ptid_get_pid (child_ptid);
5212
5213 remote_detach_pid (child_pid);
5214 detach_inferior (child_pid);
5215 }
5216 }
5217 return 0;
5218 }
5219
5220 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5221 in the program space of the new inferior. On entry and at return the
5222 current inferior is the exec'ing inferior. INF is the new exec'd
5223 inferior, which may be the same as the exec'ing inferior unless
5224 follow-exec-mode is "new". */
5225
5226 static void
5227 remote_follow_exec (struct target_ops *ops,
5228 struct inferior *inf, char *execd_pathname)
5229 {
5230 /* We know that this is a target file name, so if it has the "target:"
5231 prefix we strip it off before saving it in the program space. */
5232 if (is_target_filename (execd_pathname))
5233 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5234
5235 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5236 }
5237
5238 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5239
5240 static void
5241 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5242 {
5243 if (args)
5244 error (_("Argument given to \"disconnect\" when remotely debugging."));
5245
5246 /* Make sure we unpush even the extended remote targets. Calling
5247 target_mourn_inferior won't unpush, and remote_mourn won't
5248 unpush if there is more than one inferior left. */
5249 unpush_target (target);
5250 generic_mourn_inferior ();
5251
5252 if (from_tty)
5253 puts_filtered ("Ending remote debugging.\n");
5254 }
5255
5256 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5257 be chatty about it. */
5258
5259 static void
5260 extended_remote_attach (struct target_ops *target, const char *args,
5261 int from_tty)
5262 {
5263 struct remote_state *rs = get_remote_state ();
5264 int pid;
5265 char *wait_status = NULL;
5266
5267 pid = parse_pid_to_attach (args);
5268
5269 /* Remote PID can be freely equal to getpid, do not check it here the same
5270 way as in other targets. */
5271
5272 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5273 error (_("This target does not support attaching to a process"));
5274
5275 if (from_tty)
5276 {
5277 char *exec_file = get_exec_file (0);
5278
5279 if (exec_file)
5280 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5281 target_pid_to_str (pid_to_ptid (pid)));
5282 else
5283 printf_unfiltered (_("Attaching to %s\n"),
5284 target_pid_to_str (pid_to_ptid (pid)));
5285
5286 gdb_flush (gdb_stdout);
5287 }
5288
5289 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5290 putpkt (rs->buf);
5291 getpkt (&rs->buf, &rs->buf_size, 0);
5292
5293 switch (packet_ok (rs->buf,
5294 &remote_protocol_packets[PACKET_vAttach]))
5295 {
5296 case PACKET_OK:
5297 if (!target_is_non_stop_p ())
5298 {
5299 /* Save the reply for later. */
5300 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5301 strcpy (wait_status, rs->buf);
5302 }
5303 else if (strcmp (rs->buf, "OK") != 0)
5304 error (_("Attaching to %s failed with: %s"),
5305 target_pid_to_str (pid_to_ptid (pid)),
5306 rs->buf);
5307 break;
5308 case PACKET_UNKNOWN:
5309 error (_("This target does not support attaching to a process"));
5310 default:
5311 error (_("Attaching to %s failed"),
5312 target_pid_to_str (pid_to_ptid (pid)));
5313 }
5314
5315 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5316
5317 inferior_ptid = pid_to_ptid (pid);
5318
5319 if (target_is_non_stop_p ())
5320 {
5321 struct thread_info *thread;
5322
5323 /* Get list of threads. */
5324 remote_update_thread_list (target);
5325
5326 thread = first_thread_of_process (pid);
5327 if (thread)
5328 inferior_ptid = thread->ptid;
5329 else
5330 inferior_ptid = pid_to_ptid (pid);
5331
5332 /* Invalidate our notion of the remote current thread. */
5333 record_currthread (rs, minus_one_ptid);
5334 }
5335 else
5336 {
5337 /* Now, if we have thread information, update inferior_ptid. */
5338 inferior_ptid = remote_current_thread (inferior_ptid);
5339
5340 /* Add the main thread to the thread list. */
5341 add_thread_silent (inferior_ptid);
5342 }
5343
5344 /* Next, if the target can specify a description, read it. We do
5345 this before anything involving memory or registers. */
5346 target_find_description ();
5347
5348 if (!target_is_non_stop_p ())
5349 {
5350 /* Use the previously fetched status. */
5351 gdb_assert (wait_status != NULL);
5352
5353 if (target_can_async_p ())
5354 {
5355 struct notif_event *reply
5356 = remote_notif_parse (&notif_client_stop, wait_status);
5357
5358 push_stop_reply ((struct stop_reply *) reply);
5359
5360 target_async (1);
5361 }
5362 else
5363 {
5364 gdb_assert (wait_status != NULL);
5365 strcpy (rs->buf, wait_status);
5366 rs->cached_wait_status = 1;
5367 }
5368 }
5369 else
5370 gdb_assert (wait_status == NULL);
5371 }
5372
5373 /* Implementation of the to_post_attach method. */
5374
5375 static void
5376 extended_remote_post_attach (struct target_ops *ops, int pid)
5377 {
5378 /* Get text, data & bss offsets. */
5379 get_offsets ();
5380
5381 /* In certain cases GDB might not have had the chance to start
5382 symbol lookup up until now. This could happen if the debugged
5383 binary is not using shared libraries, the vsyscall page is not
5384 present (on Linux) and the binary itself hadn't changed since the
5385 debugging process was started. */
5386 if (symfile_objfile != NULL)
5387 remote_check_symbols();
5388 }
5389
5390 \f
5391 /* Check for the availability of vCont. This function should also check
5392 the response. */
5393
5394 static void
5395 remote_vcont_probe (struct remote_state *rs)
5396 {
5397 char *buf;
5398
5399 strcpy (rs->buf, "vCont?");
5400 putpkt (rs->buf);
5401 getpkt (&rs->buf, &rs->buf_size, 0);
5402 buf = rs->buf;
5403
5404 /* Make sure that the features we assume are supported. */
5405 if (startswith (buf, "vCont"))
5406 {
5407 char *p = &buf[5];
5408 int support_c, support_C;
5409
5410 rs->supports_vCont.s = 0;
5411 rs->supports_vCont.S = 0;
5412 support_c = 0;
5413 support_C = 0;
5414 rs->supports_vCont.t = 0;
5415 rs->supports_vCont.r = 0;
5416 while (p && *p == ';')
5417 {
5418 p++;
5419 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5420 rs->supports_vCont.s = 1;
5421 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5422 rs->supports_vCont.S = 1;
5423 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5424 support_c = 1;
5425 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5426 support_C = 1;
5427 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5428 rs->supports_vCont.t = 1;
5429 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5430 rs->supports_vCont.r = 1;
5431
5432 p = strchr (p, ';');
5433 }
5434
5435 /* If c, and C are not all supported, we can't use vCont. Clearing
5436 BUF will make packet_ok disable the packet. */
5437 if (!support_c || !support_C)
5438 buf[0] = 0;
5439 }
5440
5441 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5442 }
5443
5444 /* Helper function for building "vCont" resumptions. Write a
5445 resumption to P. ENDP points to one-passed-the-end of the buffer
5446 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5447 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5448 resumed thread should be single-stepped and/or signalled. If PTID
5449 equals minus_one_ptid, then all threads are resumed; if PTID
5450 represents a process, then all threads of the process are resumed;
5451 the thread to be stepped and/or signalled is given in the global
5452 INFERIOR_PTID. */
5453
5454 static char *
5455 append_resumption (char *p, char *endp,
5456 ptid_t ptid, int step, enum gdb_signal siggnal)
5457 {
5458 struct remote_state *rs = get_remote_state ();
5459
5460 if (step && siggnal != GDB_SIGNAL_0)
5461 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5462 else if (step
5463 /* GDB is willing to range step. */
5464 && use_range_stepping
5465 /* Target supports range stepping. */
5466 && rs->supports_vCont.r
5467 /* We don't currently support range stepping multiple
5468 threads with a wildcard (though the protocol allows it,
5469 so stubs shouldn't make an active effort to forbid
5470 it). */
5471 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5472 {
5473 struct thread_info *tp;
5474
5475 if (ptid_equal (ptid, minus_one_ptid))
5476 {
5477 /* If we don't know about the target thread's tid, then
5478 we're resuming magic_null_ptid (see caller). */
5479 tp = find_thread_ptid (magic_null_ptid);
5480 }
5481 else
5482 tp = find_thread_ptid (ptid);
5483 gdb_assert (tp != NULL);
5484
5485 if (tp->control.may_range_step)
5486 {
5487 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5488
5489 p += xsnprintf (p, endp - p, ";r%s,%s",
5490 phex_nz (tp->control.step_range_start,
5491 addr_size),
5492 phex_nz (tp->control.step_range_end,
5493 addr_size));
5494 }
5495 else
5496 p += xsnprintf (p, endp - p, ";s");
5497 }
5498 else if (step)
5499 p += xsnprintf (p, endp - p, ";s");
5500 else if (siggnal != GDB_SIGNAL_0)
5501 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5502 else
5503 p += xsnprintf (p, endp - p, ";c");
5504
5505 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5506 {
5507 ptid_t nptid;
5508
5509 /* All (-1) threads of process. */
5510 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5511
5512 p += xsnprintf (p, endp - p, ":");
5513 p = write_ptid (p, endp, nptid);
5514 }
5515 else if (!ptid_equal (ptid, minus_one_ptid))
5516 {
5517 p += xsnprintf (p, endp - p, ":");
5518 p = write_ptid (p, endp, ptid);
5519 }
5520
5521 return p;
5522 }
5523
5524 /* Clear the thread's private info on resume. */
5525
5526 static void
5527 resume_clear_thread_private_info (struct thread_info *thread)
5528 {
5529 if (thread->priv != NULL)
5530 {
5531 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5532 thread->priv->watch_data_address = 0;
5533 }
5534 }
5535
5536 /* Append a vCont continue-with-signal action for threads that have a
5537 non-zero stop signal. */
5538
5539 static char *
5540 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5541 {
5542 struct thread_info *thread;
5543
5544 ALL_NON_EXITED_THREADS (thread)
5545 if (ptid_match (thread->ptid, ptid)
5546 && !ptid_equal (inferior_ptid, thread->ptid)
5547 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5548 {
5549 p = append_resumption (p, endp, thread->ptid,
5550 0, thread->suspend.stop_signal);
5551 thread->suspend.stop_signal = GDB_SIGNAL_0;
5552 resume_clear_thread_private_info (thread);
5553 }
5554
5555 return p;
5556 }
5557
5558 /* Resume the remote inferior by using a "vCont" packet. The thread
5559 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5560 resumed thread should be single-stepped and/or signalled. If PTID
5561 equals minus_one_ptid, then all threads are resumed; the thread to
5562 be stepped and/or signalled is given in the global INFERIOR_PTID.
5563 This function returns non-zero iff it resumes the inferior.
5564
5565 This function issues a strict subset of all possible vCont commands at the
5566 moment. */
5567
5568 static int
5569 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5570 {
5571 struct remote_state *rs = get_remote_state ();
5572 char *p;
5573 char *endp;
5574
5575 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5576 remote_vcont_probe (rs);
5577
5578 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5579 return 0;
5580
5581 p = rs->buf;
5582 endp = rs->buf + get_remote_packet_size ();
5583
5584 /* If we could generate a wider range of packets, we'd have to worry
5585 about overflowing BUF. Should there be a generic
5586 "multi-part-packet" packet? */
5587
5588 p += xsnprintf (p, endp - p, "vCont");
5589
5590 if (ptid_equal (ptid, magic_null_ptid))
5591 {
5592 /* MAGIC_NULL_PTID means that we don't have any active threads,
5593 so we don't have any TID numbers the inferior will
5594 understand. Make sure to only send forms that do not specify
5595 a TID. */
5596 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5597 }
5598 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5599 {
5600 /* Resume all threads (of all processes, or of a single
5601 process), with preference for INFERIOR_PTID. This assumes
5602 inferior_ptid belongs to the set of all threads we are about
5603 to resume. */
5604 if (step || siggnal != GDB_SIGNAL_0)
5605 {
5606 /* Step inferior_ptid, with or without signal. */
5607 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5608 }
5609
5610 /* Also pass down any pending signaled resumption for other
5611 threads not the current. */
5612 p = append_pending_thread_resumptions (p, endp, ptid);
5613
5614 /* And continue others without a signal. */
5615 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5616 }
5617 else
5618 {
5619 /* Scheduler locking; resume only PTID. */
5620 append_resumption (p, endp, ptid, step, siggnal);
5621 }
5622
5623 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5624 putpkt (rs->buf);
5625
5626 if (target_is_non_stop_p ())
5627 {
5628 /* In non-stop, the stub replies to vCont with "OK". The stop
5629 reply will be reported asynchronously by means of a `%Stop'
5630 notification. */
5631 getpkt (&rs->buf, &rs->buf_size, 0);
5632 if (strcmp (rs->buf, "OK") != 0)
5633 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5634 }
5635
5636 return 1;
5637 }
5638
5639 /* Tell the remote machine to resume. */
5640
5641 static void
5642 remote_resume (struct target_ops *ops,
5643 ptid_t ptid, int step, enum gdb_signal siggnal)
5644 {
5645 struct remote_state *rs = get_remote_state ();
5646 char *buf;
5647 struct thread_info *thread;
5648
5649 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5650 (explained in remote-notif.c:handle_notification) so
5651 remote_notif_process is not called. We need find a place where
5652 it is safe to start a 'vNotif' sequence. It is good to do it
5653 before resuming inferior, because inferior was stopped and no RSP
5654 traffic at that moment. */
5655 if (!target_is_non_stop_p ())
5656 remote_notif_process (rs->notif_state, &notif_client_stop);
5657
5658 rs->last_sent_signal = siggnal;
5659 rs->last_sent_step = step;
5660
5661 rs->last_resume_exec_dir = execution_direction;
5662
5663 /* The vCont packet doesn't need to specify threads via Hc. */
5664 /* No reverse support (yet) for vCont. */
5665 if (execution_direction != EXEC_REVERSE)
5666 if (remote_vcont_resume (ptid, step, siggnal))
5667 goto done;
5668
5669 /* All other supported resume packets do use Hc, so set the continue
5670 thread. */
5671 if (ptid_equal (ptid, minus_one_ptid))
5672 set_continue_thread (any_thread_ptid);
5673 else
5674 set_continue_thread (ptid);
5675
5676 ALL_NON_EXITED_THREADS (thread)
5677 resume_clear_thread_private_info (thread);
5678
5679 buf = rs->buf;
5680 if (execution_direction == EXEC_REVERSE)
5681 {
5682 /* We don't pass signals to the target in reverse exec mode. */
5683 if (info_verbose && siggnal != GDB_SIGNAL_0)
5684 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5685 siggnal);
5686
5687 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5688 error (_("Remote reverse-step not supported."));
5689 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5690 error (_("Remote reverse-continue not supported."));
5691
5692 strcpy (buf, step ? "bs" : "bc");
5693 }
5694 else if (siggnal != GDB_SIGNAL_0)
5695 {
5696 buf[0] = step ? 'S' : 'C';
5697 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5698 buf[2] = tohex (((int) siggnal) & 0xf);
5699 buf[3] = '\0';
5700 }
5701 else
5702 strcpy (buf, step ? "s" : "c");
5703
5704 putpkt (buf);
5705
5706 done:
5707 /* We are about to start executing the inferior, let's register it
5708 with the event loop. NOTE: this is the one place where all the
5709 execution commands end up. We could alternatively do this in each
5710 of the execution commands in infcmd.c. */
5711 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5712 into infcmd.c in order to allow inferior function calls to work
5713 NOT asynchronously. */
5714 if (target_can_async_p ())
5715 target_async (1);
5716
5717 /* We've just told the target to resume. The remote server will
5718 wait for the inferior to stop, and then send a stop reply. In
5719 the mean time, we can't start another command/query ourselves
5720 because the stub wouldn't be ready to process it. This applies
5721 only to the base all-stop protocol, however. In non-stop (which
5722 only supports vCont), the stub replies with an "OK", and is
5723 immediate able to process further serial input. */
5724 if (!target_is_non_stop_p ())
5725 rs->waiting_for_stop_reply = 1;
5726 }
5727 \f
5728
5729 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5730 thread, all threads of a remote process, or all threads of all
5731 processes. */
5732
5733 static void
5734 remote_stop_ns (ptid_t ptid)
5735 {
5736 struct remote_state *rs = get_remote_state ();
5737 char *p = rs->buf;
5738 char *endp = rs->buf + get_remote_packet_size ();
5739
5740 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5741 remote_vcont_probe (rs);
5742
5743 if (!rs->supports_vCont.t)
5744 error (_("Remote server does not support stopping threads"));
5745
5746 if (ptid_equal (ptid, minus_one_ptid)
5747 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5748 p += xsnprintf (p, endp - p, "vCont;t");
5749 else
5750 {
5751 ptid_t nptid;
5752
5753 p += xsnprintf (p, endp - p, "vCont;t:");
5754
5755 if (ptid_is_pid (ptid))
5756 /* All (-1) threads of process. */
5757 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5758 else
5759 {
5760 /* Small optimization: if we already have a stop reply for
5761 this thread, no use in telling the stub we want this
5762 stopped. */
5763 if (peek_stop_reply (ptid))
5764 return;
5765
5766 nptid = ptid;
5767 }
5768
5769 write_ptid (p, endp, nptid);
5770 }
5771
5772 /* In non-stop, we get an immediate OK reply. The stop reply will
5773 come in asynchronously by notification. */
5774 putpkt (rs->buf);
5775 getpkt (&rs->buf, &rs->buf_size, 0);
5776 if (strcmp (rs->buf, "OK") != 0)
5777 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5778 }
5779
5780 /* All-stop version of target_interrupt. Sends a break or a ^C to
5781 interrupt the remote target. It is undefined which thread of which
5782 process reports the interrupt. */
5783
5784 static void
5785 remote_interrupt_as (void)
5786 {
5787 struct remote_state *rs = get_remote_state ();
5788
5789 rs->ctrlc_pending_p = 1;
5790
5791 /* If the inferior is stopped already, but the core didn't know
5792 about it yet, just ignore the request. The cached wait status
5793 will be collected in remote_wait. */
5794 if (rs->cached_wait_status)
5795 return;
5796
5797 /* Send interrupt_sequence to remote target. */
5798 send_interrupt_sequence ();
5799 }
5800
5801 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5802 the remote target. It is undefined which thread of which process
5803 reports the interrupt. Throws an error if the packet is not
5804 supported by the server. */
5805
5806 static void
5807 remote_interrupt_ns (void)
5808 {
5809 struct remote_state *rs = get_remote_state ();
5810 char *p = rs->buf;
5811 char *endp = rs->buf + get_remote_packet_size ();
5812
5813 xsnprintf (p, endp - p, "vCtrlC");
5814
5815 /* In non-stop, we get an immediate OK reply. The stop reply will
5816 come in asynchronously by notification. */
5817 putpkt (rs->buf);
5818 getpkt (&rs->buf, &rs->buf_size, 0);
5819
5820 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5821 {
5822 case PACKET_OK:
5823 break;
5824 case PACKET_UNKNOWN:
5825 error (_("No support for interrupting the remote target."));
5826 case PACKET_ERROR:
5827 error (_("Interrupting target failed: %s"), rs->buf);
5828 }
5829 }
5830
5831 /* Implement the to_stop function for the remote targets. */
5832
5833 static void
5834 remote_stop (struct target_ops *self, ptid_t ptid)
5835 {
5836 if (remote_debug)
5837 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5838
5839 if (target_is_non_stop_p ())
5840 remote_stop_ns (ptid);
5841 else
5842 {
5843 /* We don't currently have a way to transparently pause the
5844 remote target in all-stop mode. Interrupt it instead. */
5845 remote_interrupt_as ();
5846 }
5847 }
5848
5849 /* Implement the to_interrupt function for the remote targets. */
5850
5851 static void
5852 remote_interrupt (struct target_ops *self, ptid_t ptid)
5853 {
5854 struct remote_state *rs = get_remote_state ();
5855
5856 if (remote_debug)
5857 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5858
5859 if (target_is_non_stop_p ())
5860 remote_interrupt_ns ();
5861 else
5862 remote_interrupt_as ();
5863 }
5864
5865 /* Implement the to_pass_ctrlc function for the remote targets. */
5866
5867 static void
5868 remote_pass_ctrlc (struct target_ops *self)
5869 {
5870 struct remote_state *rs = get_remote_state ();
5871
5872 if (remote_debug)
5873 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
5874
5875 /* If we're starting up, we're not fully synced yet. Quit
5876 immediately. */
5877 if (rs->starting_up)
5878 quit ();
5879 /* If ^C has already been sent once, offer to disconnect. */
5880 else if (rs->ctrlc_pending_p)
5881 interrupt_query ();
5882 else
5883 target_interrupt (inferior_ptid);
5884 }
5885
5886 /* Ask the user what to do when an interrupt is received. */
5887
5888 static void
5889 interrupt_query (void)
5890 {
5891 struct remote_state *rs = get_remote_state ();
5892
5893 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5894 {
5895 if (query (_("The target is not responding to interrupt requests.\n"
5896 "Stop debugging it? ")))
5897 {
5898 remote_unpush_target ();
5899 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5900 }
5901 }
5902 else
5903 {
5904 if (query (_("Interrupted while waiting for the program.\n"
5905 "Give up waiting? ")))
5906 quit ();
5907 }
5908 }
5909
5910 /* Enable/disable target terminal ownership. Most targets can use
5911 terminal groups to control terminal ownership. Remote targets are
5912 different in that explicit transfer of ownership to/from GDB/target
5913 is required. */
5914
5915 static void
5916 remote_terminal_inferior (struct target_ops *self)
5917 {
5918 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5919 idempotent. The event-loop GDB talking to an asynchronous target
5920 with a synchronous command calls this function from both
5921 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5922 transfer the terminal to the target when it shouldn't this guard
5923 can go away. */
5924 if (!remote_async_terminal_ours_p)
5925 return;
5926 remote_async_terminal_ours_p = 0;
5927 /* NOTE: At this point we could also register our selves as the
5928 recipient of all input. Any characters typed could then be
5929 passed on down to the target. */
5930 }
5931
5932 static void
5933 remote_terminal_ours (struct target_ops *self)
5934 {
5935 /* See FIXME in remote_terminal_inferior. */
5936 if (remote_async_terminal_ours_p)
5937 return;
5938 remote_async_terminal_ours_p = 1;
5939 }
5940
5941 static void
5942 remote_console_output (char *msg)
5943 {
5944 char *p;
5945
5946 for (p = msg; p[0] && p[1]; p += 2)
5947 {
5948 char tb[2];
5949 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5950
5951 tb[0] = c;
5952 tb[1] = 0;
5953 fputs_unfiltered (tb, gdb_stdtarg);
5954 }
5955 gdb_flush (gdb_stdtarg);
5956 }
5957
5958 typedef struct cached_reg
5959 {
5960 int num;
5961 gdb_byte data[MAX_REGISTER_SIZE];
5962 } cached_reg_t;
5963
5964 DEF_VEC_O(cached_reg_t);
5965
5966 typedef struct stop_reply
5967 {
5968 struct notif_event base;
5969
5970 /* The identifier of the thread about this event */
5971 ptid_t ptid;
5972
5973 /* The remote state this event is associated with. When the remote
5974 connection, represented by a remote_state object, is closed,
5975 all the associated stop_reply events should be released. */
5976 struct remote_state *rs;
5977
5978 struct target_waitstatus ws;
5979
5980 /* Expedited registers. This makes remote debugging a bit more
5981 efficient for those targets that provide critical registers as
5982 part of their normal status mechanism (as another roundtrip to
5983 fetch them is avoided). */
5984 VEC(cached_reg_t) *regcache;
5985
5986 enum target_stop_reason stop_reason;
5987
5988 CORE_ADDR watch_data_address;
5989
5990 int core;
5991 } *stop_reply_p;
5992
5993 DECLARE_QUEUE_P (stop_reply_p);
5994 DEFINE_QUEUE_P (stop_reply_p);
5995 /* The list of already fetched and acknowledged stop events. This
5996 queue is used for notification Stop, and other notifications
5997 don't need queue for their events, because the notification events
5998 of Stop can't be consumed immediately, so that events should be
5999 queued first, and be consumed by remote_wait_{ns,as} one per
6000 time. Other notifications can consume their events immediately,
6001 so queue is not needed for them. */
6002 static QUEUE (stop_reply_p) *stop_reply_queue;
6003
6004 static void
6005 stop_reply_xfree (struct stop_reply *r)
6006 {
6007 notif_event_xfree ((struct notif_event *) r);
6008 }
6009
6010 /* Return the length of the stop reply queue. */
6011
6012 static int
6013 stop_reply_queue_length (void)
6014 {
6015 return QUEUE_length (stop_reply_p, stop_reply_queue);
6016 }
6017
6018 static void
6019 remote_notif_stop_parse (struct notif_client *self, char *buf,
6020 struct notif_event *event)
6021 {
6022 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6023 }
6024
6025 static void
6026 remote_notif_stop_ack (struct notif_client *self, char *buf,
6027 struct notif_event *event)
6028 {
6029 struct stop_reply *stop_reply = (struct stop_reply *) event;
6030
6031 /* acknowledge */
6032 putpkt ((char *) self->ack_command);
6033
6034 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6035 /* We got an unknown stop reply. */
6036 error (_("Unknown stop reply"));
6037
6038 push_stop_reply (stop_reply);
6039 }
6040
6041 static int
6042 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6043 {
6044 /* We can't get pending events in remote_notif_process for
6045 notification stop, and we have to do this in remote_wait_ns
6046 instead. If we fetch all queued events from stub, remote stub
6047 may exit and we have no chance to process them back in
6048 remote_wait_ns. */
6049 mark_async_event_handler (remote_async_inferior_event_token);
6050 return 0;
6051 }
6052
6053 static void
6054 stop_reply_dtr (struct notif_event *event)
6055 {
6056 struct stop_reply *r = (struct stop_reply *) event;
6057
6058 VEC_free (cached_reg_t, r->regcache);
6059 }
6060
6061 static struct notif_event *
6062 remote_notif_stop_alloc_reply (void)
6063 {
6064 /* We cast to a pointer to the "base class". */
6065 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6066
6067 r->dtr = stop_reply_dtr;
6068
6069 return r;
6070 }
6071
6072 /* A client of notification Stop. */
6073
6074 struct notif_client notif_client_stop =
6075 {
6076 "Stop",
6077 "vStopped",
6078 remote_notif_stop_parse,
6079 remote_notif_stop_ack,
6080 remote_notif_stop_can_get_pending_events,
6081 remote_notif_stop_alloc_reply,
6082 REMOTE_NOTIF_STOP,
6083 };
6084
6085 /* A parameter to pass data in and out. */
6086
6087 struct queue_iter_param
6088 {
6089 void *input;
6090 struct stop_reply *output;
6091 };
6092
6093 /* Determine if THREAD is a pending fork parent thread. ARG contains
6094 the pid of the process that owns the threads we want to check, or
6095 -1 if we want to check all threads. */
6096
6097 static int
6098 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6099 ptid_t thread_ptid)
6100 {
6101 if (ws->kind == TARGET_WAITKIND_FORKED
6102 || ws->kind == TARGET_WAITKIND_VFORKED)
6103 {
6104 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6105 return 1;
6106 }
6107
6108 return 0;
6109 }
6110
6111 /* Check whether EVENT is a fork event, and if it is, remove the
6112 fork child from the context list passed in DATA. */
6113
6114 static int
6115 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6116 QUEUE_ITER (stop_reply_p) *iter,
6117 stop_reply_p event,
6118 void *data)
6119 {
6120 struct queue_iter_param *param = (struct queue_iter_param *) data;
6121 struct threads_listing_context *context
6122 = (struct threads_listing_context *) param->input;
6123
6124 if (event->ws.kind == TARGET_WAITKIND_FORKED
6125 || event->ws.kind == TARGET_WAITKIND_VFORKED
6126 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6127 threads_listing_context_remove (&event->ws, context);
6128
6129 return 1;
6130 }
6131
6132 /* If CONTEXT contains any fork child threads that have not been
6133 reported yet, remove them from the CONTEXT list. If such a
6134 thread exists it is because we are stopped at a fork catchpoint
6135 and have not yet called follow_fork, which will set up the
6136 host-side data structures for the new process. */
6137
6138 static void
6139 remove_new_fork_children (struct threads_listing_context *context)
6140 {
6141 struct thread_info * thread;
6142 int pid = -1;
6143 struct notif_client *notif = &notif_client_stop;
6144 struct queue_iter_param param;
6145
6146 /* For any threads stopped at a fork event, remove the corresponding
6147 fork child threads from the CONTEXT list. */
6148 ALL_NON_EXITED_THREADS (thread)
6149 {
6150 struct target_waitstatus *ws;
6151
6152 if (thread->suspend.waitstatus_pending_p)
6153 ws = &thread->suspend.waitstatus;
6154 else
6155 ws = &thread->pending_follow;
6156
6157 if (is_pending_fork_parent (ws, pid, thread->ptid))
6158 {
6159 threads_listing_context_remove (ws, context);
6160 }
6161 }
6162
6163 /* Check for any pending fork events (not reported or processed yet)
6164 in process PID and remove those fork child threads from the
6165 CONTEXT list as well. */
6166 remote_notif_get_pending_events (notif);
6167 param.input = context;
6168 param.output = NULL;
6169 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6170 remove_child_of_pending_fork, &param);
6171 }
6172
6173 /* Remove stop replies in the queue if its pid is equal to the given
6174 inferior's pid. */
6175
6176 static int
6177 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6178 QUEUE_ITER (stop_reply_p) *iter,
6179 stop_reply_p event,
6180 void *data)
6181 {
6182 struct queue_iter_param *param = (struct queue_iter_param *) data;
6183 struct inferior *inf = (struct inferior *) param->input;
6184
6185 if (ptid_get_pid (event->ptid) == inf->pid)
6186 {
6187 stop_reply_xfree (event);
6188 QUEUE_remove_elem (stop_reply_p, q, iter);
6189 }
6190
6191 return 1;
6192 }
6193
6194 /* Discard all pending stop replies of inferior INF. */
6195
6196 static void
6197 discard_pending_stop_replies (struct inferior *inf)
6198 {
6199 struct queue_iter_param param;
6200 struct stop_reply *reply;
6201 struct remote_state *rs = get_remote_state ();
6202 struct remote_notif_state *rns = rs->notif_state;
6203
6204 /* This function can be notified when an inferior exists. When the
6205 target is not remote, the notification state is NULL. */
6206 if (rs->remote_desc == NULL)
6207 return;
6208
6209 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6210
6211 /* Discard the in-flight notification. */
6212 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6213 {
6214 stop_reply_xfree (reply);
6215 rns->pending_event[notif_client_stop.id] = NULL;
6216 }
6217
6218 param.input = inf;
6219 param.output = NULL;
6220 /* Discard the stop replies we have already pulled with
6221 vStopped. */
6222 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6223 remove_stop_reply_for_inferior, &param);
6224 }
6225
6226 /* If its remote state is equal to the given remote state,
6227 remove EVENT from the stop reply queue. */
6228
6229 static int
6230 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6231 QUEUE_ITER (stop_reply_p) *iter,
6232 stop_reply_p event,
6233 void *data)
6234 {
6235 struct queue_iter_param *param = (struct queue_iter_param *) data;
6236 struct remote_state *rs = (struct remote_state *) param->input;
6237
6238 if (event->rs == rs)
6239 {
6240 stop_reply_xfree (event);
6241 QUEUE_remove_elem (stop_reply_p, q, iter);
6242 }
6243
6244 return 1;
6245 }
6246
6247 /* Discard the stop replies for RS in stop_reply_queue. */
6248
6249 static void
6250 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6251 {
6252 struct queue_iter_param param;
6253
6254 param.input = rs;
6255 param.output = NULL;
6256 /* Discard the stop replies we have already pulled with
6257 vStopped. */
6258 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6259 remove_stop_reply_of_remote_state, &param);
6260 }
6261
6262 /* A parameter to pass data in and out. */
6263
6264 static int
6265 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6266 QUEUE_ITER (stop_reply_p) *iter,
6267 stop_reply_p event,
6268 void *data)
6269 {
6270 struct queue_iter_param *param = (struct queue_iter_param *) data;
6271 ptid_t *ptid = (ptid_t *) param->input;
6272
6273 if (ptid_match (event->ptid, *ptid))
6274 {
6275 param->output = event;
6276 QUEUE_remove_elem (stop_reply_p, q, iter);
6277 return 0;
6278 }
6279
6280 return 1;
6281 }
6282
6283 /* Remove the first reply in 'stop_reply_queue' which matches
6284 PTID. */
6285
6286 static struct stop_reply *
6287 remote_notif_remove_queued_reply (ptid_t ptid)
6288 {
6289 struct queue_iter_param param;
6290
6291 param.input = &ptid;
6292 param.output = NULL;
6293
6294 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6295 remote_notif_remove_once_on_match, &param);
6296 if (notif_debug)
6297 fprintf_unfiltered (gdb_stdlog,
6298 "notif: discard queued event: 'Stop' in %s\n",
6299 target_pid_to_str (ptid));
6300
6301 return param.output;
6302 }
6303
6304 /* Look for a queued stop reply belonging to PTID. If one is found,
6305 remove it from the queue, and return it. Returns NULL if none is
6306 found. If there are still queued events left to process, tell the
6307 event loop to get back to target_wait soon. */
6308
6309 static struct stop_reply *
6310 queued_stop_reply (ptid_t ptid)
6311 {
6312 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6313
6314 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6315 /* There's still at least an event left. */
6316 mark_async_event_handler (remote_async_inferior_event_token);
6317
6318 return r;
6319 }
6320
6321 /* Push a fully parsed stop reply in the stop reply queue. Since we
6322 know that we now have at least one queued event left to pass to the
6323 core side, tell the event loop to get back to target_wait soon. */
6324
6325 static void
6326 push_stop_reply (struct stop_reply *new_event)
6327 {
6328 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6329
6330 if (notif_debug)
6331 fprintf_unfiltered (gdb_stdlog,
6332 "notif: push 'Stop' %s to queue %d\n",
6333 target_pid_to_str (new_event->ptid),
6334 QUEUE_length (stop_reply_p,
6335 stop_reply_queue));
6336
6337 mark_async_event_handler (remote_async_inferior_event_token);
6338 }
6339
6340 static int
6341 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6342 QUEUE_ITER (stop_reply_p) *iter,
6343 struct stop_reply *event,
6344 void *data)
6345 {
6346 ptid_t *ptid = (ptid_t *) data;
6347
6348 return !(ptid_equal (*ptid, event->ptid)
6349 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6350 }
6351
6352 /* Returns true if we have a stop reply for PTID. */
6353
6354 static int
6355 peek_stop_reply (ptid_t ptid)
6356 {
6357 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6358 stop_reply_match_ptid_and_ws, &ptid);
6359 }
6360
6361 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6362 starting with P and ending with PEND matches PREFIX. */
6363
6364 static int
6365 strprefix (const char *p, const char *pend, const char *prefix)
6366 {
6367 for ( ; p < pend; p++, prefix++)
6368 if (*p != *prefix)
6369 return 0;
6370 return *prefix == '\0';
6371 }
6372
6373 /* Parse the stop reply in BUF. Either the function succeeds, and the
6374 result is stored in EVENT, or throws an error. */
6375
6376 static void
6377 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6378 {
6379 struct remote_arch_state *rsa = get_remote_arch_state ();
6380 ULONGEST addr;
6381 char *p;
6382 int skipregs = 0;
6383
6384 event->ptid = null_ptid;
6385 event->rs = get_remote_state ();
6386 event->ws.kind = TARGET_WAITKIND_IGNORE;
6387 event->ws.value.integer = 0;
6388 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6389 event->regcache = NULL;
6390 event->core = -1;
6391
6392 switch (buf[0])
6393 {
6394 case 'T': /* Status with PC, SP, FP, ... */
6395 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6396 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6397 ss = signal number
6398 n... = register number
6399 r... = register contents
6400 */
6401
6402 p = &buf[3]; /* after Txx */
6403 while (*p)
6404 {
6405 char *p1;
6406 int fieldsize;
6407
6408 p1 = strchr (p, ':');
6409 if (p1 == NULL)
6410 error (_("Malformed packet(a) (missing colon): %s\n\
6411 Packet: '%s'\n"),
6412 p, buf);
6413 if (p == p1)
6414 error (_("Malformed packet(a) (missing register number): %s\n\
6415 Packet: '%s'\n"),
6416 p, buf);
6417
6418 /* Some "registers" are actually extended stop information.
6419 Note if you're adding a new entry here: GDB 7.9 and
6420 earlier assume that all register "numbers" that start
6421 with an hex digit are real register numbers. Make sure
6422 the server only sends such a packet if it knows the
6423 client understands it. */
6424
6425 if (strprefix (p, p1, "thread"))
6426 event->ptid = read_ptid (++p1, &p);
6427 else if (strprefix (p, p1, "syscall_entry"))
6428 {
6429 ULONGEST sysno;
6430
6431 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6432 p = unpack_varlen_hex (++p1, &sysno);
6433 event->ws.value.syscall_number = (int) sysno;
6434 }
6435 else if (strprefix (p, p1, "syscall_return"))
6436 {
6437 ULONGEST sysno;
6438
6439 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6440 p = unpack_varlen_hex (++p1, &sysno);
6441 event->ws.value.syscall_number = (int) sysno;
6442 }
6443 else if (strprefix (p, p1, "watch")
6444 || strprefix (p, p1, "rwatch")
6445 || strprefix (p, p1, "awatch"))
6446 {
6447 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6448 p = unpack_varlen_hex (++p1, &addr);
6449 event->watch_data_address = (CORE_ADDR) addr;
6450 }
6451 else if (strprefix (p, p1, "swbreak"))
6452 {
6453 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6454
6455 /* Make sure the stub doesn't forget to indicate support
6456 with qSupported. */
6457 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6458 error (_("Unexpected swbreak stop reason"));
6459
6460 /* The value part is documented as "must be empty",
6461 though we ignore it, in case we ever decide to make
6462 use of it in a backward compatible way. */
6463 p = strchrnul (p1 + 1, ';');
6464 }
6465 else if (strprefix (p, p1, "hwbreak"))
6466 {
6467 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6468
6469 /* Make sure the stub doesn't forget to indicate support
6470 with qSupported. */
6471 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6472 error (_("Unexpected hwbreak stop reason"));
6473
6474 /* See above. */
6475 p = strchrnul (p1 + 1, ';');
6476 }
6477 else if (strprefix (p, p1, "library"))
6478 {
6479 event->ws.kind = TARGET_WAITKIND_LOADED;
6480 p = strchrnul (p1 + 1, ';');
6481 }
6482 else if (strprefix (p, p1, "replaylog"))
6483 {
6484 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6485 /* p1 will indicate "begin" or "end", but it makes
6486 no difference for now, so ignore it. */
6487 p = strchrnul (p1 + 1, ';');
6488 }
6489 else if (strprefix (p, p1, "core"))
6490 {
6491 ULONGEST c;
6492
6493 p = unpack_varlen_hex (++p1, &c);
6494 event->core = c;
6495 }
6496 else if (strprefix (p, p1, "fork"))
6497 {
6498 event->ws.value.related_pid = read_ptid (++p1, &p);
6499 event->ws.kind = TARGET_WAITKIND_FORKED;
6500 }
6501 else if (strprefix (p, p1, "vfork"))
6502 {
6503 event->ws.value.related_pid = read_ptid (++p1, &p);
6504 event->ws.kind = TARGET_WAITKIND_VFORKED;
6505 }
6506 else if (strprefix (p, p1, "vforkdone"))
6507 {
6508 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6509 p = strchrnul (p1 + 1, ';');
6510 }
6511 else if (strprefix (p, p1, "exec"))
6512 {
6513 ULONGEST ignored;
6514 char pathname[PATH_MAX];
6515 int pathlen;
6516
6517 /* Determine the length of the execd pathname. */
6518 p = unpack_varlen_hex (++p1, &ignored);
6519 pathlen = (p - p1) / 2;
6520
6521 /* Save the pathname for event reporting and for
6522 the next run command. */
6523 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6524 pathname[pathlen] = '\0';
6525
6526 /* This is freed during event handling. */
6527 event->ws.value.execd_pathname = xstrdup (pathname);
6528 event->ws.kind = TARGET_WAITKIND_EXECD;
6529
6530 /* Skip the registers included in this packet, since
6531 they may be for an architecture different from the
6532 one used by the original program. */
6533 skipregs = 1;
6534 }
6535 else if (strprefix (p, p1, "create"))
6536 {
6537 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6538 p = strchrnul (p1 + 1, ';');
6539 }
6540 else
6541 {
6542 ULONGEST pnum;
6543 char *p_temp;
6544
6545 if (skipregs)
6546 {
6547 p = strchrnul (p1 + 1, ';');
6548 p++;
6549 continue;
6550 }
6551
6552 /* Maybe a real ``P'' register number. */
6553 p_temp = unpack_varlen_hex (p, &pnum);
6554 /* If the first invalid character is the colon, we got a
6555 register number. Otherwise, it's an unknown stop
6556 reason. */
6557 if (p_temp == p1)
6558 {
6559 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6560 cached_reg_t cached_reg;
6561
6562 if (reg == NULL)
6563 error (_("Remote sent bad register number %s: %s\n\
6564 Packet: '%s'\n"),
6565 hex_string (pnum), p, buf);
6566
6567 cached_reg.num = reg->regnum;
6568
6569 p = p1 + 1;
6570 fieldsize = hex2bin (p, cached_reg.data,
6571 register_size (target_gdbarch (),
6572 reg->regnum));
6573 p += 2 * fieldsize;
6574 if (fieldsize < register_size (target_gdbarch (),
6575 reg->regnum))
6576 warning (_("Remote reply is too short: %s"), buf);
6577
6578 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6579 }
6580 else
6581 {
6582 /* Not a number. Silently skip unknown optional
6583 info. */
6584 p = strchrnul (p1 + 1, ';');
6585 }
6586 }
6587
6588 if (*p != ';')
6589 error (_("Remote register badly formatted: %s\nhere: %s"),
6590 buf, p);
6591 ++p;
6592 }
6593
6594 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6595 break;
6596
6597 /* fall through */
6598 case 'S': /* Old style status, just signal only. */
6599 {
6600 int sig;
6601
6602 event->ws.kind = TARGET_WAITKIND_STOPPED;
6603 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6604 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6605 event->ws.value.sig = (enum gdb_signal) sig;
6606 else
6607 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6608 }
6609 break;
6610 case 'w': /* Thread exited. */
6611 {
6612 char *p;
6613 ULONGEST value;
6614
6615 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6616 p = unpack_varlen_hex (&buf[1], &value);
6617 event->ws.value.integer = value;
6618 if (*p != ';')
6619 error (_("stop reply packet badly formatted: %s"), buf);
6620 event->ptid = read_ptid (++p, NULL);
6621 break;
6622 }
6623 case 'W': /* Target exited. */
6624 case 'X':
6625 {
6626 char *p;
6627 int pid;
6628 ULONGEST value;
6629
6630 /* GDB used to accept only 2 hex chars here. Stubs should
6631 only send more if they detect GDB supports multi-process
6632 support. */
6633 p = unpack_varlen_hex (&buf[1], &value);
6634
6635 if (buf[0] == 'W')
6636 {
6637 /* The remote process exited. */
6638 event->ws.kind = TARGET_WAITKIND_EXITED;
6639 event->ws.value.integer = value;
6640 }
6641 else
6642 {
6643 /* The remote process exited with a signal. */
6644 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6645 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6646 event->ws.value.sig = (enum gdb_signal) value;
6647 else
6648 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6649 }
6650
6651 /* If no process is specified, assume inferior_ptid. */
6652 pid = ptid_get_pid (inferior_ptid);
6653 if (*p == '\0')
6654 ;
6655 else if (*p == ';')
6656 {
6657 p++;
6658
6659 if (*p == '\0')
6660 ;
6661 else if (startswith (p, "process:"))
6662 {
6663 ULONGEST upid;
6664
6665 p += sizeof ("process:") - 1;
6666 unpack_varlen_hex (p, &upid);
6667 pid = upid;
6668 }
6669 else
6670 error (_("unknown stop reply packet: %s"), buf);
6671 }
6672 else
6673 error (_("unknown stop reply packet: %s"), buf);
6674 event->ptid = pid_to_ptid (pid);
6675 }
6676 break;
6677 case 'N':
6678 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6679 event->ptid = minus_one_ptid;
6680 break;
6681 }
6682
6683 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6684 error (_("No process or thread specified in stop reply: %s"), buf);
6685 }
6686
6687 /* When the stub wants to tell GDB about a new notification reply, it
6688 sends a notification (%Stop, for example). Those can come it at
6689 any time, hence, we have to make sure that any pending
6690 putpkt/getpkt sequence we're making is finished, before querying
6691 the stub for more events with the corresponding ack command
6692 (vStopped, for example). E.g., if we started a vStopped sequence
6693 immediately upon receiving the notification, something like this
6694 could happen:
6695
6696 1.1) --> Hg 1
6697 1.2) <-- OK
6698 1.3) --> g
6699 1.4) <-- %Stop
6700 1.5) --> vStopped
6701 1.6) <-- (registers reply to step #1.3)
6702
6703 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6704 query.
6705
6706 To solve this, whenever we parse a %Stop notification successfully,
6707 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6708 doing whatever we were doing:
6709
6710 2.1) --> Hg 1
6711 2.2) <-- OK
6712 2.3) --> g
6713 2.4) <-- %Stop
6714 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6715 2.5) <-- (registers reply to step #2.3)
6716
6717 Eventualy after step #2.5, we return to the event loop, which
6718 notices there's an event on the
6719 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6720 associated callback --- the function below. At this point, we're
6721 always safe to start a vStopped sequence. :
6722
6723 2.6) --> vStopped
6724 2.7) <-- T05 thread:2
6725 2.8) --> vStopped
6726 2.9) --> OK
6727 */
6728
6729 void
6730 remote_notif_get_pending_events (struct notif_client *nc)
6731 {
6732 struct remote_state *rs = get_remote_state ();
6733
6734 if (rs->notif_state->pending_event[nc->id] != NULL)
6735 {
6736 if (notif_debug)
6737 fprintf_unfiltered (gdb_stdlog,
6738 "notif: process: '%s' ack pending event\n",
6739 nc->name);
6740
6741 /* acknowledge */
6742 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6743 rs->notif_state->pending_event[nc->id] = NULL;
6744
6745 while (1)
6746 {
6747 getpkt (&rs->buf, &rs->buf_size, 0);
6748 if (strcmp (rs->buf, "OK") == 0)
6749 break;
6750 else
6751 remote_notif_ack (nc, rs->buf);
6752 }
6753 }
6754 else
6755 {
6756 if (notif_debug)
6757 fprintf_unfiltered (gdb_stdlog,
6758 "notif: process: '%s' no pending reply\n",
6759 nc->name);
6760 }
6761 }
6762
6763 /* Called when it is decided that STOP_REPLY holds the info of the
6764 event that is to be returned to the core. This function always
6765 destroys STOP_REPLY. */
6766
6767 static ptid_t
6768 process_stop_reply (struct stop_reply *stop_reply,
6769 struct target_waitstatus *status)
6770 {
6771 ptid_t ptid;
6772
6773 *status = stop_reply->ws;
6774 ptid = stop_reply->ptid;
6775
6776 /* If no thread/process was reported by the stub, assume the current
6777 inferior. */
6778 if (ptid_equal (ptid, null_ptid))
6779 ptid = inferior_ptid;
6780
6781 if (status->kind != TARGET_WAITKIND_EXITED
6782 && status->kind != TARGET_WAITKIND_SIGNALLED
6783 && status->kind != TARGET_WAITKIND_NO_RESUMED)
6784 {
6785 struct private_thread_info *remote_thr;
6786
6787 /* Expedited registers. */
6788 if (stop_reply->regcache)
6789 {
6790 struct regcache *regcache
6791 = get_thread_arch_regcache (ptid, target_gdbarch ());
6792 cached_reg_t *reg;
6793 int ix;
6794
6795 for (ix = 0;
6796 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6797 ix++)
6798 regcache_raw_supply (regcache, reg->num, reg->data);
6799 VEC_free (cached_reg_t, stop_reply->regcache);
6800 }
6801
6802 remote_notice_new_inferior (ptid, 0);
6803 remote_thr = demand_private_info (ptid);
6804 remote_thr->core = stop_reply->core;
6805 remote_thr->stop_reason = stop_reply->stop_reason;
6806 remote_thr->watch_data_address = stop_reply->watch_data_address;
6807 }
6808
6809 stop_reply_xfree (stop_reply);
6810 return ptid;
6811 }
6812
6813 /* The non-stop mode version of target_wait. */
6814
6815 static ptid_t
6816 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6817 {
6818 struct remote_state *rs = get_remote_state ();
6819 struct stop_reply *stop_reply;
6820 int ret;
6821 int is_notif = 0;
6822
6823 /* If in non-stop mode, get out of getpkt even if a
6824 notification is received. */
6825
6826 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6827 0 /* forever */, &is_notif);
6828 while (1)
6829 {
6830 if (ret != -1 && !is_notif)
6831 switch (rs->buf[0])
6832 {
6833 case 'E': /* Error of some sort. */
6834 /* We're out of sync with the target now. Did it continue
6835 or not? We can't tell which thread it was in non-stop,
6836 so just ignore this. */
6837 warning (_("Remote failure reply: %s"), rs->buf);
6838 break;
6839 case 'O': /* Console output. */
6840 remote_console_output (rs->buf + 1);
6841 break;
6842 default:
6843 warning (_("Invalid remote reply: %s"), rs->buf);
6844 break;
6845 }
6846
6847 /* Acknowledge a pending stop reply that may have arrived in the
6848 mean time. */
6849 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6850 remote_notif_get_pending_events (&notif_client_stop);
6851
6852 /* If indeed we noticed a stop reply, we're done. */
6853 stop_reply = queued_stop_reply (ptid);
6854 if (stop_reply != NULL)
6855 return process_stop_reply (stop_reply, status);
6856
6857 /* Still no event. If we're just polling for an event, then
6858 return to the event loop. */
6859 if (options & TARGET_WNOHANG)
6860 {
6861 status->kind = TARGET_WAITKIND_IGNORE;
6862 return minus_one_ptid;
6863 }
6864
6865 /* Otherwise do a blocking wait. */
6866 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6867 1 /* forever */, &is_notif);
6868 }
6869 }
6870
6871 /* Wait until the remote machine stops, then return, storing status in
6872 STATUS just as `wait' would. */
6873
6874 static ptid_t
6875 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6876 {
6877 struct remote_state *rs = get_remote_state ();
6878 ptid_t event_ptid = null_ptid;
6879 char *buf;
6880 struct stop_reply *stop_reply;
6881
6882 again:
6883
6884 status->kind = TARGET_WAITKIND_IGNORE;
6885 status->value.integer = 0;
6886
6887 stop_reply = queued_stop_reply (ptid);
6888 if (stop_reply != NULL)
6889 return process_stop_reply (stop_reply, status);
6890
6891 if (rs->cached_wait_status)
6892 /* Use the cached wait status, but only once. */
6893 rs->cached_wait_status = 0;
6894 else
6895 {
6896 int ret;
6897 int is_notif;
6898 int forever = ((options & TARGET_WNOHANG) == 0
6899 && wait_forever_enabled_p);
6900
6901 if (!rs->waiting_for_stop_reply)
6902 {
6903 status->kind = TARGET_WAITKIND_NO_RESUMED;
6904 return minus_one_ptid;
6905 }
6906
6907 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6908 _never_ wait for ever -> test on target_is_async_p().
6909 However, before we do that we need to ensure that the caller
6910 knows how to take the target into/out of async mode. */
6911 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6912 forever, &is_notif);
6913
6914 /* GDB gets a notification. Return to core as this event is
6915 not interesting. */
6916 if (ret != -1 && is_notif)
6917 return minus_one_ptid;
6918
6919 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6920 return minus_one_ptid;
6921 }
6922
6923 buf = rs->buf;
6924
6925 /* Assume that the target has acknowledged Ctrl-C unless we receive
6926 an 'F' or 'O' packet. */
6927 if (buf[0] != 'F' && buf[0] != 'O')
6928 rs->ctrlc_pending_p = 0;
6929
6930 switch (buf[0])
6931 {
6932 case 'E': /* Error of some sort. */
6933 /* We're out of sync with the target now. Did it continue or
6934 not? Not is more likely, so report a stop. */
6935 rs->waiting_for_stop_reply = 0;
6936
6937 warning (_("Remote failure reply: %s"), buf);
6938 status->kind = TARGET_WAITKIND_STOPPED;
6939 status->value.sig = GDB_SIGNAL_0;
6940 break;
6941 case 'F': /* File-I/O request. */
6942 /* GDB may access the inferior memory while handling the File-I/O
6943 request, but we don't want GDB accessing memory while waiting
6944 for a stop reply. See the comments in putpkt_binary. Set
6945 waiting_for_stop_reply to 0 temporarily. */
6946 rs->waiting_for_stop_reply = 0;
6947 remote_fileio_request (buf, rs->ctrlc_pending_p);
6948 rs->ctrlc_pending_p = 0;
6949 /* GDB handled the File-I/O request, and the target is running
6950 again. Keep waiting for events. */
6951 rs->waiting_for_stop_reply = 1;
6952 break;
6953 case 'N': case 'T': case 'S': case 'X': case 'W':
6954 {
6955 struct stop_reply *stop_reply;
6956
6957 /* There is a stop reply to handle. */
6958 rs->waiting_for_stop_reply = 0;
6959
6960 stop_reply
6961 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6962 rs->buf);
6963
6964 event_ptid = process_stop_reply (stop_reply, status);
6965 break;
6966 }
6967 case 'O': /* Console output. */
6968 remote_console_output (buf + 1);
6969 break;
6970 case '\0':
6971 if (rs->last_sent_signal != GDB_SIGNAL_0)
6972 {
6973 /* Zero length reply means that we tried 'S' or 'C' and the
6974 remote system doesn't support it. */
6975 target_terminal_ours_for_output ();
6976 printf_filtered
6977 ("Can't send signals to this remote system. %s not sent.\n",
6978 gdb_signal_to_name (rs->last_sent_signal));
6979 rs->last_sent_signal = GDB_SIGNAL_0;
6980 target_terminal_inferior ();
6981
6982 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6983 putpkt ((char *) buf);
6984 break;
6985 }
6986 /* else fallthrough */
6987 default:
6988 warning (_("Invalid remote reply: %s"), buf);
6989 break;
6990 }
6991
6992 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6993 return minus_one_ptid;
6994 else if (status->kind == TARGET_WAITKIND_IGNORE)
6995 {
6996 /* Nothing interesting happened. If we're doing a non-blocking
6997 poll, we're done. Otherwise, go back to waiting. */
6998 if (options & TARGET_WNOHANG)
6999 return minus_one_ptid;
7000 else
7001 goto again;
7002 }
7003 else if (status->kind != TARGET_WAITKIND_EXITED
7004 && status->kind != TARGET_WAITKIND_SIGNALLED)
7005 {
7006 if (!ptid_equal (event_ptid, null_ptid))
7007 record_currthread (rs, event_ptid);
7008 else
7009 event_ptid = inferior_ptid;
7010 }
7011 else
7012 /* A process exit. Invalidate our notion of current thread. */
7013 record_currthread (rs, minus_one_ptid);
7014
7015 return event_ptid;
7016 }
7017
7018 /* Wait until the remote machine stops, then return, storing status in
7019 STATUS just as `wait' would. */
7020
7021 static ptid_t
7022 remote_wait (struct target_ops *ops,
7023 ptid_t ptid, struct target_waitstatus *status, int options)
7024 {
7025 ptid_t event_ptid;
7026
7027 if (target_is_non_stop_p ())
7028 event_ptid = remote_wait_ns (ptid, status, options);
7029 else
7030 event_ptid = remote_wait_as (ptid, status, options);
7031
7032 if (target_is_async_p ())
7033 {
7034 /* If there are are events left in the queue tell the event loop
7035 to return here. */
7036 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7037 mark_async_event_handler (remote_async_inferior_event_token);
7038 }
7039
7040 return event_ptid;
7041 }
7042
7043 /* Fetch a single register using a 'p' packet. */
7044
7045 static int
7046 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7047 {
7048 struct remote_state *rs = get_remote_state ();
7049 char *buf, *p;
7050 char regp[MAX_REGISTER_SIZE];
7051 int i;
7052
7053 if (packet_support (PACKET_p) == PACKET_DISABLE)
7054 return 0;
7055
7056 if (reg->pnum == -1)
7057 return 0;
7058
7059 p = rs->buf;
7060 *p++ = 'p';
7061 p += hexnumstr (p, reg->pnum);
7062 *p++ = '\0';
7063 putpkt (rs->buf);
7064 getpkt (&rs->buf, &rs->buf_size, 0);
7065
7066 buf = rs->buf;
7067
7068 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7069 {
7070 case PACKET_OK:
7071 break;
7072 case PACKET_UNKNOWN:
7073 return 0;
7074 case PACKET_ERROR:
7075 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7076 gdbarch_register_name (get_regcache_arch (regcache),
7077 reg->regnum),
7078 buf);
7079 }
7080
7081 /* If this register is unfetchable, tell the regcache. */
7082 if (buf[0] == 'x')
7083 {
7084 regcache_raw_supply (regcache, reg->regnum, NULL);
7085 return 1;
7086 }
7087
7088 /* Otherwise, parse and supply the value. */
7089 p = buf;
7090 i = 0;
7091 while (p[0] != 0)
7092 {
7093 if (p[1] == 0)
7094 error (_("fetch_register_using_p: early buf termination"));
7095
7096 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7097 p += 2;
7098 }
7099 regcache_raw_supply (regcache, reg->regnum, regp);
7100 return 1;
7101 }
7102
7103 /* Fetch the registers included in the target's 'g' packet. */
7104
7105 static int
7106 send_g_packet (void)
7107 {
7108 struct remote_state *rs = get_remote_state ();
7109 int buf_len;
7110
7111 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7112 remote_send (&rs->buf, &rs->buf_size);
7113
7114 /* We can get out of synch in various cases. If the first character
7115 in the buffer is not a hex character, assume that has happened
7116 and try to fetch another packet to read. */
7117 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7118 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7119 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7120 && rs->buf[0] != 'x') /* New: unavailable register value. */
7121 {
7122 if (remote_debug)
7123 fprintf_unfiltered (gdb_stdlog,
7124 "Bad register packet; fetching a new packet\n");
7125 getpkt (&rs->buf, &rs->buf_size, 0);
7126 }
7127
7128 buf_len = strlen (rs->buf);
7129
7130 /* Sanity check the received packet. */
7131 if (buf_len % 2 != 0)
7132 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7133
7134 return buf_len / 2;
7135 }
7136
7137 static void
7138 process_g_packet (struct regcache *regcache)
7139 {
7140 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7141 struct remote_state *rs = get_remote_state ();
7142 struct remote_arch_state *rsa = get_remote_arch_state ();
7143 int i, buf_len;
7144 char *p;
7145 char *regs;
7146
7147 buf_len = strlen (rs->buf);
7148
7149 /* Further sanity checks, with knowledge of the architecture. */
7150 if (buf_len > 2 * rsa->sizeof_g_packet)
7151 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7152
7153 /* Save the size of the packet sent to us by the target. It is used
7154 as a heuristic when determining the max size of packets that the
7155 target can safely receive. */
7156 if (rsa->actual_register_packet_size == 0)
7157 rsa->actual_register_packet_size = buf_len;
7158
7159 /* If this is smaller than we guessed the 'g' packet would be,
7160 update our records. A 'g' reply that doesn't include a register's
7161 value implies either that the register is not available, or that
7162 the 'p' packet must be used. */
7163 if (buf_len < 2 * rsa->sizeof_g_packet)
7164 {
7165 rsa->sizeof_g_packet = buf_len / 2;
7166
7167 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7168 {
7169 if (rsa->regs[i].pnum == -1)
7170 continue;
7171
7172 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7173 rsa->regs[i].in_g_packet = 0;
7174 else
7175 rsa->regs[i].in_g_packet = 1;
7176 }
7177 }
7178
7179 regs = (char *) alloca (rsa->sizeof_g_packet);
7180
7181 /* Unimplemented registers read as all bits zero. */
7182 memset (regs, 0, rsa->sizeof_g_packet);
7183
7184 /* Reply describes registers byte by byte, each byte encoded as two
7185 hex characters. Suck them all up, then supply them to the
7186 register cacheing/storage mechanism. */
7187
7188 p = rs->buf;
7189 for (i = 0; i < rsa->sizeof_g_packet; i++)
7190 {
7191 if (p[0] == 0 || p[1] == 0)
7192 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7193 internal_error (__FILE__, __LINE__,
7194 _("unexpected end of 'g' packet reply"));
7195
7196 if (p[0] == 'x' && p[1] == 'x')
7197 regs[i] = 0; /* 'x' */
7198 else
7199 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7200 p += 2;
7201 }
7202
7203 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7204 {
7205 struct packet_reg *r = &rsa->regs[i];
7206
7207 if (r->in_g_packet)
7208 {
7209 if (r->offset * 2 >= strlen (rs->buf))
7210 /* This shouldn't happen - we adjusted in_g_packet above. */
7211 internal_error (__FILE__, __LINE__,
7212 _("unexpected end of 'g' packet reply"));
7213 else if (rs->buf[r->offset * 2] == 'x')
7214 {
7215 gdb_assert (r->offset * 2 < strlen (rs->buf));
7216 /* The register isn't available, mark it as such (at
7217 the same time setting the value to zero). */
7218 regcache_raw_supply (regcache, r->regnum, NULL);
7219 }
7220 else
7221 regcache_raw_supply (regcache, r->regnum,
7222 regs + r->offset);
7223 }
7224 }
7225 }
7226
7227 static void
7228 fetch_registers_using_g (struct regcache *regcache)
7229 {
7230 send_g_packet ();
7231 process_g_packet (regcache);
7232 }
7233
7234 /* Make the remote selected traceframe match GDB's selected
7235 traceframe. */
7236
7237 static void
7238 set_remote_traceframe (void)
7239 {
7240 int newnum;
7241 struct remote_state *rs = get_remote_state ();
7242
7243 if (rs->remote_traceframe_number == get_traceframe_number ())
7244 return;
7245
7246 /* Avoid recursion, remote_trace_find calls us again. */
7247 rs->remote_traceframe_number = get_traceframe_number ();
7248
7249 newnum = target_trace_find (tfind_number,
7250 get_traceframe_number (), 0, 0, NULL);
7251
7252 /* Should not happen. If it does, all bets are off. */
7253 if (newnum != get_traceframe_number ())
7254 warning (_("could not set remote traceframe"));
7255 }
7256
7257 static void
7258 remote_fetch_registers (struct target_ops *ops,
7259 struct regcache *regcache, int regnum)
7260 {
7261 struct remote_arch_state *rsa = get_remote_arch_state ();
7262 int i;
7263
7264 set_remote_traceframe ();
7265 set_general_thread (inferior_ptid);
7266
7267 if (regnum >= 0)
7268 {
7269 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7270
7271 gdb_assert (reg != NULL);
7272
7273 /* If this register might be in the 'g' packet, try that first -
7274 we are likely to read more than one register. If this is the
7275 first 'g' packet, we might be overly optimistic about its
7276 contents, so fall back to 'p'. */
7277 if (reg->in_g_packet)
7278 {
7279 fetch_registers_using_g (regcache);
7280 if (reg->in_g_packet)
7281 return;
7282 }
7283
7284 if (fetch_register_using_p (regcache, reg))
7285 return;
7286
7287 /* This register is not available. */
7288 regcache_raw_supply (regcache, reg->regnum, NULL);
7289
7290 return;
7291 }
7292
7293 fetch_registers_using_g (regcache);
7294
7295 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7296 if (!rsa->regs[i].in_g_packet)
7297 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7298 {
7299 /* This register is not available. */
7300 regcache_raw_supply (regcache, i, NULL);
7301 }
7302 }
7303
7304 /* Prepare to store registers. Since we may send them all (using a
7305 'G' request), we have to read out the ones we don't want to change
7306 first. */
7307
7308 static void
7309 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7310 {
7311 struct remote_arch_state *rsa = get_remote_arch_state ();
7312 int i;
7313 gdb_byte buf[MAX_REGISTER_SIZE];
7314
7315 /* Make sure the entire registers array is valid. */
7316 switch (packet_support (PACKET_P))
7317 {
7318 case PACKET_DISABLE:
7319 case PACKET_SUPPORT_UNKNOWN:
7320 /* Make sure all the necessary registers are cached. */
7321 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7322 if (rsa->regs[i].in_g_packet)
7323 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7324 break;
7325 case PACKET_ENABLE:
7326 break;
7327 }
7328 }
7329
7330 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7331 packet was not recognized. */
7332
7333 static int
7334 store_register_using_P (const struct regcache *regcache,
7335 struct packet_reg *reg)
7336 {
7337 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7338 struct remote_state *rs = get_remote_state ();
7339 /* Try storing a single register. */
7340 char *buf = rs->buf;
7341 gdb_byte regp[MAX_REGISTER_SIZE];
7342 char *p;
7343
7344 if (packet_support (PACKET_P) == PACKET_DISABLE)
7345 return 0;
7346
7347 if (reg->pnum == -1)
7348 return 0;
7349
7350 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7351 p = buf + strlen (buf);
7352 regcache_raw_collect (regcache, reg->regnum, regp);
7353 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7354 putpkt (rs->buf);
7355 getpkt (&rs->buf, &rs->buf_size, 0);
7356
7357 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7358 {
7359 case PACKET_OK:
7360 return 1;
7361 case PACKET_ERROR:
7362 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7363 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7364 case PACKET_UNKNOWN:
7365 return 0;
7366 default:
7367 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7368 }
7369 }
7370
7371 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7372 contents of the register cache buffer. FIXME: ignores errors. */
7373
7374 static void
7375 store_registers_using_G (const struct regcache *regcache)
7376 {
7377 struct remote_state *rs = get_remote_state ();
7378 struct remote_arch_state *rsa = get_remote_arch_state ();
7379 gdb_byte *regs;
7380 char *p;
7381
7382 /* Extract all the registers in the regcache copying them into a
7383 local buffer. */
7384 {
7385 int i;
7386
7387 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7388 memset (regs, 0, rsa->sizeof_g_packet);
7389 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7390 {
7391 struct packet_reg *r = &rsa->regs[i];
7392
7393 if (r->in_g_packet)
7394 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7395 }
7396 }
7397
7398 /* Command describes registers byte by byte,
7399 each byte encoded as two hex characters. */
7400 p = rs->buf;
7401 *p++ = 'G';
7402 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7403 updated. */
7404 bin2hex (regs, p, rsa->sizeof_g_packet);
7405 putpkt (rs->buf);
7406 getpkt (&rs->buf, &rs->buf_size, 0);
7407 if (packet_check_result (rs->buf) == PACKET_ERROR)
7408 error (_("Could not write registers; remote failure reply '%s'"),
7409 rs->buf);
7410 }
7411
7412 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7413 of the register cache buffer. FIXME: ignores errors. */
7414
7415 static void
7416 remote_store_registers (struct target_ops *ops,
7417 struct regcache *regcache, int regnum)
7418 {
7419 struct remote_arch_state *rsa = get_remote_arch_state ();
7420 int i;
7421
7422 set_remote_traceframe ();
7423 set_general_thread (inferior_ptid);
7424
7425 if (regnum >= 0)
7426 {
7427 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7428
7429 gdb_assert (reg != NULL);
7430
7431 /* Always prefer to store registers using the 'P' packet if
7432 possible; we often change only a small number of registers.
7433 Sometimes we change a larger number; we'd need help from a
7434 higher layer to know to use 'G'. */
7435 if (store_register_using_P (regcache, reg))
7436 return;
7437
7438 /* For now, don't complain if we have no way to write the
7439 register. GDB loses track of unavailable registers too
7440 easily. Some day, this may be an error. We don't have
7441 any way to read the register, either... */
7442 if (!reg->in_g_packet)
7443 return;
7444
7445 store_registers_using_G (regcache);
7446 return;
7447 }
7448
7449 store_registers_using_G (regcache);
7450
7451 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7452 if (!rsa->regs[i].in_g_packet)
7453 if (!store_register_using_P (regcache, &rsa->regs[i]))
7454 /* See above for why we do not issue an error here. */
7455 continue;
7456 }
7457 \f
7458
7459 /* Return the number of hex digits in num. */
7460
7461 static int
7462 hexnumlen (ULONGEST num)
7463 {
7464 int i;
7465
7466 for (i = 0; num != 0; i++)
7467 num >>= 4;
7468
7469 return max (i, 1);
7470 }
7471
7472 /* Set BUF to the minimum number of hex digits representing NUM. */
7473
7474 static int
7475 hexnumstr (char *buf, ULONGEST num)
7476 {
7477 int len = hexnumlen (num);
7478
7479 return hexnumnstr (buf, num, len);
7480 }
7481
7482
7483 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7484
7485 static int
7486 hexnumnstr (char *buf, ULONGEST num, int width)
7487 {
7488 int i;
7489
7490 buf[width] = '\0';
7491
7492 for (i = width - 1; i >= 0; i--)
7493 {
7494 buf[i] = "0123456789abcdef"[(num & 0xf)];
7495 num >>= 4;
7496 }
7497
7498 return width;
7499 }
7500
7501 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7502
7503 static CORE_ADDR
7504 remote_address_masked (CORE_ADDR addr)
7505 {
7506 unsigned int address_size = remote_address_size;
7507
7508 /* If "remoteaddresssize" was not set, default to target address size. */
7509 if (!address_size)
7510 address_size = gdbarch_addr_bit (target_gdbarch ());
7511
7512 if (address_size > 0
7513 && address_size < (sizeof (ULONGEST) * 8))
7514 {
7515 /* Only create a mask when that mask can safely be constructed
7516 in a ULONGEST variable. */
7517 ULONGEST mask = 1;
7518
7519 mask = (mask << address_size) - 1;
7520 addr &= mask;
7521 }
7522 return addr;
7523 }
7524
7525 /* Determine whether the remote target supports binary downloading.
7526 This is accomplished by sending a no-op memory write of zero length
7527 to the target at the specified address. It does not suffice to send
7528 the whole packet, since many stubs strip the eighth bit and
7529 subsequently compute a wrong checksum, which causes real havoc with
7530 remote_write_bytes.
7531
7532 NOTE: This can still lose if the serial line is not eight-bit
7533 clean. In cases like this, the user should clear "remote
7534 X-packet". */
7535
7536 static void
7537 check_binary_download (CORE_ADDR addr)
7538 {
7539 struct remote_state *rs = get_remote_state ();
7540
7541 switch (packet_support (PACKET_X))
7542 {
7543 case PACKET_DISABLE:
7544 break;
7545 case PACKET_ENABLE:
7546 break;
7547 case PACKET_SUPPORT_UNKNOWN:
7548 {
7549 char *p;
7550
7551 p = rs->buf;
7552 *p++ = 'X';
7553 p += hexnumstr (p, (ULONGEST) addr);
7554 *p++ = ',';
7555 p += hexnumstr (p, (ULONGEST) 0);
7556 *p++ = ':';
7557 *p = '\0';
7558
7559 putpkt_binary (rs->buf, (int) (p - rs->buf));
7560 getpkt (&rs->buf, &rs->buf_size, 0);
7561
7562 if (rs->buf[0] == '\0')
7563 {
7564 if (remote_debug)
7565 fprintf_unfiltered (gdb_stdlog,
7566 "binary downloading NOT "
7567 "supported by target\n");
7568 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7569 }
7570 else
7571 {
7572 if (remote_debug)
7573 fprintf_unfiltered (gdb_stdlog,
7574 "binary downloading supported by target\n");
7575 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7576 }
7577 break;
7578 }
7579 }
7580 }
7581
7582 /* Helper function to resize the payload in order to try to get a good
7583 alignment. We try to write an amount of data such that the next write will
7584 start on an address aligned on REMOTE_ALIGN_WRITES. */
7585
7586 static int
7587 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7588 {
7589 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7590 }
7591
7592 /* Write memory data directly to the remote machine.
7593 This does not inform the data cache; the data cache uses this.
7594 HEADER is the starting part of the packet.
7595 MEMADDR is the address in the remote memory space.
7596 MYADDR is the address of the buffer in our space.
7597 LEN_UNITS is the number of addressable units to write.
7598 UNIT_SIZE is the length in bytes of an addressable unit.
7599 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7600 should send data as binary ('X'), or hex-encoded ('M').
7601
7602 The function creates packet of the form
7603 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7604
7605 where encoding of <DATA> is terminated by PACKET_FORMAT.
7606
7607 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7608 are omitted.
7609
7610 Return the transferred status, error or OK (an
7611 'enum target_xfer_status' value). Save the number of addressable units
7612 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7613
7614 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7615 exchange between gdb and the stub could look like (?? in place of the
7616 checksum):
7617
7618 -> $m1000,4#??
7619 <- aaaabbbbccccdddd
7620
7621 -> $M1000,3:eeeeffffeeee#??
7622 <- OK
7623
7624 -> $m1000,4#??
7625 <- eeeeffffeeeedddd */
7626
7627 static enum target_xfer_status
7628 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7629 const gdb_byte *myaddr, ULONGEST len_units,
7630 int unit_size, ULONGEST *xfered_len_units,
7631 char packet_format, int use_length)
7632 {
7633 struct remote_state *rs = get_remote_state ();
7634 char *p;
7635 char *plen = NULL;
7636 int plenlen = 0;
7637 int todo_units;
7638 int units_written;
7639 int payload_capacity_bytes;
7640 int payload_length_bytes;
7641
7642 if (packet_format != 'X' && packet_format != 'M')
7643 internal_error (__FILE__, __LINE__,
7644 _("remote_write_bytes_aux: bad packet format"));
7645
7646 if (len_units == 0)
7647 return TARGET_XFER_EOF;
7648
7649 payload_capacity_bytes = get_memory_write_packet_size ();
7650
7651 /* The packet buffer will be large enough for the payload;
7652 get_memory_packet_size ensures this. */
7653 rs->buf[0] = '\0';
7654
7655 /* Compute the size of the actual payload by subtracting out the
7656 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7657
7658 payload_capacity_bytes -= strlen ("$,:#NN");
7659 if (!use_length)
7660 /* The comma won't be used. */
7661 payload_capacity_bytes += 1;
7662 payload_capacity_bytes -= strlen (header);
7663 payload_capacity_bytes -= hexnumlen (memaddr);
7664
7665 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7666
7667 strcat (rs->buf, header);
7668 p = rs->buf + strlen (header);
7669
7670 /* Compute a best guess of the number of bytes actually transfered. */
7671 if (packet_format == 'X')
7672 {
7673 /* Best guess at number of bytes that will fit. */
7674 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7675 if (use_length)
7676 payload_capacity_bytes -= hexnumlen (todo_units);
7677 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7678 }
7679 else
7680 {
7681 /* Number of bytes that will fit. */
7682 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7683 if (use_length)
7684 payload_capacity_bytes -= hexnumlen (todo_units);
7685 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7686 }
7687
7688 if (todo_units <= 0)
7689 internal_error (__FILE__, __LINE__,
7690 _("minimum packet size too small to write data"));
7691
7692 /* If we already need another packet, then try to align the end
7693 of this packet to a useful boundary. */
7694 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7695 todo_units = align_for_efficient_write (todo_units, memaddr);
7696
7697 /* Append "<memaddr>". */
7698 memaddr = remote_address_masked (memaddr);
7699 p += hexnumstr (p, (ULONGEST) memaddr);
7700
7701 if (use_length)
7702 {
7703 /* Append ",". */
7704 *p++ = ',';
7705
7706 /* Append the length and retain its location and size. It may need to be
7707 adjusted once the packet body has been created. */
7708 plen = p;
7709 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7710 p += plenlen;
7711 }
7712
7713 /* Append ":". */
7714 *p++ = ':';
7715 *p = '\0';
7716
7717 /* Append the packet body. */
7718 if (packet_format == 'X')
7719 {
7720 /* Binary mode. Send target system values byte by byte, in
7721 increasing byte addresses. Only escape certain critical
7722 characters. */
7723 payload_length_bytes =
7724 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7725 &units_written, payload_capacity_bytes);
7726
7727 /* If not all TODO units fit, then we'll need another packet. Make
7728 a second try to keep the end of the packet aligned. Don't do
7729 this if the packet is tiny. */
7730 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7731 {
7732 int new_todo_units;
7733
7734 new_todo_units = align_for_efficient_write (units_written, memaddr);
7735
7736 if (new_todo_units != units_written)
7737 payload_length_bytes =
7738 remote_escape_output (myaddr, new_todo_units, unit_size,
7739 (gdb_byte *) p, &units_written,
7740 payload_capacity_bytes);
7741 }
7742
7743 p += payload_length_bytes;
7744 if (use_length && units_written < todo_units)
7745 {
7746 /* Escape chars have filled up the buffer prematurely,
7747 and we have actually sent fewer units than planned.
7748 Fix-up the length field of the packet. Use the same
7749 number of characters as before. */
7750 plen += hexnumnstr (plen, (ULONGEST) units_written,
7751 plenlen);
7752 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7753 }
7754 }
7755 else
7756 {
7757 /* Normal mode: Send target system values byte by byte, in
7758 increasing byte addresses. Each byte is encoded as a two hex
7759 value. */
7760 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7761 units_written = todo_units;
7762 }
7763
7764 putpkt_binary (rs->buf, (int) (p - rs->buf));
7765 getpkt (&rs->buf, &rs->buf_size, 0);
7766
7767 if (rs->buf[0] == 'E')
7768 return TARGET_XFER_E_IO;
7769
7770 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7771 send fewer units than we'd planned. */
7772 *xfered_len_units = (ULONGEST) units_written;
7773 return TARGET_XFER_OK;
7774 }
7775
7776 /* Write memory data directly to the remote machine.
7777 This does not inform the data cache; the data cache uses this.
7778 MEMADDR is the address in the remote memory space.
7779 MYADDR is the address of the buffer in our space.
7780 LEN is the number of bytes.
7781
7782 Return the transferred status, error or OK (an
7783 'enum target_xfer_status' value). Save the number of bytes
7784 transferred in *XFERED_LEN. Only transfer a single packet. */
7785
7786 static enum target_xfer_status
7787 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7788 int unit_size, ULONGEST *xfered_len)
7789 {
7790 char *packet_format = 0;
7791
7792 /* Check whether the target supports binary download. */
7793 check_binary_download (memaddr);
7794
7795 switch (packet_support (PACKET_X))
7796 {
7797 case PACKET_ENABLE:
7798 packet_format = "X";
7799 break;
7800 case PACKET_DISABLE:
7801 packet_format = "M";
7802 break;
7803 case PACKET_SUPPORT_UNKNOWN:
7804 internal_error (__FILE__, __LINE__,
7805 _("remote_write_bytes: bad internal state"));
7806 default:
7807 internal_error (__FILE__, __LINE__, _("bad switch"));
7808 }
7809
7810 return remote_write_bytes_aux (packet_format,
7811 memaddr, myaddr, len, unit_size, xfered_len,
7812 packet_format[0], 1);
7813 }
7814
7815 /* Read memory data directly from the remote machine.
7816 This does not use the data cache; the data cache uses this.
7817 MEMADDR is the address in the remote memory space.
7818 MYADDR is the address of the buffer in our space.
7819 LEN_UNITS is the number of addressable memory units to read..
7820 UNIT_SIZE is the length in bytes of an addressable unit.
7821
7822 Return the transferred status, error or OK (an
7823 'enum target_xfer_status' value). Save the number of bytes
7824 transferred in *XFERED_LEN_UNITS.
7825
7826 See the comment of remote_write_bytes_aux for an example of
7827 memory read/write exchange between gdb and the stub. */
7828
7829 static enum target_xfer_status
7830 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7831 int unit_size, ULONGEST *xfered_len_units)
7832 {
7833 struct remote_state *rs = get_remote_state ();
7834 int buf_size_bytes; /* Max size of packet output buffer. */
7835 char *p;
7836 int todo_units;
7837 int decoded_bytes;
7838
7839 buf_size_bytes = get_memory_read_packet_size ();
7840 /* The packet buffer will be large enough for the payload;
7841 get_memory_packet_size ensures this. */
7842
7843 /* Number of units that will fit. */
7844 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7845
7846 /* Construct "m"<memaddr>","<len>". */
7847 memaddr = remote_address_masked (memaddr);
7848 p = rs->buf;
7849 *p++ = 'm';
7850 p += hexnumstr (p, (ULONGEST) memaddr);
7851 *p++ = ',';
7852 p += hexnumstr (p, (ULONGEST) todo_units);
7853 *p = '\0';
7854 putpkt (rs->buf);
7855 getpkt (&rs->buf, &rs->buf_size, 0);
7856 if (rs->buf[0] == 'E'
7857 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7858 && rs->buf[3] == '\0')
7859 return TARGET_XFER_E_IO;
7860 /* Reply describes memory byte by byte, each byte encoded as two hex
7861 characters. */
7862 p = rs->buf;
7863 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7864 /* Return what we have. Let higher layers handle partial reads. */
7865 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7866 return TARGET_XFER_OK;
7867 }
7868
7869 /* Using the set of read-only target sections of remote, read live
7870 read-only memory.
7871
7872 For interface/parameters/return description see target.h,
7873 to_xfer_partial. */
7874
7875 static enum target_xfer_status
7876 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7877 ULONGEST memaddr, ULONGEST len,
7878 int unit_size, ULONGEST *xfered_len)
7879 {
7880 struct target_section *secp;
7881 struct target_section_table *table;
7882
7883 secp = target_section_by_addr (ops, memaddr);
7884 if (secp != NULL
7885 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7886 secp->the_bfd_section)
7887 & SEC_READONLY))
7888 {
7889 struct target_section *p;
7890 ULONGEST memend = memaddr + len;
7891
7892 table = target_get_section_table (ops);
7893
7894 for (p = table->sections; p < table->sections_end; p++)
7895 {
7896 if (memaddr >= p->addr)
7897 {
7898 if (memend <= p->endaddr)
7899 {
7900 /* Entire transfer is within this section. */
7901 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7902 xfered_len);
7903 }
7904 else if (memaddr >= p->endaddr)
7905 {
7906 /* This section ends before the transfer starts. */
7907 continue;
7908 }
7909 else
7910 {
7911 /* This section overlaps the transfer. Just do half. */
7912 len = p->endaddr - memaddr;
7913 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7914 xfered_len);
7915 }
7916 }
7917 }
7918 }
7919
7920 return TARGET_XFER_EOF;
7921 }
7922
7923 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7924 first if the requested memory is unavailable in traceframe.
7925 Otherwise, fall back to remote_read_bytes_1. */
7926
7927 static enum target_xfer_status
7928 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7929 gdb_byte *myaddr, ULONGEST len, int unit_size,
7930 ULONGEST *xfered_len)
7931 {
7932 if (len == 0)
7933 return TARGET_XFER_EOF;
7934
7935 if (get_traceframe_number () != -1)
7936 {
7937 VEC(mem_range_s) *available;
7938
7939 /* If we fail to get the set of available memory, then the
7940 target does not support querying traceframe info, and so we
7941 attempt reading from the traceframe anyway (assuming the
7942 target implements the old QTro packet then). */
7943 if (traceframe_available_memory (&available, memaddr, len))
7944 {
7945 struct cleanup *old_chain;
7946
7947 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7948
7949 if (VEC_empty (mem_range_s, available)
7950 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7951 {
7952 enum target_xfer_status res;
7953
7954 /* Don't read into the traceframe's available
7955 memory. */
7956 if (!VEC_empty (mem_range_s, available))
7957 {
7958 LONGEST oldlen = len;
7959
7960 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7961 gdb_assert (len <= oldlen);
7962 }
7963
7964 do_cleanups (old_chain);
7965
7966 /* This goes through the topmost target again. */
7967 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7968 len, unit_size, xfered_len);
7969 if (res == TARGET_XFER_OK)
7970 return TARGET_XFER_OK;
7971 else
7972 {
7973 /* No use trying further, we know some memory starting
7974 at MEMADDR isn't available. */
7975 *xfered_len = len;
7976 return TARGET_XFER_UNAVAILABLE;
7977 }
7978 }
7979
7980 /* Don't try to read more than how much is available, in
7981 case the target implements the deprecated QTro packet to
7982 cater for older GDBs (the target's knowledge of read-only
7983 sections may be outdated by now). */
7984 len = VEC_index (mem_range_s, available, 0)->length;
7985
7986 do_cleanups (old_chain);
7987 }
7988 }
7989
7990 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7991 }
7992
7993 \f
7994
7995 /* Sends a packet with content determined by the printf format string
7996 FORMAT and the remaining arguments, then gets the reply. Returns
7997 whether the packet was a success, a failure, or unknown. */
7998
7999 static enum packet_result remote_send_printf (const char *format, ...)
8000 ATTRIBUTE_PRINTF (1, 2);
8001
8002 static enum packet_result
8003 remote_send_printf (const char *format, ...)
8004 {
8005 struct remote_state *rs = get_remote_state ();
8006 int max_size = get_remote_packet_size ();
8007 va_list ap;
8008
8009 va_start (ap, format);
8010
8011 rs->buf[0] = '\0';
8012 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8013 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8014
8015 if (putpkt (rs->buf) < 0)
8016 error (_("Communication problem with target."));
8017
8018 rs->buf[0] = '\0';
8019 getpkt (&rs->buf, &rs->buf_size, 0);
8020
8021 return packet_check_result (rs->buf);
8022 }
8023
8024 static void
8025 restore_remote_timeout (void *p)
8026 {
8027 int value = *(int *)p;
8028
8029 remote_timeout = value;
8030 }
8031
8032 /* Flash writing can take quite some time. We'll set
8033 effectively infinite timeout for flash operations.
8034 In future, we'll need to decide on a better approach. */
8035 static const int remote_flash_timeout = 1000;
8036
8037 static void
8038 remote_flash_erase (struct target_ops *ops,
8039 ULONGEST address, LONGEST length)
8040 {
8041 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8042 int saved_remote_timeout = remote_timeout;
8043 enum packet_result ret;
8044 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8045 &saved_remote_timeout);
8046
8047 remote_timeout = remote_flash_timeout;
8048
8049 ret = remote_send_printf ("vFlashErase:%s,%s",
8050 phex (address, addr_size),
8051 phex (length, 4));
8052 switch (ret)
8053 {
8054 case PACKET_UNKNOWN:
8055 error (_("Remote target does not support flash erase"));
8056 case PACKET_ERROR:
8057 error (_("Error erasing flash with vFlashErase packet"));
8058 default:
8059 break;
8060 }
8061
8062 do_cleanups (back_to);
8063 }
8064
8065 static enum target_xfer_status
8066 remote_flash_write (struct target_ops *ops, ULONGEST address,
8067 ULONGEST length, ULONGEST *xfered_len,
8068 const gdb_byte *data)
8069 {
8070 int saved_remote_timeout = remote_timeout;
8071 enum target_xfer_status ret;
8072 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8073 &saved_remote_timeout);
8074
8075 remote_timeout = remote_flash_timeout;
8076 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8077 xfered_len,'X', 0);
8078 do_cleanups (back_to);
8079
8080 return ret;
8081 }
8082
8083 static void
8084 remote_flash_done (struct target_ops *ops)
8085 {
8086 int saved_remote_timeout = remote_timeout;
8087 int ret;
8088 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8089 &saved_remote_timeout);
8090
8091 remote_timeout = remote_flash_timeout;
8092 ret = remote_send_printf ("vFlashDone");
8093 do_cleanups (back_to);
8094
8095 switch (ret)
8096 {
8097 case PACKET_UNKNOWN:
8098 error (_("Remote target does not support vFlashDone"));
8099 case PACKET_ERROR:
8100 error (_("Error finishing flash operation"));
8101 default:
8102 break;
8103 }
8104 }
8105
8106 static void
8107 remote_files_info (struct target_ops *ignore)
8108 {
8109 puts_filtered ("Debugging a target over a serial line.\n");
8110 }
8111 \f
8112 /* Stuff for dealing with the packets which are part of this protocol.
8113 See comment at top of file for details. */
8114
8115 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8116 error to higher layers. Called when a serial error is detected.
8117 The exception message is STRING, followed by a colon and a blank,
8118 the system error message for errno at function entry and final dot
8119 for output compatibility with throw_perror_with_name. */
8120
8121 static void
8122 unpush_and_perror (const char *string)
8123 {
8124 int saved_errno = errno;
8125
8126 remote_unpush_target ();
8127 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8128 safe_strerror (saved_errno));
8129 }
8130
8131 /* Read a single character from the remote end. The current quit
8132 handler is overridden to avoid quitting in the middle of packet
8133 sequence, as that would break communication with the remote server.
8134 See remote_serial_quit_handler for more detail. */
8135
8136 static int
8137 readchar (int timeout)
8138 {
8139 int ch;
8140 struct remote_state *rs = get_remote_state ();
8141 struct cleanup *old_chain;
8142
8143 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8144
8145 rs->got_ctrlc_during_io = 0;
8146
8147 ch = serial_readchar (rs->remote_desc, timeout);
8148
8149 if (rs->got_ctrlc_during_io)
8150 set_quit_flag ();
8151
8152 do_cleanups (old_chain);
8153
8154 if (ch >= 0)
8155 return ch;
8156
8157 switch ((enum serial_rc) ch)
8158 {
8159 case SERIAL_EOF:
8160 remote_unpush_target ();
8161 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8162 /* no return */
8163 case SERIAL_ERROR:
8164 unpush_and_perror (_("Remote communication error. "
8165 "Target disconnected."));
8166 /* no return */
8167 case SERIAL_TIMEOUT:
8168 break;
8169 }
8170 return ch;
8171 }
8172
8173 /* Wrapper for serial_write that closes the target and throws if
8174 writing fails. The current quit handler is overridden to avoid
8175 quitting in the middle of packet sequence, as that would break
8176 communication with the remote server. See
8177 remote_serial_quit_handler for more detail. */
8178
8179 static void
8180 remote_serial_write (const char *str, int len)
8181 {
8182 struct remote_state *rs = get_remote_state ();
8183 struct cleanup *old_chain;
8184
8185 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8186
8187 rs->got_ctrlc_during_io = 0;
8188
8189 if (serial_write (rs->remote_desc, str, len))
8190 {
8191 unpush_and_perror (_("Remote communication error. "
8192 "Target disconnected."));
8193 }
8194
8195 if (rs->got_ctrlc_during_io)
8196 set_quit_flag ();
8197
8198 do_cleanups (old_chain);
8199 }
8200
8201 /* Send the command in *BUF to the remote machine, and read the reply
8202 into *BUF. Report an error if we get an error reply. Resize
8203 *BUF using xrealloc if necessary to hold the result, and update
8204 *SIZEOF_BUF. */
8205
8206 static void
8207 remote_send (char **buf,
8208 long *sizeof_buf)
8209 {
8210 putpkt (*buf);
8211 getpkt (buf, sizeof_buf, 0);
8212
8213 if ((*buf)[0] == 'E')
8214 error (_("Remote failure reply: %s"), *buf);
8215 }
8216
8217 /* Return a pointer to an xmalloc'ed string representing an escaped
8218 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8219 etc. The caller is responsible for releasing the returned
8220 memory. */
8221
8222 static char *
8223 escape_buffer (const char *buf, int n)
8224 {
8225 struct cleanup *old_chain;
8226 struct ui_file *stb;
8227 char *str;
8228
8229 stb = mem_fileopen ();
8230 old_chain = make_cleanup_ui_file_delete (stb);
8231
8232 fputstrn_unfiltered (buf, n, '\\', stb);
8233 str = ui_file_xstrdup (stb, NULL);
8234 do_cleanups (old_chain);
8235 return str;
8236 }
8237
8238 /* Display a null-terminated packet on stdout, for debugging, using C
8239 string notation. */
8240
8241 static void
8242 print_packet (const char *buf)
8243 {
8244 puts_filtered ("\"");
8245 fputstr_filtered (buf, '"', gdb_stdout);
8246 puts_filtered ("\"");
8247 }
8248
8249 int
8250 putpkt (const char *buf)
8251 {
8252 return putpkt_binary (buf, strlen (buf));
8253 }
8254
8255 /* Send a packet to the remote machine, with error checking. The data
8256 of the packet is in BUF. The string in BUF can be at most
8257 get_remote_packet_size () - 5 to account for the $, # and checksum,
8258 and for a possible /0 if we are debugging (remote_debug) and want
8259 to print the sent packet as a string. */
8260
8261 static int
8262 putpkt_binary (const char *buf, int cnt)
8263 {
8264 struct remote_state *rs = get_remote_state ();
8265 int i;
8266 unsigned char csum = 0;
8267 char *buf2 = (char *) xmalloc (cnt + 6);
8268 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8269
8270 int ch;
8271 int tcount = 0;
8272 char *p;
8273
8274 /* Catch cases like trying to read memory or listing threads while
8275 we're waiting for a stop reply. The remote server wouldn't be
8276 ready to handle this request, so we'd hang and timeout. We don't
8277 have to worry about this in synchronous mode, because in that
8278 case it's not possible to issue a command while the target is
8279 running. This is not a problem in non-stop mode, because in that
8280 case, the stub is always ready to process serial input. */
8281 if (!target_is_non_stop_p ()
8282 && target_is_async_p ()
8283 && rs->waiting_for_stop_reply)
8284 {
8285 error (_("Cannot execute this command while the target is running.\n"
8286 "Use the \"interrupt\" command to stop the target\n"
8287 "and then try again."));
8288 }
8289
8290 /* We're sending out a new packet. Make sure we don't look at a
8291 stale cached response. */
8292 rs->cached_wait_status = 0;
8293
8294 /* Copy the packet into buffer BUF2, encapsulating it
8295 and giving it a checksum. */
8296
8297 p = buf2;
8298 *p++ = '$';
8299
8300 for (i = 0; i < cnt; i++)
8301 {
8302 csum += buf[i];
8303 *p++ = buf[i];
8304 }
8305 *p++ = '#';
8306 *p++ = tohex ((csum >> 4) & 0xf);
8307 *p++ = tohex (csum & 0xf);
8308
8309 /* Send it over and over until we get a positive ack. */
8310
8311 while (1)
8312 {
8313 int started_error_output = 0;
8314
8315 if (remote_debug)
8316 {
8317 struct cleanup *old_chain;
8318 char *str;
8319
8320 *p = '\0';
8321 str = escape_buffer (buf2, p - buf2);
8322 old_chain = make_cleanup (xfree, str);
8323 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8324 gdb_flush (gdb_stdlog);
8325 do_cleanups (old_chain);
8326 }
8327 remote_serial_write (buf2, p - buf2);
8328
8329 /* If this is a no acks version of the remote protocol, send the
8330 packet and move on. */
8331 if (rs->noack_mode)
8332 break;
8333
8334 /* Read until either a timeout occurs (-2) or '+' is read.
8335 Handle any notification that arrives in the mean time. */
8336 while (1)
8337 {
8338 ch = readchar (remote_timeout);
8339
8340 if (remote_debug)
8341 {
8342 switch (ch)
8343 {
8344 case '+':
8345 case '-':
8346 case SERIAL_TIMEOUT:
8347 case '$':
8348 case '%':
8349 if (started_error_output)
8350 {
8351 putchar_unfiltered ('\n');
8352 started_error_output = 0;
8353 }
8354 }
8355 }
8356
8357 switch (ch)
8358 {
8359 case '+':
8360 if (remote_debug)
8361 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8362 do_cleanups (old_chain);
8363 return 1;
8364 case '-':
8365 if (remote_debug)
8366 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8367 /* FALLTHROUGH */
8368 case SERIAL_TIMEOUT:
8369 tcount++;
8370 if (tcount > 3)
8371 {
8372 do_cleanups (old_chain);
8373 return 0;
8374 }
8375 break; /* Retransmit buffer. */
8376 case '$':
8377 {
8378 if (remote_debug)
8379 fprintf_unfiltered (gdb_stdlog,
8380 "Packet instead of Ack, ignoring it\n");
8381 /* It's probably an old response sent because an ACK
8382 was lost. Gobble up the packet and ack it so it
8383 doesn't get retransmitted when we resend this
8384 packet. */
8385 skip_frame ();
8386 remote_serial_write ("+", 1);
8387 continue; /* Now, go look for +. */
8388 }
8389
8390 case '%':
8391 {
8392 int val;
8393
8394 /* If we got a notification, handle it, and go back to looking
8395 for an ack. */
8396 /* We've found the start of a notification. Now
8397 collect the data. */
8398 val = read_frame (&rs->buf, &rs->buf_size);
8399 if (val >= 0)
8400 {
8401 if (remote_debug)
8402 {
8403 struct cleanup *old_chain;
8404 char *str;
8405
8406 str = escape_buffer (rs->buf, val);
8407 old_chain = make_cleanup (xfree, str);
8408 fprintf_unfiltered (gdb_stdlog,
8409 " Notification received: %s\n",
8410 str);
8411 do_cleanups (old_chain);
8412 }
8413 handle_notification (rs->notif_state, rs->buf);
8414 /* We're in sync now, rewait for the ack. */
8415 tcount = 0;
8416 }
8417 else
8418 {
8419 if (remote_debug)
8420 {
8421 if (!started_error_output)
8422 {
8423 started_error_output = 1;
8424 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8425 }
8426 fputc_unfiltered (ch & 0177, gdb_stdlog);
8427 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8428 }
8429 }
8430 continue;
8431 }
8432 /* fall-through */
8433 default:
8434 if (remote_debug)
8435 {
8436 if (!started_error_output)
8437 {
8438 started_error_output = 1;
8439 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8440 }
8441 fputc_unfiltered (ch & 0177, gdb_stdlog);
8442 }
8443 continue;
8444 }
8445 break; /* Here to retransmit. */
8446 }
8447
8448 #if 0
8449 /* This is wrong. If doing a long backtrace, the user should be
8450 able to get out next time we call QUIT, without anything as
8451 violent as interrupt_query. If we want to provide a way out of
8452 here without getting to the next QUIT, it should be based on
8453 hitting ^C twice as in remote_wait. */
8454 if (quit_flag)
8455 {
8456 quit_flag = 0;
8457 interrupt_query ();
8458 }
8459 #endif
8460 }
8461
8462 do_cleanups (old_chain);
8463 return 0;
8464 }
8465
8466 /* Come here after finding the start of a frame when we expected an
8467 ack. Do our best to discard the rest of this packet. */
8468
8469 static void
8470 skip_frame (void)
8471 {
8472 int c;
8473
8474 while (1)
8475 {
8476 c = readchar (remote_timeout);
8477 switch (c)
8478 {
8479 case SERIAL_TIMEOUT:
8480 /* Nothing we can do. */
8481 return;
8482 case '#':
8483 /* Discard the two bytes of checksum and stop. */
8484 c = readchar (remote_timeout);
8485 if (c >= 0)
8486 c = readchar (remote_timeout);
8487
8488 return;
8489 case '*': /* Run length encoding. */
8490 /* Discard the repeat count. */
8491 c = readchar (remote_timeout);
8492 if (c < 0)
8493 return;
8494 break;
8495 default:
8496 /* A regular character. */
8497 break;
8498 }
8499 }
8500 }
8501
8502 /* Come here after finding the start of the frame. Collect the rest
8503 into *BUF, verifying the checksum, length, and handling run-length
8504 compression. NUL terminate the buffer. If there is not enough room,
8505 expand *BUF using xrealloc.
8506
8507 Returns -1 on error, number of characters in buffer (ignoring the
8508 trailing NULL) on success. (could be extended to return one of the
8509 SERIAL status indications). */
8510
8511 static long
8512 read_frame (char **buf_p,
8513 long *sizeof_buf)
8514 {
8515 unsigned char csum;
8516 long bc;
8517 int c;
8518 char *buf = *buf_p;
8519 struct remote_state *rs = get_remote_state ();
8520
8521 csum = 0;
8522 bc = 0;
8523
8524 while (1)
8525 {
8526 c = readchar (remote_timeout);
8527 switch (c)
8528 {
8529 case SERIAL_TIMEOUT:
8530 if (remote_debug)
8531 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8532 return -1;
8533 case '$':
8534 if (remote_debug)
8535 fputs_filtered ("Saw new packet start in middle of old one\n",
8536 gdb_stdlog);
8537 return -1; /* Start a new packet, count retries. */
8538 case '#':
8539 {
8540 unsigned char pktcsum;
8541 int check_0 = 0;
8542 int check_1 = 0;
8543
8544 buf[bc] = '\0';
8545
8546 check_0 = readchar (remote_timeout);
8547 if (check_0 >= 0)
8548 check_1 = readchar (remote_timeout);
8549
8550 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8551 {
8552 if (remote_debug)
8553 fputs_filtered ("Timeout in checksum, retrying\n",
8554 gdb_stdlog);
8555 return -1;
8556 }
8557 else if (check_0 < 0 || check_1 < 0)
8558 {
8559 if (remote_debug)
8560 fputs_filtered ("Communication error in checksum\n",
8561 gdb_stdlog);
8562 return -1;
8563 }
8564
8565 /* Don't recompute the checksum; with no ack packets we
8566 don't have any way to indicate a packet retransmission
8567 is necessary. */
8568 if (rs->noack_mode)
8569 return bc;
8570
8571 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8572 if (csum == pktcsum)
8573 return bc;
8574
8575 if (remote_debug)
8576 {
8577 struct cleanup *old_chain;
8578 char *str;
8579
8580 str = escape_buffer (buf, bc);
8581 old_chain = make_cleanup (xfree, str);
8582 fprintf_unfiltered (gdb_stdlog,
8583 "Bad checksum, sentsum=0x%x, "
8584 "csum=0x%x, buf=%s\n",
8585 pktcsum, csum, str);
8586 do_cleanups (old_chain);
8587 }
8588 /* Number of characters in buffer ignoring trailing
8589 NULL. */
8590 return -1;
8591 }
8592 case '*': /* Run length encoding. */
8593 {
8594 int repeat;
8595
8596 csum += c;
8597 c = readchar (remote_timeout);
8598 csum += c;
8599 repeat = c - ' ' + 3; /* Compute repeat count. */
8600
8601 /* The character before ``*'' is repeated. */
8602
8603 if (repeat > 0 && repeat <= 255 && bc > 0)
8604 {
8605 if (bc + repeat - 1 >= *sizeof_buf - 1)
8606 {
8607 /* Make some more room in the buffer. */
8608 *sizeof_buf += repeat;
8609 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8610 buf = *buf_p;
8611 }
8612
8613 memset (&buf[bc], buf[bc - 1], repeat);
8614 bc += repeat;
8615 continue;
8616 }
8617
8618 buf[bc] = '\0';
8619 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8620 return -1;
8621 }
8622 default:
8623 if (bc >= *sizeof_buf - 1)
8624 {
8625 /* Make some more room in the buffer. */
8626 *sizeof_buf *= 2;
8627 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8628 buf = *buf_p;
8629 }
8630
8631 buf[bc++] = c;
8632 csum += c;
8633 continue;
8634 }
8635 }
8636 }
8637
8638 /* Read a packet from the remote machine, with error checking, and
8639 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8640 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8641 rather than timing out; this is used (in synchronous mode) to wait
8642 for a target that is is executing user code to stop. */
8643 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8644 don't have to change all the calls to getpkt to deal with the
8645 return value, because at the moment I don't know what the right
8646 thing to do it for those. */
8647 void
8648 getpkt (char **buf,
8649 long *sizeof_buf,
8650 int forever)
8651 {
8652 getpkt_sane (buf, sizeof_buf, forever);
8653 }
8654
8655
8656 /* Read a packet from the remote machine, with error checking, and
8657 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8658 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8659 rather than timing out; this is used (in synchronous mode) to wait
8660 for a target that is is executing user code to stop. If FOREVER ==
8661 0, this function is allowed to time out gracefully and return an
8662 indication of this to the caller. Otherwise return the number of
8663 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8664 enough reason to return to the caller. *IS_NOTIF is an output
8665 boolean that indicates whether *BUF holds a notification or not
8666 (a regular packet). */
8667
8668 static int
8669 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8670 int expecting_notif, int *is_notif)
8671 {
8672 struct remote_state *rs = get_remote_state ();
8673 int c;
8674 int tries;
8675 int timeout;
8676 int val = -1;
8677
8678 /* We're reading a new response. Make sure we don't look at a
8679 previously cached response. */
8680 rs->cached_wait_status = 0;
8681
8682 strcpy (*buf, "timeout");
8683
8684 if (forever)
8685 timeout = watchdog > 0 ? watchdog : -1;
8686 else if (expecting_notif)
8687 timeout = 0; /* There should already be a char in the buffer. If
8688 not, bail out. */
8689 else
8690 timeout = remote_timeout;
8691
8692 #define MAX_TRIES 3
8693
8694 /* Process any number of notifications, and then return when
8695 we get a packet. */
8696 for (;;)
8697 {
8698 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8699 times. */
8700 for (tries = 1; tries <= MAX_TRIES; tries++)
8701 {
8702 /* This can loop forever if the remote side sends us
8703 characters continuously, but if it pauses, we'll get
8704 SERIAL_TIMEOUT from readchar because of timeout. Then
8705 we'll count that as a retry.
8706
8707 Note that even when forever is set, we will only wait
8708 forever prior to the start of a packet. After that, we
8709 expect characters to arrive at a brisk pace. They should
8710 show up within remote_timeout intervals. */
8711 do
8712 c = readchar (timeout);
8713 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8714
8715 if (c == SERIAL_TIMEOUT)
8716 {
8717 if (expecting_notif)
8718 return -1; /* Don't complain, it's normal to not get
8719 anything in this case. */
8720
8721 if (forever) /* Watchdog went off? Kill the target. */
8722 {
8723 remote_unpush_target ();
8724 throw_error (TARGET_CLOSE_ERROR,
8725 _("Watchdog timeout has expired. "
8726 "Target detached."));
8727 }
8728 if (remote_debug)
8729 fputs_filtered ("Timed out.\n", gdb_stdlog);
8730 }
8731 else
8732 {
8733 /* We've found the start of a packet or notification.
8734 Now collect the data. */
8735 val = read_frame (buf, sizeof_buf);
8736 if (val >= 0)
8737 break;
8738 }
8739
8740 remote_serial_write ("-", 1);
8741 }
8742
8743 if (tries > MAX_TRIES)
8744 {
8745 /* We have tried hard enough, and just can't receive the
8746 packet/notification. Give up. */
8747 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8748
8749 /* Skip the ack char if we're in no-ack mode. */
8750 if (!rs->noack_mode)
8751 remote_serial_write ("+", 1);
8752 return -1;
8753 }
8754
8755 /* If we got an ordinary packet, return that to our caller. */
8756 if (c == '$')
8757 {
8758 if (remote_debug)
8759 {
8760 struct cleanup *old_chain;
8761 char *str;
8762
8763 str = escape_buffer (*buf, val);
8764 old_chain = make_cleanup (xfree, str);
8765 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8766 do_cleanups (old_chain);
8767 }
8768
8769 /* Skip the ack char if we're in no-ack mode. */
8770 if (!rs->noack_mode)
8771 remote_serial_write ("+", 1);
8772 if (is_notif != NULL)
8773 *is_notif = 0;
8774 return val;
8775 }
8776
8777 /* If we got a notification, handle it, and go back to looking
8778 for a packet. */
8779 else
8780 {
8781 gdb_assert (c == '%');
8782
8783 if (remote_debug)
8784 {
8785 struct cleanup *old_chain;
8786 char *str;
8787
8788 str = escape_buffer (*buf, val);
8789 old_chain = make_cleanup (xfree, str);
8790 fprintf_unfiltered (gdb_stdlog,
8791 " Notification received: %s\n",
8792 str);
8793 do_cleanups (old_chain);
8794 }
8795 if (is_notif != NULL)
8796 *is_notif = 1;
8797
8798 handle_notification (rs->notif_state, *buf);
8799
8800 /* Notifications require no acknowledgement. */
8801
8802 if (expecting_notif)
8803 return val;
8804 }
8805 }
8806 }
8807
8808 static int
8809 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8810 {
8811 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8812 }
8813
8814 static int
8815 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8816 int *is_notif)
8817 {
8818 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8819 is_notif);
8820 }
8821
8822 /* Check whether EVENT is a fork event for the process specified
8823 by the pid passed in DATA, and if it is, kill the fork child. */
8824
8825 static int
8826 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8827 QUEUE_ITER (stop_reply_p) *iter,
8828 stop_reply_p event,
8829 void *data)
8830 {
8831 struct queue_iter_param *param = (struct queue_iter_param *) data;
8832 int parent_pid = *(int *) param->input;
8833
8834 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8835 {
8836 struct remote_state *rs = get_remote_state ();
8837 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8838 int res;
8839
8840 res = remote_vkill (child_pid, rs);
8841 if (res != 0)
8842 error (_("Can't kill fork child process %d"), child_pid);
8843 }
8844
8845 return 1;
8846 }
8847
8848 /* Kill any new fork children of process PID that haven't been
8849 processed by follow_fork. */
8850
8851 static void
8852 kill_new_fork_children (int pid, struct remote_state *rs)
8853 {
8854 struct thread_info *thread;
8855 struct notif_client *notif = &notif_client_stop;
8856 struct queue_iter_param param;
8857
8858 /* Kill the fork child threads of any threads in process PID
8859 that are stopped at a fork event. */
8860 ALL_NON_EXITED_THREADS (thread)
8861 {
8862 struct target_waitstatus *ws = &thread->pending_follow;
8863
8864 if (is_pending_fork_parent (ws, pid, thread->ptid))
8865 {
8866 struct remote_state *rs = get_remote_state ();
8867 int child_pid = ptid_get_pid (ws->value.related_pid);
8868 int res;
8869
8870 res = remote_vkill (child_pid, rs);
8871 if (res != 0)
8872 error (_("Can't kill fork child process %d"), child_pid);
8873 }
8874 }
8875
8876 /* Check for any pending fork events (not reported or processed yet)
8877 in process PID and kill those fork child threads as well. */
8878 remote_notif_get_pending_events (notif);
8879 param.input = &pid;
8880 param.output = NULL;
8881 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8882 kill_child_of_pending_fork, &param);
8883 }
8884
8885 \f
8886 /* Target hook to kill the current inferior. */
8887
8888 static void
8889 remote_kill (struct target_ops *ops)
8890 {
8891 int res = -1;
8892 int pid = ptid_get_pid (inferior_ptid);
8893 struct remote_state *rs = get_remote_state ();
8894
8895 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
8896 {
8897 /* If we're stopped while forking and we haven't followed yet,
8898 kill the child task. We need to do this before killing the
8899 parent task because if this is a vfork then the parent will
8900 be sleeping. */
8901 kill_new_fork_children (pid, rs);
8902
8903 res = remote_vkill (pid, rs);
8904 if (res == 0)
8905 {
8906 target_mourn_inferior ();
8907 return;
8908 }
8909 }
8910
8911 /* If we are in 'target remote' mode and we are killing the only
8912 inferior, then we will tell gdbserver to exit and unpush the
8913 target. */
8914 if (res == -1 && !remote_multi_process_p (rs)
8915 && number_of_live_inferiors () == 1)
8916 {
8917 remote_kill_k ();
8918
8919 /* We've killed the remote end, we get to mourn it. If we are
8920 not in extended mode, mourning the inferior also unpushes
8921 remote_ops from the target stack, which closes the remote
8922 connection. */
8923 target_mourn_inferior ();
8924
8925 return;
8926 }
8927
8928 error (_("Can't kill process"));
8929 }
8930
8931 /* Send a kill request to the target using the 'vKill' packet. */
8932
8933 static int
8934 remote_vkill (int pid, struct remote_state *rs)
8935 {
8936 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8937 return -1;
8938
8939 /* Tell the remote target to detach. */
8940 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8941 putpkt (rs->buf);
8942 getpkt (&rs->buf, &rs->buf_size, 0);
8943
8944 switch (packet_ok (rs->buf,
8945 &remote_protocol_packets[PACKET_vKill]))
8946 {
8947 case PACKET_OK:
8948 return 0;
8949 case PACKET_ERROR:
8950 return 1;
8951 case PACKET_UNKNOWN:
8952 return -1;
8953 default:
8954 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8955 }
8956 }
8957
8958 /* Send a kill request to the target using the 'k' packet. */
8959
8960 static void
8961 remote_kill_k (void)
8962 {
8963 /* Catch errors so the user can quit from gdb even when we
8964 aren't on speaking terms with the remote system. */
8965 TRY
8966 {
8967 putpkt ("k");
8968 }
8969 CATCH (ex, RETURN_MASK_ERROR)
8970 {
8971 if (ex.error == TARGET_CLOSE_ERROR)
8972 {
8973 /* If we got an (EOF) error that caused the target
8974 to go away, then we're done, that's what we wanted.
8975 "k" is susceptible to cause a premature EOF, given
8976 that the remote server isn't actually required to
8977 reply to "k", and it can happen that it doesn't
8978 even get to reply ACK to the "k". */
8979 return;
8980 }
8981
8982 /* Otherwise, something went wrong. We didn't actually kill
8983 the target. Just propagate the exception, and let the
8984 user or higher layers decide what to do. */
8985 throw_exception (ex);
8986 }
8987 END_CATCH
8988 }
8989
8990 static void
8991 remote_mourn (struct target_ops *target)
8992 {
8993 struct remote_state *rs = get_remote_state ();
8994
8995 /* In 'target remote' mode with one inferior, we close the connection. */
8996 if (!rs->extended && number_of_live_inferiors () <= 1)
8997 {
8998 unpush_target (target);
8999
9000 /* remote_close takes care of doing most of the clean up. */
9001 generic_mourn_inferior ();
9002 return;
9003 }
9004
9005 /* In case we got here due to an error, but we're going to stay
9006 connected. */
9007 rs->waiting_for_stop_reply = 0;
9008
9009 /* If the current general thread belonged to the process we just
9010 detached from or has exited, the remote side current general
9011 thread becomes undefined. Considering a case like this:
9012
9013 - We just got here due to a detach.
9014 - The process that we're detaching from happens to immediately
9015 report a global breakpoint being hit in non-stop mode, in the
9016 same thread we had selected before.
9017 - GDB attaches to this process again.
9018 - This event happens to be the next event we handle.
9019
9020 GDB would consider that the current general thread didn't need to
9021 be set on the stub side (with Hg), since for all it knew,
9022 GENERAL_THREAD hadn't changed.
9023
9024 Notice that although in all-stop mode, the remote server always
9025 sets the current thread to the thread reporting the stop event,
9026 that doesn't happen in non-stop mode; in non-stop, the stub *must
9027 not* change the current thread when reporting a breakpoint hit,
9028 due to the decoupling of event reporting and event handling.
9029
9030 To keep things simple, we always invalidate our notion of the
9031 current thread. */
9032 record_currthread (rs, minus_one_ptid);
9033
9034 /* Call common code to mark the inferior as not running. */
9035 generic_mourn_inferior ();
9036
9037 if (!have_inferiors ())
9038 {
9039 if (!remote_multi_process_p (rs))
9040 {
9041 /* Check whether the target is running now - some remote stubs
9042 automatically restart after kill. */
9043 putpkt ("?");
9044 getpkt (&rs->buf, &rs->buf_size, 0);
9045
9046 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9047 {
9048 /* Assume that the target has been restarted. Set
9049 inferior_ptid so that bits of core GDB realizes
9050 there's something here, e.g., so that the user can
9051 say "kill" again. */
9052 inferior_ptid = magic_null_ptid;
9053 }
9054 }
9055 }
9056 }
9057
9058 static int
9059 extended_remote_supports_disable_randomization (struct target_ops *self)
9060 {
9061 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9062 }
9063
9064 static void
9065 extended_remote_disable_randomization (int val)
9066 {
9067 struct remote_state *rs = get_remote_state ();
9068 char *reply;
9069
9070 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9071 val);
9072 putpkt (rs->buf);
9073 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9074 if (*reply == '\0')
9075 error (_("Target does not support QDisableRandomization."));
9076 if (strcmp (reply, "OK") != 0)
9077 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9078 }
9079
9080 static int
9081 extended_remote_run (char *args)
9082 {
9083 struct remote_state *rs = get_remote_state ();
9084 int len;
9085 const char *remote_exec_file = get_remote_exec_file ();
9086
9087 /* If the user has disabled vRun support, or we have detected that
9088 support is not available, do not try it. */
9089 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9090 return -1;
9091
9092 strcpy (rs->buf, "vRun;");
9093 len = strlen (rs->buf);
9094
9095 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9096 error (_("Remote file name too long for run packet"));
9097 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9098 strlen (remote_exec_file));
9099
9100 gdb_assert (args != NULL);
9101 if (*args)
9102 {
9103 struct cleanup *back_to;
9104 int i;
9105 char **argv;
9106
9107 argv = gdb_buildargv (args);
9108 back_to = make_cleanup_freeargv (argv);
9109 for (i = 0; argv[i] != NULL; i++)
9110 {
9111 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9112 error (_("Argument list too long for run packet"));
9113 rs->buf[len++] = ';';
9114 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9115 strlen (argv[i]));
9116 }
9117 do_cleanups (back_to);
9118 }
9119
9120 rs->buf[len++] = '\0';
9121
9122 putpkt (rs->buf);
9123 getpkt (&rs->buf, &rs->buf_size, 0);
9124
9125 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9126 {
9127 case PACKET_OK:
9128 /* We have a wait response. All is well. */
9129 return 0;
9130 case PACKET_UNKNOWN:
9131 return -1;
9132 case PACKET_ERROR:
9133 if (remote_exec_file[0] == '\0')
9134 error (_("Running the default executable on the remote target failed; "
9135 "try \"set remote exec-file\"?"));
9136 else
9137 error (_("Running \"%s\" on the remote target failed"),
9138 remote_exec_file);
9139 default:
9140 gdb_assert_not_reached (_("bad switch"));
9141 }
9142 }
9143
9144 /* In the extended protocol we want to be able to do things like
9145 "run" and have them basically work as expected. So we need
9146 a special create_inferior function. We support changing the
9147 executable file and the command line arguments, but not the
9148 environment. */
9149
9150 static void
9151 extended_remote_create_inferior (struct target_ops *ops,
9152 char *exec_file, char *args,
9153 char **env, int from_tty)
9154 {
9155 int run_worked;
9156 char *stop_reply;
9157 struct remote_state *rs = get_remote_state ();
9158 const char *remote_exec_file = get_remote_exec_file ();
9159
9160 /* If running asynchronously, register the target file descriptor
9161 with the event loop. */
9162 if (target_can_async_p ())
9163 target_async (1);
9164
9165 /* Disable address space randomization if requested (and supported). */
9166 if (extended_remote_supports_disable_randomization (ops))
9167 extended_remote_disable_randomization (disable_randomization);
9168
9169 /* Now restart the remote server. */
9170 run_worked = extended_remote_run (args) != -1;
9171 if (!run_worked)
9172 {
9173 /* vRun was not supported. Fail if we need it to do what the
9174 user requested. */
9175 if (remote_exec_file[0])
9176 error (_("Remote target does not support \"set remote exec-file\""));
9177 if (args[0])
9178 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9179
9180 /* Fall back to "R". */
9181 extended_remote_restart ();
9182 }
9183
9184 if (!have_inferiors ())
9185 {
9186 /* Clean up from the last time we ran, before we mark the target
9187 running again. This will mark breakpoints uninserted, and
9188 get_offsets may insert breakpoints. */
9189 init_thread_list ();
9190 init_wait_for_inferior ();
9191 }
9192
9193 /* vRun's success return is a stop reply. */
9194 stop_reply = run_worked ? rs->buf : NULL;
9195 add_current_inferior_and_thread (stop_reply);
9196
9197 /* Get updated offsets, if the stub uses qOffsets. */
9198 get_offsets ();
9199 }
9200 \f
9201
9202 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9203 the list of conditions (in agent expression bytecode format), if any, the
9204 target needs to evaluate. The output is placed into the packet buffer
9205 started from BUF and ended at BUF_END. */
9206
9207 static int
9208 remote_add_target_side_condition (struct gdbarch *gdbarch,
9209 struct bp_target_info *bp_tgt, char *buf,
9210 char *buf_end)
9211 {
9212 struct agent_expr *aexpr = NULL;
9213 int i, ix;
9214
9215 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9216 return 0;
9217
9218 buf += strlen (buf);
9219 xsnprintf (buf, buf_end - buf, "%s", ";");
9220 buf++;
9221
9222 /* Send conditions to the target and free the vector. */
9223 for (ix = 0;
9224 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9225 ix++)
9226 {
9227 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9228 buf += strlen (buf);
9229 for (i = 0; i < aexpr->len; ++i)
9230 buf = pack_hex_byte (buf, aexpr->buf[i]);
9231 *buf = '\0';
9232 }
9233 return 0;
9234 }
9235
9236 static void
9237 remote_add_target_side_commands (struct gdbarch *gdbarch,
9238 struct bp_target_info *bp_tgt, char *buf)
9239 {
9240 struct agent_expr *aexpr = NULL;
9241 int i, ix;
9242
9243 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9244 return;
9245
9246 buf += strlen (buf);
9247
9248 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9249 buf += strlen (buf);
9250
9251 /* Concatenate all the agent expressions that are commands into the
9252 cmds parameter. */
9253 for (ix = 0;
9254 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9255 ix++)
9256 {
9257 sprintf (buf, "X%x,", aexpr->len);
9258 buf += strlen (buf);
9259 for (i = 0; i < aexpr->len; ++i)
9260 buf = pack_hex_byte (buf, aexpr->buf[i]);
9261 *buf = '\0';
9262 }
9263 }
9264
9265 /* Insert a breakpoint. On targets that have software breakpoint
9266 support, we ask the remote target to do the work; on targets
9267 which don't, we insert a traditional memory breakpoint. */
9268
9269 static int
9270 remote_insert_breakpoint (struct target_ops *ops,
9271 struct gdbarch *gdbarch,
9272 struct bp_target_info *bp_tgt)
9273 {
9274 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9275 If it succeeds, then set the support to PACKET_ENABLE. If it
9276 fails, and the user has explicitly requested the Z support then
9277 report an error, otherwise, mark it disabled and go on. */
9278
9279 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9280 {
9281 CORE_ADDR addr = bp_tgt->reqstd_address;
9282 struct remote_state *rs;
9283 char *p, *endbuf;
9284 int bpsize;
9285
9286 /* Make sure the remote is pointing at the right process, if
9287 necessary. */
9288 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9289 set_general_process ();
9290
9291 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9292
9293 rs = get_remote_state ();
9294 p = rs->buf;
9295 endbuf = rs->buf + get_remote_packet_size ();
9296
9297 *(p++) = 'Z';
9298 *(p++) = '0';
9299 *(p++) = ',';
9300 addr = (ULONGEST) remote_address_masked (addr);
9301 p += hexnumstr (p, addr);
9302 xsnprintf (p, endbuf - p, ",%d", bpsize);
9303
9304 if (remote_supports_cond_breakpoints (ops))
9305 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9306
9307 if (remote_can_run_breakpoint_commands (ops))
9308 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9309
9310 putpkt (rs->buf);
9311 getpkt (&rs->buf, &rs->buf_size, 0);
9312
9313 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9314 {
9315 case PACKET_ERROR:
9316 return -1;
9317 case PACKET_OK:
9318 bp_tgt->placed_address = addr;
9319 bp_tgt->placed_size = bpsize;
9320 return 0;
9321 case PACKET_UNKNOWN:
9322 break;
9323 }
9324 }
9325
9326 /* If this breakpoint has target-side commands but this stub doesn't
9327 support Z0 packets, throw error. */
9328 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9329 throw_error (NOT_SUPPORTED_ERROR, _("\
9330 Target doesn't support breakpoints that have target side commands."));
9331
9332 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9333 }
9334
9335 static int
9336 remote_remove_breakpoint (struct target_ops *ops,
9337 struct gdbarch *gdbarch,
9338 struct bp_target_info *bp_tgt)
9339 {
9340 CORE_ADDR addr = bp_tgt->placed_address;
9341 struct remote_state *rs = get_remote_state ();
9342
9343 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9344 {
9345 char *p = rs->buf;
9346 char *endbuf = rs->buf + get_remote_packet_size ();
9347
9348 /* Make sure the remote is pointing at the right process, if
9349 necessary. */
9350 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9351 set_general_process ();
9352
9353 *(p++) = 'z';
9354 *(p++) = '0';
9355 *(p++) = ',';
9356
9357 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9358 p += hexnumstr (p, addr);
9359 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9360
9361 putpkt (rs->buf);
9362 getpkt (&rs->buf, &rs->buf_size, 0);
9363
9364 return (rs->buf[0] == 'E');
9365 }
9366
9367 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9368 }
9369
9370 static enum Z_packet_type
9371 watchpoint_to_Z_packet (int type)
9372 {
9373 switch (type)
9374 {
9375 case hw_write:
9376 return Z_PACKET_WRITE_WP;
9377 break;
9378 case hw_read:
9379 return Z_PACKET_READ_WP;
9380 break;
9381 case hw_access:
9382 return Z_PACKET_ACCESS_WP;
9383 break;
9384 default:
9385 internal_error (__FILE__, __LINE__,
9386 _("hw_bp_to_z: bad watchpoint type %d"), type);
9387 }
9388 }
9389
9390 static int
9391 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9392 enum target_hw_bp_type type, struct expression *cond)
9393 {
9394 struct remote_state *rs = get_remote_state ();
9395 char *endbuf = rs->buf + get_remote_packet_size ();
9396 char *p;
9397 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9398
9399 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9400 return 1;
9401
9402 /* Make sure the remote is pointing at the right process, if
9403 necessary. */
9404 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9405 set_general_process ();
9406
9407 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9408 p = strchr (rs->buf, '\0');
9409 addr = remote_address_masked (addr);
9410 p += hexnumstr (p, (ULONGEST) addr);
9411 xsnprintf (p, endbuf - p, ",%x", len);
9412
9413 putpkt (rs->buf);
9414 getpkt (&rs->buf, &rs->buf_size, 0);
9415
9416 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9417 {
9418 case PACKET_ERROR:
9419 return -1;
9420 case PACKET_UNKNOWN:
9421 return 1;
9422 case PACKET_OK:
9423 return 0;
9424 }
9425 internal_error (__FILE__, __LINE__,
9426 _("remote_insert_watchpoint: reached end of function"));
9427 }
9428
9429 static int
9430 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9431 CORE_ADDR start, int length)
9432 {
9433 CORE_ADDR diff = remote_address_masked (addr - start);
9434
9435 return diff < length;
9436 }
9437
9438
9439 static int
9440 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9441 enum target_hw_bp_type type, struct expression *cond)
9442 {
9443 struct remote_state *rs = get_remote_state ();
9444 char *endbuf = rs->buf + get_remote_packet_size ();
9445 char *p;
9446 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9447
9448 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9449 return -1;
9450
9451 /* Make sure the remote is pointing at the right process, if
9452 necessary. */
9453 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9454 set_general_process ();
9455
9456 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9457 p = strchr (rs->buf, '\0');
9458 addr = remote_address_masked (addr);
9459 p += hexnumstr (p, (ULONGEST) addr);
9460 xsnprintf (p, endbuf - p, ",%x", len);
9461 putpkt (rs->buf);
9462 getpkt (&rs->buf, &rs->buf_size, 0);
9463
9464 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9465 {
9466 case PACKET_ERROR:
9467 case PACKET_UNKNOWN:
9468 return -1;
9469 case PACKET_OK:
9470 return 0;
9471 }
9472 internal_error (__FILE__, __LINE__,
9473 _("remote_remove_watchpoint: reached end of function"));
9474 }
9475
9476
9477 int remote_hw_watchpoint_limit = -1;
9478 int remote_hw_watchpoint_length_limit = -1;
9479 int remote_hw_breakpoint_limit = -1;
9480
9481 static int
9482 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9483 CORE_ADDR addr, int len)
9484 {
9485 if (remote_hw_watchpoint_length_limit == 0)
9486 return 0;
9487 else if (remote_hw_watchpoint_length_limit < 0)
9488 return 1;
9489 else if (len <= remote_hw_watchpoint_length_limit)
9490 return 1;
9491 else
9492 return 0;
9493 }
9494
9495 static int
9496 remote_check_watch_resources (struct target_ops *self,
9497 enum bptype type, int cnt, int ot)
9498 {
9499 if (type == bp_hardware_breakpoint)
9500 {
9501 if (remote_hw_breakpoint_limit == 0)
9502 return 0;
9503 else if (remote_hw_breakpoint_limit < 0)
9504 return 1;
9505 else if (cnt <= remote_hw_breakpoint_limit)
9506 return 1;
9507 }
9508 else
9509 {
9510 if (remote_hw_watchpoint_limit == 0)
9511 return 0;
9512 else if (remote_hw_watchpoint_limit < 0)
9513 return 1;
9514 else if (ot)
9515 return -1;
9516 else if (cnt <= remote_hw_watchpoint_limit)
9517 return 1;
9518 }
9519 return -1;
9520 }
9521
9522 /* The to_stopped_by_sw_breakpoint method of target remote. */
9523
9524 static int
9525 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9526 {
9527 struct thread_info *thread = inferior_thread ();
9528
9529 return (thread->priv != NULL
9530 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9531 }
9532
9533 /* The to_supports_stopped_by_sw_breakpoint method of target
9534 remote. */
9535
9536 static int
9537 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9538 {
9539 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9540 }
9541
9542 /* The to_stopped_by_hw_breakpoint method of target remote. */
9543
9544 static int
9545 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9546 {
9547 struct thread_info *thread = inferior_thread ();
9548
9549 return (thread->priv != NULL
9550 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9551 }
9552
9553 /* The to_supports_stopped_by_hw_breakpoint method of target
9554 remote. */
9555
9556 static int
9557 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9558 {
9559 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9560 }
9561
9562 static int
9563 remote_stopped_by_watchpoint (struct target_ops *ops)
9564 {
9565 struct thread_info *thread = inferior_thread ();
9566
9567 return (thread->priv != NULL
9568 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9569 }
9570
9571 static int
9572 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9573 {
9574 struct thread_info *thread = inferior_thread ();
9575
9576 if (thread->priv != NULL
9577 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9578 {
9579 *addr_p = thread->priv->watch_data_address;
9580 return 1;
9581 }
9582
9583 return 0;
9584 }
9585
9586
9587 static int
9588 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9589 struct bp_target_info *bp_tgt)
9590 {
9591 CORE_ADDR addr = bp_tgt->reqstd_address;
9592 struct remote_state *rs;
9593 char *p, *endbuf;
9594 char *message;
9595 int bpsize;
9596
9597 /* The length field should be set to the size of a breakpoint
9598 instruction, even though we aren't inserting one ourselves. */
9599
9600 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9601
9602 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9603 return -1;
9604
9605 /* Make sure the remote is pointing at the right process, if
9606 necessary. */
9607 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9608 set_general_process ();
9609
9610 rs = get_remote_state ();
9611 p = rs->buf;
9612 endbuf = rs->buf + get_remote_packet_size ();
9613
9614 *(p++) = 'Z';
9615 *(p++) = '1';
9616 *(p++) = ',';
9617
9618 addr = remote_address_masked (addr);
9619 p += hexnumstr (p, (ULONGEST) addr);
9620 xsnprintf (p, endbuf - p, ",%x", bpsize);
9621
9622 if (remote_supports_cond_breakpoints (self))
9623 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9624
9625 if (remote_can_run_breakpoint_commands (self))
9626 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9627
9628 putpkt (rs->buf);
9629 getpkt (&rs->buf, &rs->buf_size, 0);
9630
9631 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9632 {
9633 case PACKET_ERROR:
9634 if (rs->buf[1] == '.')
9635 {
9636 message = strchr (rs->buf + 2, '.');
9637 if (message)
9638 error (_("Remote failure reply: %s"), message + 1);
9639 }
9640 return -1;
9641 case PACKET_UNKNOWN:
9642 return -1;
9643 case PACKET_OK:
9644 bp_tgt->placed_address = addr;
9645 bp_tgt->placed_size = bpsize;
9646 return 0;
9647 }
9648 internal_error (__FILE__, __LINE__,
9649 _("remote_insert_hw_breakpoint: reached end of function"));
9650 }
9651
9652
9653 static int
9654 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9655 struct bp_target_info *bp_tgt)
9656 {
9657 CORE_ADDR addr;
9658 struct remote_state *rs = get_remote_state ();
9659 char *p = rs->buf;
9660 char *endbuf = rs->buf + get_remote_packet_size ();
9661
9662 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9663 return -1;
9664
9665 /* Make sure the remote is pointing at the right process, if
9666 necessary. */
9667 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9668 set_general_process ();
9669
9670 *(p++) = 'z';
9671 *(p++) = '1';
9672 *(p++) = ',';
9673
9674 addr = remote_address_masked (bp_tgt->placed_address);
9675 p += hexnumstr (p, (ULONGEST) addr);
9676 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9677
9678 putpkt (rs->buf);
9679 getpkt (&rs->buf, &rs->buf_size, 0);
9680
9681 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9682 {
9683 case PACKET_ERROR:
9684 case PACKET_UNKNOWN:
9685 return -1;
9686 case PACKET_OK:
9687 return 0;
9688 }
9689 internal_error (__FILE__, __LINE__,
9690 _("remote_remove_hw_breakpoint: reached end of function"));
9691 }
9692
9693 /* Verify memory using the "qCRC:" request. */
9694
9695 static int
9696 remote_verify_memory (struct target_ops *ops,
9697 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9698 {
9699 struct remote_state *rs = get_remote_state ();
9700 unsigned long host_crc, target_crc;
9701 char *tmp;
9702
9703 /* It doesn't make sense to use qCRC if the remote target is
9704 connected but not running. */
9705 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9706 {
9707 enum packet_result result;
9708
9709 /* Make sure the remote is pointing at the right process. */
9710 set_general_process ();
9711
9712 /* FIXME: assumes lma can fit into long. */
9713 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9714 (long) lma, (long) size);
9715 putpkt (rs->buf);
9716
9717 /* Be clever; compute the host_crc before waiting for target
9718 reply. */
9719 host_crc = xcrc32 (data, size, 0xffffffff);
9720
9721 getpkt (&rs->buf, &rs->buf_size, 0);
9722
9723 result = packet_ok (rs->buf,
9724 &remote_protocol_packets[PACKET_qCRC]);
9725 if (result == PACKET_ERROR)
9726 return -1;
9727 else if (result == PACKET_OK)
9728 {
9729 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9730 target_crc = target_crc * 16 + fromhex (*tmp);
9731
9732 return (host_crc == target_crc);
9733 }
9734 }
9735
9736 return simple_verify_memory (ops, data, lma, size);
9737 }
9738
9739 /* compare-sections command
9740
9741 With no arguments, compares each loadable section in the exec bfd
9742 with the same memory range on the target, and reports mismatches.
9743 Useful for verifying the image on the target against the exec file. */
9744
9745 static void
9746 compare_sections_command (char *args, int from_tty)
9747 {
9748 asection *s;
9749 struct cleanup *old_chain;
9750 gdb_byte *sectdata;
9751 const char *sectname;
9752 bfd_size_type size;
9753 bfd_vma lma;
9754 int matched = 0;
9755 int mismatched = 0;
9756 int res;
9757 int read_only = 0;
9758
9759 if (!exec_bfd)
9760 error (_("command cannot be used without an exec file"));
9761
9762 /* Make sure the remote is pointing at the right process. */
9763 set_general_process ();
9764
9765 if (args != NULL && strcmp (args, "-r") == 0)
9766 {
9767 read_only = 1;
9768 args = NULL;
9769 }
9770
9771 for (s = exec_bfd->sections; s; s = s->next)
9772 {
9773 if (!(s->flags & SEC_LOAD))
9774 continue; /* Skip non-loadable section. */
9775
9776 if (read_only && (s->flags & SEC_READONLY) == 0)
9777 continue; /* Skip writeable sections */
9778
9779 size = bfd_get_section_size (s);
9780 if (size == 0)
9781 continue; /* Skip zero-length section. */
9782
9783 sectname = bfd_get_section_name (exec_bfd, s);
9784 if (args && strcmp (args, sectname) != 0)
9785 continue; /* Not the section selected by user. */
9786
9787 matched = 1; /* Do this section. */
9788 lma = s->lma;
9789
9790 sectdata = (gdb_byte *) xmalloc (size);
9791 old_chain = make_cleanup (xfree, sectdata);
9792 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9793
9794 res = target_verify_memory (sectdata, lma, size);
9795
9796 if (res == -1)
9797 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9798 paddress (target_gdbarch (), lma),
9799 paddress (target_gdbarch (), lma + size));
9800
9801 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9802 paddress (target_gdbarch (), lma),
9803 paddress (target_gdbarch (), lma + size));
9804 if (res)
9805 printf_filtered ("matched.\n");
9806 else
9807 {
9808 printf_filtered ("MIS-MATCHED!\n");
9809 mismatched++;
9810 }
9811
9812 do_cleanups (old_chain);
9813 }
9814 if (mismatched > 0)
9815 warning (_("One or more sections of the target image does not match\n\
9816 the loaded file\n"));
9817 if (args && !matched)
9818 printf_filtered (_("No loaded section named '%s'.\n"), args);
9819 }
9820
9821 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9822 into remote target. The number of bytes written to the remote
9823 target is returned, or -1 for error. */
9824
9825 static enum target_xfer_status
9826 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9827 const char *annex, const gdb_byte *writebuf,
9828 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9829 struct packet_config *packet)
9830 {
9831 int i, buf_len;
9832 ULONGEST n;
9833 struct remote_state *rs = get_remote_state ();
9834 int max_size = get_memory_write_packet_size ();
9835
9836 if (packet->support == PACKET_DISABLE)
9837 return TARGET_XFER_E_IO;
9838
9839 /* Insert header. */
9840 i = snprintf (rs->buf, max_size,
9841 "qXfer:%s:write:%s:%s:",
9842 object_name, annex ? annex : "",
9843 phex_nz (offset, sizeof offset));
9844 max_size -= (i + 1);
9845
9846 /* Escape as much data as fits into rs->buf. */
9847 buf_len = remote_escape_output
9848 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9849
9850 if (putpkt_binary (rs->buf, i + buf_len) < 0
9851 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9852 || packet_ok (rs->buf, packet) != PACKET_OK)
9853 return TARGET_XFER_E_IO;
9854
9855 unpack_varlen_hex (rs->buf, &n);
9856
9857 *xfered_len = n;
9858 return TARGET_XFER_OK;
9859 }
9860
9861 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9862 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9863 number of bytes read is returned, or 0 for EOF, or -1 for error.
9864 The number of bytes read may be less than LEN without indicating an
9865 EOF. PACKET is checked and updated to indicate whether the remote
9866 target supports this object. */
9867
9868 static enum target_xfer_status
9869 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9870 const char *annex,
9871 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9872 ULONGEST *xfered_len,
9873 struct packet_config *packet)
9874 {
9875 struct remote_state *rs = get_remote_state ();
9876 LONGEST i, n, packet_len;
9877
9878 if (packet->support == PACKET_DISABLE)
9879 return TARGET_XFER_E_IO;
9880
9881 /* Check whether we've cached an end-of-object packet that matches
9882 this request. */
9883 if (rs->finished_object)
9884 {
9885 if (strcmp (object_name, rs->finished_object) == 0
9886 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9887 && offset == rs->finished_offset)
9888 return TARGET_XFER_EOF;
9889
9890
9891 /* Otherwise, we're now reading something different. Discard
9892 the cache. */
9893 xfree (rs->finished_object);
9894 xfree (rs->finished_annex);
9895 rs->finished_object = NULL;
9896 rs->finished_annex = NULL;
9897 }
9898
9899 /* Request only enough to fit in a single packet. The actual data
9900 may not, since we don't know how much of it will need to be escaped;
9901 the target is free to respond with slightly less data. We subtract
9902 five to account for the response type and the protocol frame. */
9903 n = min (get_remote_packet_size () - 5, len);
9904 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9905 object_name, annex ? annex : "",
9906 phex_nz (offset, sizeof offset),
9907 phex_nz (n, sizeof n));
9908 i = putpkt (rs->buf);
9909 if (i < 0)
9910 return TARGET_XFER_E_IO;
9911
9912 rs->buf[0] = '\0';
9913 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9914 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9915 return TARGET_XFER_E_IO;
9916
9917 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9918 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9919
9920 /* 'm' means there is (or at least might be) more data after this
9921 batch. That does not make sense unless there's at least one byte
9922 of data in this reply. */
9923 if (rs->buf[0] == 'm' && packet_len == 1)
9924 error (_("Remote qXfer reply contained no data."));
9925
9926 /* Got some data. */
9927 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9928 packet_len - 1, readbuf, n);
9929
9930 /* 'l' is an EOF marker, possibly including a final block of data,
9931 or possibly empty. If we have the final block of a non-empty
9932 object, record this fact to bypass a subsequent partial read. */
9933 if (rs->buf[0] == 'l' && offset + i > 0)
9934 {
9935 rs->finished_object = xstrdup (object_name);
9936 rs->finished_annex = xstrdup (annex ? annex : "");
9937 rs->finished_offset = offset + i;
9938 }
9939
9940 if (i == 0)
9941 return TARGET_XFER_EOF;
9942 else
9943 {
9944 *xfered_len = i;
9945 return TARGET_XFER_OK;
9946 }
9947 }
9948
9949 static enum target_xfer_status
9950 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9951 const char *annex, gdb_byte *readbuf,
9952 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9953 ULONGEST *xfered_len)
9954 {
9955 struct remote_state *rs;
9956 int i;
9957 char *p2;
9958 char query_type;
9959 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9960
9961 set_remote_traceframe ();
9962 set_general_thread (inferior_ptid);
9963
9964 rs = get_remote_state ();
9965
9966 /* Handle memory using the standard memory routines. */
9967 if (object == TARGET_OBJECT_MEMORY)
9968 {
9969 /* If the remote target is connected but not running, we should
9970 pass this request down to a lower stratum (e.g. the executable
9971 file). */
9972 if (!target_has_execution)
9973 return TARGET_XFER_EOF;
9974
9975 if (writebuf != NULL)
9976 return remote_write_bytes (offset, writebuf, len, unit_size,
9977 xfered_len);
9978 else
9979 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9980 xfered_len);
9981 }
9982
9983 /* Handle SPU memory using qxfer packets. */
9984 if (object == TARGET_OBJECT_SPU)
9985 {
9986 if (readbuf)
9987 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9988 xfered_len, &remote_protocol_packets
9989 [PACKET_qXfer_spu_read]);
9990 else
9991 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9992 xfered_len, &remote_protocol_packets
9993 [PACKET_qXfer_spu_write]);
9994 }
9995
9996 /* Handle extra signal info using qxfer packets. */
9997 if (object == TARGET_OBJECT_SIGNAL_INFO)
9998 {
9999 if (readbuf)
10000 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10001 xfered_len, &remote_protocol_packets
10002 [PACKET_qXfer_siginfo_read]);
10003 else
10004 return remote_write_qxfer (ops, "siginfo", annex,
10005 writebuf, offset, len, xfered_len,
10006 &remote_protocol_packets
10007 [PACKET_qXfer_siginfo_write]);
10008 }
10009
10010 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10011 {
10012 if (readbuf)
10013 return remote_read_qxfer (ops, "statictrace", annex,
10014 readbuf, offset, len, xfered_len,
10015 &remote_protocol_packets
10016 [PACKET_qXfer_statictrace_read]);
10017 else
10018 return TARGET_XFER_E_IO;
10019 }
10020
10021 /* Only handle flash writes. */
10022 if (writebuf != NULL)
10023 {
10024 switch (object)
10025 {
10026 case TARGET_OBJECT_FLASH:
10027 return remote_flash_write (ops, offset, len, xfered_len,
10028 writebuf);
10029
10030 default:
10031 return TARGET_XFER_E_IO;
10032 }
10033 }
10034
10035 /* Map pre-existing objects onto letters. DO NOT do this for new
10036 objects!!! Instead specify new query packets. */
10037 switch (object)
10038 {
10039 case TARGET_OBJECT_AVR:
10040 query_type = 'R';
10041 break;
10042
10043 case TARGET_OBJECT_AUXV:
10044 gdb_assert (annex == NULL);
10045 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10046 xfered_len,
10047 &remote_protocol_packets[PACKET_qXfer_auxv]);
10048
10049 case TARGET_OBJECT_AVAILABLE_FEATURES:
10050 return remote_read_qxfer
10051 (ops, "features", annex, readbuf, offset, len, xfered_len,
10052 &remote_protocol_packets[PACKET_qXfer_features]);
10053
10054 case TARGET_OBJECT_LIBRARIES:
10055 return remote_read_qxfer
10056 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10057 &remote_protocol_packets[PACKET_qXfer_libraries]);
10058
10059 case TARGET_OBJECT_LIBRARIES_SVR4:
10060 return remote_read_qxfer
10061 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10062 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10063
10064 case TARGET_OBJECT_MEMORY_MAP:
10065 gdb_assert (annex == NULL);
10066 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10067 xfered_len,
10068 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10069
10070 case TARGET_OBJECT_OSDATA:
10071 /* Should only get here if we're connected. */
10072 gdb_assert (rs->remote_desc);
10073 return remote_read_qxfer
10074 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10075 &remote_protocol_packets[PACKET_qXfer_osdata]);
10076
10077 case TARGET_OBJECT_THREADS:
10078 gdb_assert (annex == NULL);
10079 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10080 xfered_len,
10081 &remote_protocol_packets[PACKET_qXfer_threads]);
10082
10083 case TARGET_OBJECT_TRACEFRAME_INFO:
10084 gdb_assert (annex == NULL);
10085 return remote_read_qxfer
10086 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10087 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10088
10089 case TARGET_OBJECT_FDPIC:
10090 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10091 xfered_len,
10092 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10093
10094 case TARGET_OBJECT_OPENVMS_UIB:
10095 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10096 xfered_len,
10097 &remote_protocol_packets[PACKET_qXfer_uib]);
10098
10099 case TARGET_OBJECT_BTRACE:
10100 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10101 xfered_len,
10102 &remote_protocol_packets[PACKET_qXfer_btrace]);
10103
10104 case TARGET_OBJECT_BTRACE_CONF:
10105 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10106 len, xfered_len,
10107 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10108
10109 case TARGET_OBJECT_EXEC_FILE:
10110 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10111 len, xfered_len,
10112 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10113
10114 default:
10115 return TARGET_XFER_E_IO;
10116 }
10117
10118 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10119 large enough let the caller deal with it. */
10120 if (len < get_remote_packet_size ())
10121 return TARGET_XFER_E_IO;
10122 len = get_remote_packet_size ();
10123
10124 /* Except for querying the minimum buffer size, target must be open. */
10125 if (!rs->remote_desc)
10126 error (_("remote query is only available after target open"));
10127
10128 gdb_assert (annex != NULL);
10129 gdb_assert (readbuf != NULL);
10130
10131 p2 = rs->buf;
10132 *p2++ = 'q';
10133 *p2++ = query_type;
10134
10135 /* We used one buffer char for the remote protocol q command and
10136 another for the query type. As the remote protocol encapsulation
10137 uses 4 chars plus one extra in case we are debugging
10138 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10139 string. */
10140 i = 0;
10141 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10142 {
10143 /* Bad caller may have sent forbidden characters. */
10144 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10145 *p2++ = annex[i];
10146 i++;
10147 }
10148 *p2 = '\0';
10149 gdb_assert (annex[i] == '\0');
10150
10151 i = putpkt (rs->buf);
10152 if (i < 0)
10153 return TARGET_XFER_E_IO;
10154
10155 getpkt (&rs->buf, &rs->buf_size, 0);
10156 strcpy ((char *) readbuf, rs->buf);
10157
10158 *xfered_len = strlen ((char *) readbuf);
10159 return TARGET_XFER_OK;
10160 }
10161
10162 /* Implementation of to_get_memory_xfer_limit. */
10163
10164 static ULONGEST
10165 remote_get_memory_xfer_limit (struct target_ops *ops)
10166 {
10167 return get_memory_write_packet_size ();
10168 }
10169
10170 static int
10171 remote_search_memory (struct target_ops* ops,
10172 CORE_ADDR start_addr, ULONGEST search_space_len,
10173 const gdb_byte *pattern, ULONGEST pattern_len,
10174 CORE_ADDR *found_addrp)
10175 {
10176 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10177 struct remote_state *rs = get_remote_state ();
10178 int max_size = get_memory_write_packet_size ();
10179 struct packet_config *packet =
10180 &remote_protocol_packets[PACKET_qSearch_memory];
10181 /* Number of packet bytes used to encode the pattern;
10182 this could be more than PATTERN_LEN due to escape characters. */
10183 int escaped_pattern_len;
10184 /* Amount of pattern that was encodable in the packet. */
10185 int used_pattern_len;
10186 int i;
10187 int found;
10188 ULONGEST found_addr;
10189
10190 /* Don't go to the target if we don't have to.
10191 This is done before checking packet->support to avoid the possibility that
10192 a success for this edge case means the facility works in general. */
10193 if (pattern_len > search_space_len)
10194 return 0;
10195 if (pattern_len == 0)
10196 {
10197 *found_addrp = start_addr;
10198 return 1;
10199 }
10200
10201 /* If we already know the packet isn't supported, fall back to the simple
10202 way of searching memory. */
10203
10204 if (packet_config_support (packet) == PACKET_DISABLE)
10205 {
10206 /* Target doesn't provided special support, fall back and use the
10207 standard support (copy memory and do the search here). */
10208 return simple_search_memory (ops, start_addr, search_space_len,
10209 pattern, pattern_len, found_addrp);
10210 }
10211
10212 /* Make sure the remote is pointing at the right process. */
10213 set_general_process ();
10214
10215 /* Insert header. */
10216 i = snprintf (rs->buf, max_size,
10217 "qSearch:memory:%s;%s;",
10218 phex_nz (start_addr, addr_size),
10219 phex_nz (search_space_len, sizeof (search_space_len)));
10220 max_size -= (i + 1);
10221
10222 /* Escape as much data as fits into rs->buf. */
10223 escaped_pattern_len =
10224 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10225 &used_pattern_len, max_size);
10226
10227 /* Bail if the pattern is too large. */
10228 if (used_pattern_len != pattern_len)
10229 error (_("Pattern is too large to transmit to remote target."));
10230
10231 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10232 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10233 || packet_ok (rs->buf, packet) != PACKET_OK)
10234 {
10235 /* The request may not have worked because the command is not
10236 supported. If so, fall back to the simple way. */
10237 if (packet->support == PACKET_DISABLE)
10238 {
10239 return simple_search_memory (ops, start_addr, search_space_len,
10240 pattern, pattern_len, found_addrp);
10241 }
10242 return -1;
10243 }
10244
10245 if (rs->buf[0] == '0')
10246 found = 0;
10247 else if (rs->buf[0] == '1')
10248 {
10249 found = 1;
10250 if (rs->buf[1] != ',')
10251 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10252 unpack_varlen_hex (rs->buf + 2, &found_addr);
10253 *found_addrp = found_addr;
10254 }
10255 else
10256 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10257
10258 return found;
10259 }
10260
10261 static void
10262 remote_rcmd (struct target_ops *self, const char *command,
10263 struct ui_file *outbuf)
10264 {
10265 struct remote_state *rs = get_remote_state ();
10266 char *p = rs->buf;
10267
10268 if (!rs->remote_desc)
10269 error (_("remote rcmd is only available after target open"));
10270
10271 /* Send a NULL command across as an empty command. */
10272 if (command == NULL)
10273 command = "";
10274
10275 /* The query prefix. */
10276 strcpy (rs->buf, "qRcmd,");
10277 p = strchr (rs->buf, '\0');
10278
10279 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10280 > get_remote_packet_size ())
10281 error (_("\"monitor\" command ``%s'' is too long."), command);
10282
10283 /* Encode the actual command. */
10284 bin2hex ((const gdb_byte *) command, p, strlen (command));
10285
10286 if (putpkt (rs->buf) < 0)
10287 error (_("Communication problem with target."));
10288
10289 /* get/display the response */
10290 while (1)
10291 {
10292 char *buf;
10293
10294 /* XXX - see also remote_get_noisy_reply(). */
10295 QUIT; /* Allow user to bail out with ^C. */
10296 rs->buf[0] = '\0';
10297 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10298 {
10299 /* Timeout. Continue to (try to) read responses.
10300 This is better than stopping with an error, assuming the stub
10301 is still executing the (long) monitor command.
10302 If needed, the user can interrupt gdb using C-c, obtaining
10303 an effect similar to stop on timeout. */
10304 continue;
10305 }
10306 buf = rs->buf;
10307 if (buf[0] == '\0')
10308 error (_("Target does not support this command."));
10309 if (buf[0] == 'O' && buf[1] != 'K')
10310 {
10311 remote_console_output (buf + 1); /* 'O' message from stub. */
10312 continue;
10313 }
10314 if (strcmp (buf, "OK") == 0)
10315 break;
10316 if (strlen (buf) == 3 && buf[0] == 'E'
10317 && isdigit (buf[1]) && isdigit (buf[2]))
10318 {
10319 error (_("Protocol error with Rcmd"));
10320 }
10321 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10322 {
10323 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10324
10325 fputc_unfiltered (c, outbuf);
10326 }
10327 break;
10328 }
10329 }
10330
10331 static VEC(mem_region_s) *
10332 remote_memory_map (struct target_ops *ops)
10333 {
10334 VEC(mem_region_s) *result = NULL;
10335 char *text = target_read_stralloc (&current_target,
10336 TARGET_OBJECT_MEMORY_MAP, NULL);
10337
10338 if (text)
10339 {
10340 struct cleanup *back_to = make_cleanup (xfree, text);
10341
10342 result = parse_memory_map (text);
10343 do_cleanups (back_to);
10344 }
10345
10346 return result;
10347 }
10348
10349 static void
10350 packet_command (char *args, int from_tty)
10351 {
10352 struct remote_state *rs = get_remote_state ();
10353
10354 if (!rs->remote_desc)
10355 error (_("command can only be used with remote target"));
10356
10357 if (!args)
10358 error (_("remote-packet command requires packet text as argument"));
10359
10360 puts_filtered ("sending: ");
10361 print_packet (args);
10362 puts_filtered ("\n");
10363 putpkt (args);
10364
10365 getpkt (&rs->buf, &rs->buf_size, 0);
10366 puts_filtered ("received: ");
10367 print_packet (rs->buf);
10368 puts_filtered ("\n");
10369 }
10370
10371 #if 0
10372 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10373
10374 static void display_thread_info (struct gdb_ext_thread_info *info);
10375
10376 static void threadset_test_cmd (char *cmd, int tty);
10377
10378 static void threadalive_test (char *cmd, int tty);
10379
10380 static void threadlist_test_cmd (char *cmd, int tty);
10381
10382 int get_and_display_threadinfo (threadref *ref);
10383
10384 static void threadinfo_test_cmd (char *cmd, int tty);
10385
10386 static int thread_display_step (threadref *ref, void *context);
10387
10388 static void threadlist_update_test_cmd (char *cmd, int tty);
10389
10390 static void init_remote_threadtests (void);
10391
10392 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10393
10394 static void
10395 threadset_test_cmd (char *cmd, int tty)
10396 {
10397 int sample_thread = SAMPLE_THREAD;
10398
10399 printf_filtered (_("Remote threadset test\n"));
10400 set_general_thread (sample_thread);
10401 }
10402
10403
10404 static void
10405 threadalive_test (char *cmd, int tty)
10406 {
10407 int sample_thread = SAMPLE_THREAD;
10408 int pid = ptid_get_pid (inferior_ptid);
10409 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10410
10411 if (remote_thread_alive (ptid))
10412 printf_filtered ("PASS: Thread alive test\n");
10413 else
10414 printf_filtered ("FAIL: Thread alive test\n");
10415 }
10416
10417 void output_threadid (char *title, threadref *ref);
10418
10419 void
10420 output_threadid (char *title, threadref *ref)
10421 {
10422 char hexid[20];
10423
10424 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10425 hexid[16] = 0;
10426 printf_filtered ("%s %s\n", title, (&hexid[0]));
10427 }
10428
10429 static void
10430 threadlist_test_cmd (char *cmd, int tty)
10431 {
10432 int startflag = 1;
10433 threadref nextthread;
10434 int done, result_count;
10435 threadref threadlist[3];
10436
10437 printf_filtered ("Remote Threadlist test\n");
10438 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10439 &result_count, &threadlist[0]))
10440 printf_filtered ("FAIL: threadlist test\n");
10441 else
10442 {
10443 threadref *scan = threadlist;
10444 threadref *limit = scan + result_count;
10445
10446 while (scan < limit)
10447 output_threadid (" thread ", scan++);
10448 }
10449 }
10450
10451 void
10452 display_thread_info (struct gdb_ext_thread_info *info)
10453 {
10454 output_threadid ("Threadid: ", &info->threadid);
10455 printf_filtered ("Name: %s\n ", info->shortname);
10456 printf_filtered ("State: %s\n", info->display);
10457 printf_filtered ("other: %s\n\n", info->more_display);
10458 }
10459
10460 int
10461 get_and_display_threadinfo (threadref *ref)
10462 {
10463 int result;
10464 int set;
10465 struct gdb_ext_thread_info threadinfo;
10466
10467 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10468 | TAG_MOREDISPLAY | TAG_DISPLAY;
10469 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10470 display_thread_info (&threadinfo);
10471 return result;
10472 }
10473
10474 static void
10475 threadinfo_test_cmd (char *cmd, int tty)
10476 {
10477 int athread = SAMPLE_THREAD;
10478 threadref thread;
10479 int set;
10480
10481 int_to_threadref (&thread, athread);
10482 printf_filtered ("Remote Threadinfo test\n");
10483 if (!get_and_display_threadinfo (&thread))
10484 printf_filtered ("FAIL cannot get thread info\n");
10485 }
10486
10487 static int
10488 thread_display_step (threadref *ref, void *context)
10489 {
10490 /* output_threadid(" threadstep ",ref); *//* simple test */
10491 return get_and_display_threadinfo (ref);
10492 }
10493
10494 static void
10495 threadlist_update_test_cmd (char *cmd, int tty)
10496 {
10497 printf_filtered ("Remote Threadlist update test\n");
10498 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10499 }
10500
10501 static void
10502 init_remote_threadtests (void)
10503 {
10504 add_com ("tlist", class_obscure, threadlist_test_cmd,
10505 _("Fetch and print the remote list of "
10506 "thread identifiers, one pkt only"));
10507 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10508 _("Fetch and display info about one thread"));
10509 add_com ("tset", class_obscure, threadset_test_cmd,
10510 _("Test setting to a different thread"));
10511 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10512 _("Iterate through updating all remote thread info"));
10513 add_com ("talive", class_obscure, threadalive_test,
10514 _(" Remote thread alive test "));
10515 }
10516
10517 #endif /* 0 */
10518
10519 /* Convert a thread ID to a string. Returns the string in a static
10520 buffer. */
10521
10522 static char *
10523 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10524 {
10525 static char buf[64];
10526 struct remote_state *rs = get_remote_state ();
10527
10528 if (ptid_equal (ptid, null_ptid))
10529 return normal_pid_to_str (ptid);
10530 else if (ptid_is_pid (ptid))
10531 {
10532 /* Printing an inferior target id. */
10533
10534 /* When multi-process extensions are off, there's no way in the
10535 remote protocol to know the remote process id, if there's any
10536 at all. There's one exception --- when we're connected with
10537 target extended-remote, and we manually attached to a process
10538 with "attach PID". We don't record anywhere a flag that
10539 allows us to distinguish that case from the case of
10540 connecting with extended-remote and the stub already being
10541 attached to a process, and reporting yes to qAttached, hence
10542 no smart special casing here. */
10543 if (!remote_multi_process_p (rs))
10544 {
10545 xsnprintf (buf, sizeof buf, "Remote target");
10546 return buf;
10547 }
10548
10549 return normal_pid_to_str (ptid);
10550 }
10551 else
10552 {
10553 if (ptid_equal (magic_null_ptid, ptid))
10554 xsnprintf (buf, sizeof buf, "Thread <main>");
10555 else if (remote_multi_process_p (rs))
10556 if (ptid_get_lwp (ptid) == 0)
10557 return normal_pid_to_str (ptid);
10558 else
10559 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10560 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10561 else
10562 xsnprintf (buf, sizeof buf, "Thread %ld",
10563 ptid_get_lwp (ptid));
10564 return buf;
10565 }
10566 }
10567
10568 /* Get the address of the thread local variable in OBJFILE which is
10569 stored at OFFSET within the thread local storage for thread PTID. */
10570
10571 static CORE_ADDR
10572 remote_get_thread_local_address (struct target_ops *ops,
10573 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10574 {
10575 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10576 {
10577 struct remote_state *rs = get_remote_state ();
10578 char *p = rs->buf;
10579 char *endp = rs->buf + get_remote_packet_size ();
10580 enum packet_result result;
10581
10582 strcpy (p, "qGetTLSAddr:");
10583 p += strlen (p);
10584 p = write_ptid (p, endp, ptid);
10585 *p++ = ',';
10586 p += hexnumstr (p, offset);
10587 *p++ = ',';
10588 p += hexnumstr (p, lm);
10589 *p++ = '\0';
10590
10591 putpkt (rs->buf);
10592 getpkt (&rs->buf, &rs->buf_size, 0);
10593 result = packet_ok (rs->buf,
10594 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10595 if (result == PACKET_OK)
10596 {
10597 ULONGEST result;
10598
10599 unpack_varlen_hex (rs->buf, &result);
10600 return result;
10601 }
10602 else if (result == PACKET_UNKNOWN)
10603 throw_error (TLS_GENERIC_ERROR,
10604 _("Remote target doesn't support qGetTLSAddr packet"));
10605 else
10606 throw_error (TLS_GENERIC_ERROR,
10607 _("Remote target failed to process qGetTLSAddr request"));
10608 }
10609 else
10610 throw_error (TLS_GENERIC_ERROR,
10611 _("TLS not supported or disabled on this target"));
10612 /* Not reached. */
10613 return 0;
10614 }
10615
10616 /* Provide thread local base, i.e. Thread Information Block address.
10617 Returns 1 if ptid is found and thread_local_base is non zero. */
10618
10619 static int
10620 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10621 {
10622 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10623 {
10624 struct remote_state *rs = get_remote_state ();
10625 char *p = rs->buf;
10626 char *endp = rs->buf + get_remote_packet_size ();
10627 enum packet_result result;
10628
10629 strcpy (p, "qGetTIBAddr:");
10630 p += strlen (p);
10631 p = write_ptid (p, endp, ptid);
10632 *p++ = '\0';
10633
10634 putpkt (rs->buf);
10635 getpkt (&rs->buf, &rs->buf_size, 0);
10636 result = packet_ok (rs->buf,
10637 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10638 if (result == PACKET_OK)
10639 {
10640 ULONGEST result;
10641
10642 unpack_varlen_hex (rs->buf, &result);
10643 if (addr)
10644 *addr = (CORE_ADDR) result;
10645 return 1;
10646 }
10647 else if (result == PACKET_UNKNOWN)
10648 error (_("Remote target doesn't support qGetTIBAddr packet"));
10649 else
10650 error (_("Remote target failed to process qGetTIBAddr request"));
10651 }
10652 else
10653 error (_("qGetTIBAddr not supported or disabled on this target"));
10654 /* Not reached. */
10655 return 0;
10656 }
10657
10658 /* Support for inferring a target description based on the current
10659 architecture and the size of a 'g' packet. While the 'g' packet
10660 can have any size (since optional registers can be left off the
10661 end), some sizes are easily recognizable given knowledge of the
10662 approximate architecture. */
10663
10664 struct remote_g_packet_guess
10665 {
10666 int bytes;
10667 const struct target_desc *tdesc;
10668 };
10669 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10670 DEF_VEC_O(remote_g_packet_guess_s);
10671
10672 struct remote_g_packet_data
10673 {
10674 VEC(remote_g_packet_guess_s) *guesses;
10675 };
10676
10677 static struct gdbarch_data *remote_g_packet_data_handle;
10678
10679 static void *
10680 remote_g_packet_data_init (struct obstack *obstack)
10681 {
10682 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10683 }
10684
10685 void
10686 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10687 const struct target_desc *tdesc)
10688 {
10689 struct remote_g_packet_data *data
10690 = ((struct remote_g_packet_data *)
10691 gdbarch_data (gdbarch, remote_g_packet_data_handle));
10692 struct remote_g_packet_guess new_guess, *guess;
10693 int ix;
10694
10695 gdb_assert (tdesc != NULL);
10696
10697 for (ix = 0;
10698 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10699 ix++)
10700 if (guess->bytes == bytes)
10701 internal_error (__FILE__, __LINE__,
10702 _("Duplicate g packet description added for size %d"),
10703 bytes);
10704
10705 new_guess.bytes = bytes;
10706 new_guess.tdesc = tdesc;
10707 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10708 }
10709
10710 /* Return 1 if remote_read_description would do anything on this target
10711 and architecture, 0 otherwise. */
10712
10713 static int
10714 remote_read_description_p (struct target_ops *target)
10715 {
10716 struct remote_g_packet_data *data
10717 = ((struct remote_g_packet_data *)
10718 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10719
10720 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10721 return 1;
10722
10723 return 0;
10724 }
10725
10726 static const struct target_desc *
10727 remote_read_description (struct target_ops *target)
10728 {
10729 struct remote_g_packet_data *data
10730 = ((struct remote_g_packet_data *)
10731 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10732
10733 /* Do not try this during initial connection, when we do not know
10734 whether there is a running but stopped thread. */
10735 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10736 return target->beneath->to_read_description (target->beneath);
10737
10738 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10739 {
10740 struct remote_g_packet_guess *guess;
10741 int ix;
10742 int bytes = send_g_packet ();
10743
10744 for (ix = 0;
10745 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10746 ix++)
10747 if (guess->bytes == bytes)
10748 return guess->tdesc;
10749
10750 /* We discard the g packet. A minor optimization would be to
10751 hold on to it, and fill the register cache once we have selected
10752 an architecture, but it's too tricky to do safely. */
10753 }
10754
10755 return target->beneath->to_read_description (target->beneath);
10756 }
10757
10758 /* Remote file transfer support. This is host-initiated I/O, not
10759 target-initiated; for target-initiated, see remote-fileio.c. */
10760
10761 /* If *LEFT is at least the length of STRING, copy STRING to
10762 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10763 decrease *LEFT. Otherwise raise an error. */
10764
10765 static void
10766 remote_buffer_add_string (char **buffer, int *left, char *string)
10767 {
10768 int len = strlen (string);
10769
10770 if (len > *left)
10771 error (_("Packet too long for target."));
10772
10773 memcpy (*buffer, string, len);
10774 *buffer += len;
10775 *left -= len;
10776
10777 /* NUL-terminate the buffer as a convenience, if there is
10778 room. */
10779 if (*left)
10780 **buffer = '\0';
10781 }
10782
10783 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10784 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10785 decrease *LEFT. Otherwise raise an error. */
10786
10787 static void
10788 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10789 int len)
10790 {
10791 if (2 * len > *left)
10792 error (_("Packet too long for target."));
10793
10794 bin2hex (bytes, *buffer, len);
10795 *buffer += 2 * len;
10796 *left -= 2 * len;
10797
10798 /* NUL-terminate the buffer as a convenience, if there is
10799 room. */
10800 if (*left)
10801 **buffer = '\0';
10802 }
10803
10804 /* If *LEFT is large enough, convert VALUE to hex and add it to
10805 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10806 decrease *LEFT. Otherwise raise an error. */
10807
10808 static void
10809 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10810 {
10811 int len = hexnumlen (value);
10812
10813 if (len > *left)
10814 error (_("Packet too long for target."));
10815
10816 hexnumstr (*buffer, value);
10817 *buffer += len;
10818 *left -= len;
10819
10820 /* NUL-terminate the buffer as a convenience, if there is
10821 room. */
10822 if (*left)
10823 **buffer = '\0';
10824 }
10825
10826 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10827 value, *REMOTE_ERRNO to the remote error number or zero if none
10828 was included, and *ATTACHMENT to point to the start of the annex
10829 if any. The length of the packet isn't needed here; there may
10830 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10831
10832 Return 0 if the packet could be parsed, -1 if it could not. If
10833 -1 is returned, the other variables may not be initialized. */
10834
10835 static int
10836 remote_hostio_parse_result (char *buffer, int *retcode,
10837 int *remote_errno, char **attachment)
10838 {
10839 char *p, *p2;
10840
10841 *remote_errno = 0;
10842 *attachment = NULL;
10843
10844 if (buffer[0] != 'F')
10845 return -1;
10846
10847 errno = 0;
10848 *retcode = strtol (&buffer[1], &p, 16);
10849 if (errno != 0 || p == &buffer[1])
10850 return -1;
10851
10852 /* Check for ",errno". */
10853 if (*p == ',')
10854 {
10855 errno = 0;
10856 *remote_errno = strtol (p + 1, &p2, 16);
10857 if (errno != 0 || p + 1 == p2)
10858 return -1;
10859 p = p2;
10860 }
10861
10862 /* Check for ";attachment". If there is no attachment, the
10863 packet should end here. */
10864 if (*p == ';')
10865 {
10866 *attachment = p + 1;
10867 return 0;
10868 }
10869 else if (*p == '\0')
10870 return 0;
10871 else
10872 return -1;
10873 }
10874
10875 /* Send a prepared I/O packet to the target and read its response.
10876 The prepared packet is in the global RS->BUF before this function
10877 is called, and the answer is there when we return.
10878
10879 COMMAND_BYTES is the length of the request to send, which may include
10880 binary data. WHICH_PACKET is the packet configuration to check
10881 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10882 is set to the error number and -1 is returned. Otherwise the value
10883 returned by the function is returned.
10884
10885 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10886 attachment is expected; an error will be reported if there's a
10887 mismatch. If one is found, *ATTACHMENT will be set to point into
10888 the packet buffer and *ATTACHMENT_LEN will be set to the
10889 attachment's length. */
10890
10891 static int
10892 remote_hostio_send_command (int command_bytes, int which_packet,
10893 int *remote_errno, char **attachment,
10894 int *attachment_len)
10895 {
10896 struct remote_state *rs = get_remote_state ();
10897 int ret, bytes_read;
10898 char *attachment_tmp;
10899
10900 if (!rs->remote_desc
10901 || packet_support (which_packet) == PACKET_DISABLE)
10902 {
10903 *remote_errno = FILEIO_ENOSYS;
10904 return -1;
10905 }
10906
10907 putpkt_binary (rs->buf, command_bytes);
10908 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10909
10910 /* If it timed out, something is wrong. Don't try to parse the
10911 buffer. */
10912 if (bytes_read < 0)
10913 {
10914 *remote_errno = FILEIO_EINVAL;
10915 return -1;
10916 }
10917
10918 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10919 {
10920 case PACKET_ERROR:
10921 *remote_errno = FILEIO_EINVAL;
10922 return -1;
10923 case PACKET_UNKNOWN:
10924 *remote_errno = FILEIO_ENOSYS;
10925 return -1;
10926 case PACKET_OK:
10927 break;
10928 }
10929
10930 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10931 &attachment_tmp))
10932 {
10933 *remote_errno = FILEIO_EINVAL;
10934 return -1;
10935 }
10936
10937 /* Make sure we saw an attachment if and only if we expected one. */
10938 if ((attachment_tmp == NULL && attachment != NULL)
10939 || (attachment_tmp != NULL && attachment == NULL))
10940 {
10941 *remote_errno = FILEIO_EINVAL;
10942 return -1;
10943 }
10944
10945 /* If an attachment was found, it must point into the packet buffer;
10946 work out how many bytes there were. */
10947 if (attachment_tmp != NULL)
10948 {
10949 *attachment = attachment_tmp;
10950 *attachment_len = bytes_read - (*attachment - rs->buf);
10951 }
10952
10953 return ret;
10954 }
10955
10956 /* Invalidate the readahead cache. */
10957
10958 static void
10959 readahead_cache_invalidate (void)
10960 {
10961 struct remote_state *rs = get_remote_state ();
10962
10963 rs->readahead_cache.fd = -1;
10964 }
10965
10966 /* Invalidate the readahead cache if it is holding data for FD. */
10967
10968 static void
10969 readahead_cache_invalidate_fd (int fd)
10970 {
10971 struct remote_state *rs = get_remote_state ();
10972
10973 if (rs->readahead_cache.fd == fd)
10974 rs->readahead_cache.fd = -1;
10975 }
10976
10977 /* Set the filesystem remote_hostio functions that take FILENAME
10978 arguments will use. Return 0 on success, or -1 if an error
10979 occurs (and set *REMOTE_ERRNO). */
10980
10981 static int
10982 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10983 {
10984 struct remote_state *rs = get_remote_state ();
10985 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10986 char *p = rs->buf;
10987 int left = get_remote_packet_size () - 1;
10988 char arg[9];
10989 int ret;
10990
10991 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10992 return 0;
10993
10994 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10995 return 0;
10996
10997 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10998
10999 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11000 remote_buffer_add_string (&p, &left, arg);
11001
11002 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11003 remote_errno, NULL, NULL);
11004
11005 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11006 return 0;
11007
11008 if (ret == 0)
11009 rs->fs_pid = required_pid;
11010
11011 return ret;
11012 }
11013
11014 /* Implementation of to_fileio_open. */
11015
11016 static int
11017 remote_hostio_open (struct target_ops *self,
11018 struct inferior *inf, const char *filename,
11019 int flags, int mode, int warn_if_slow,
11020 int *remote_errno)
11021 {
11022 struct remote_state *rs = get_remote_state ();
11023 char *p = rs->buf;
11024 int left = get_remote_packet_size () - 1;
11025
11026 if (warn_if_slow)
11027 {
11028 static int warning_issued = 0;
11029
11030 printf_unfiltered (_("Reading %s from remote target...\n"),
11031 filename);
11032
11033 if (!warning_issued)
11034 {
11035 warning (_("File transfers from remote targets can be slow."
11036 " Use \"set sysroot\" to access files locally"
11037 " instead."));
11038 warning_issued = 1;
11039 }
11040 }
11041
11042 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11043 return -1;
11044
11045 remote_buffer_add_string (&p, &left, "vFile:open:");
11046
11047 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11048 strlen (filename));
11049 remote_buffer_add_string (&p, &left, ",");
11050
11051 remote_buffer_add_int (&p, &left, flags);
11052 remote_buffer_add_string (&p, &left, ",");
11053
11054 remote_buffer_add_int (&p, &left, mode);
11055
11056 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11057 remote_errno, NULL, NULL);
11058 }
11059
11060 /* Implementation of to_fileio_pwrite. */
11061
11062 static int
11063 remote_hostio_pwrite (struct target_ops *self,
11064 int fd, const gdb_byte *write_buf, int len,
11065 ULONGEST offset, int *remote_errno)
11066 {
11067 struct remote_state *rs = get_remote_state ();
11068 char *p = rs->buf;
11069 int left = get_remote_packet_size ();
11070 int out_len;
11071
11072 readahead_cache_invalidate_fd (fd);
11073
11074 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11075
11076 remote_buffer_add_int (&p, &left, fd);
11077 remote_buffer_add_string (&p, &left, ",");
11078
11079 remote_buffer_add_int (&p, &left, offset);
11080 remote_buffer_add_string (&p, &left, ",");
11081
11082 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11083 get_remote_packet_size () - (p - rs->buf));
11084
11085 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11086 remote_errno, NULL, NULL);
11087 }
11088
11089 /* Helper for the implementation of to_fileio_pread. Read the file
11090 from the remote side with vFile:pread. */
11091
11092 static int
11093 remote_hostio_pread_vFile (struct target_ops *self,
11094 int fd, gdb_byte *read_buf, int len,
11095 ULONGEST offset, int *remote_errno)
11096 {
11097 struct remote_state *rs = get_remote_state ();
11098 char *p = rs->buf;
11099 char *attachment;
11100 int left = get_remote_packet_size ();
11101 int ret, attachment_len;
11102 int read_len;
11103
11104 remote_buffer_add_string (&p, &left, "vFile:pread:");
11105
11106 remote_buffer_add_int (&p, &left, fd);
11107 remote_buffer_add_string (&p, &left, ",");
11108
11109 remote_buffer_add_int (&p, &left, len);
11110 remote_buffer_add_string (&p, &left, ",");
11111
11112 remote_buffer_add_int (&p, &left, offset);
11113
11114 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11115 remote_errno, &attachment,
11116 &attachment_len);
11117
11118 if (ret < 0)
11119 return ret;
11120
11121 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11122 read_buf, len);
11123 if (read_len != ret)
11124 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11125
11126 return ret;
11127 }
11128
11129 /* Serve pread from the readahead cache. Returns number of bytes
11130 read, or 0 if the request can't be served from the cache. */
11131
11132 static int
11133 remote_hostio_pread_from_cache (struct remote_state *rs,
11134 int fd, gdb_byte *read_buf, size_t len,
11135 ULONGEST offset)
11136 {
11137 struct readahead_cache *cache = &rs->readahead_cache;
11138
11139 if (cache->fd == fd
11140 && cache->offset <= offset
11141 && offset < cache->offset + cache->bufsize)
11142 {
11143 ULONGEST max = cache->offset + cache->bufsize;
11144
11145 if (offset + len > max)
11146 len = max - offset;
11147
11148 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11149 return len;
11150 }
11151
11152 return 0;
11153 }
11154
11155 /* Implementation of to_fileio_pread. */
11156
11157 static int
11158 remote_hostio_pread (struct target_ops *self,
11159 int fd, gdb_byte *read_buf, int len,
11160 ULONGEST offset, int *remote_errno)
11161 {
11162 int ret;
11163 struct remote_state *rs = get_remote_state ();
11164 struct readahead_cache *cache = &rs->readahead_cache;
11165
11166 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11167 if (ret > 0)
11168 {
11169 cache->hit_count++;
11170
11171 if (remote_debug)
11172 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11173 pulongest (cache->hit_count));
11174 return ret;
11175 }
11176
11177 cache->miss_count++;
11178 if (remote_debug)
11179 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11180 pulongest (cache->miss_count));
11181
11182 cache->fd = fd;
11183 cache->offset = offset;
11184 cache->bufsize = get_remote_packet_size ();
11185 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11186
11187 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11188 cache->offset, remote_errno);
11189 if (ret <= 0)
11190 {
11191 readahead_cache_invalidate_fd (fd);
11192 return ret;
11193 }
11194
11195 cache->bufsize = ret;
11196 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11197 }
11198
11199 /* Implementation of to_fileio_close. */
11200
11201 static int
11202 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11203 {
11204 struct remote_state *rs = get_remote_state ();
11205 char *p = rs->buf;
11206 int left = get_remote_packet_size () - 1;
11207
11208 readahead_cache_invalidate_fd (fd);
11209
11210 remote_buffer_add_string (&p, &left, "vFile:close:");
11211
11212 remote_buffer_add_int (&p, &left, fd);
11213
11214 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11215 remote_errno, NULL, NULL);
11216 }
11217
11218 /* Implementation of to_fileio_unlink. */
11219
11220 static int
11221 remote_hostio_unlink (struct target_ops *self,
11222 struct inferior *inf, const char *filename,
11223 int *remote_errno)
11224 {
11225 struct remote_state *rs = get_remote_state ();
11226 char *p = rs->buf;
11227 int left = get_remote_packet_size () - 1;
11228
11229 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11230 return -1;
11231
11232 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11233
11234 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11235 strlen (filename));
11236
11237 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11238 remote_errno, NULL, NULL);
11239 }
11240
11241 /* Implementation of to_fileio_readlink. */
11242
11243 static char *
11244 remote_hostio_readlink (struct target_ops *self,
11245 struct inferior *inf, const char *filename,
11246 int *remote_errno)
11247 {
11248 struct remote_state *rs = get_remote_state ();
11249 char *p = rs->buf;
11250 char *attachment;
11251 int left = get_remote_packet_size ();
11252 int len, attachment_len;
11253 int read_len;
11254 char *ret;
11255
11256 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11257 return NULL;
11258
11259 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11260
11261 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11262 strlen (filename));
11263
11264 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11265 remote_errno, &attachment,
11266 &attachment_len);
11267
11268 if (len < 0)
11269 return NULL;
11270
11271 ret = (char *) xmalloc (len + 1);
11272
11273 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11274 (gdb_byte *) ret, len);
11275 if (read_len != len)
11276 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11277
11278 ret[len] = '\0';
11279 return ret;
11280 }
11281
11282 /* Implementation of to_fileio_fstat. */
11283
11284 static int
11285 remote_hostio_fstat (struct target_ops *self,
11286 int fd, struct stat *st,
11287 int *remote_errno)
11288 {
11289 struct remote_state *rs = get_remote_state ();
11290 char *p = rs->buf;
11291 int left = get_remote_packet_size ();
11292 int attachment_len, ret;
11293 char *attachment;
11294 struct fio_stat fst;
11295 int read_len;
11296
11297 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11298
11299 remote_buffer_add_int (&p, &left, fd);
11300
11301 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11302 remote_errno, &attachment,
11303 &attachment_len);
11304 if (ret < 0)
11305 {
11306 if (*remote_errno != FILEIO_ENOSYS)
11307 return ret;
11308
11309 /* Strictly we should return -1, ENOSYS here, but when
11310 "set sysroot remote:" was implemented in August 2008
11311 BFD's need for a stat function was sidestepped with
11312 this hack. This was not remedied until March 2015
11313 so we retain the previous behavior to avoid breaking
11314 compatibility.
11315
11316 Note that the memset is a March 2015 addition; older
11317 GDBs set st_size *and nothing else* so the structure
11318 would have garbage in all other fields. This might
11319 break something but retaining the previous behavior
11320 here would be just too wrong. */
11321
11322 memset (st, 0, sizeof (struct stat));
11323 st->st_size = INT_MAX;
11324 return 0;
11325 }
11326
11327 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11328 (gdb_byte *) &fst, sizeof (fst));
11329
11330 if (read_len != ret)
11331 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11332
11333 if (read_len != sizeof (fst))
11334 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11335 read_len, (int) sizeof (fst));
11336
11337 remote_fileio_to_host_stat (&fst, st);
11338
11339 return 0;
11340 }
11341
11342 /* Implementation of to_filesystem_is_local. */
11343
11344 static int
11345 remote_filesystem_is_local (struct target_ops *self)
11346 {
11347 /* Valgrind GDB presents itself as a remote target but works
11348 on the local filesystem: it does not implement remote get
11349 and users are not expected to set a sysroot. To handle
11350 this case we treat the remote filesystem as local if the
11351 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11352 does not support vFile:open. */
11353 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11354 {
11355 enum packet_support ps = packet_support (PACKET_vFile_open);
11356
11357 if (ps == PACKET_SUPPORT_UNKNOWN)
11358 {
11359 int fd, remote_errno;
11360
11361 /* Try opening a file to probe support. The supplied
11362 filename is irrelevant, we only care about whether
11363 the stub recognizes the packet or not. */
11364 fd = remote_hostio_open (self, NULL, "just probing",
11365 FILEIO_O_RDONLY, 0700, 0,
11366 &remote_errno);
11367
11368 if (fd >= 0)
11369 remote_hostio_close (self, fd, &remote_errno);
11370
11371 ps = packet_support (PACKET_vFile_open);
11372 }
11373
11374 if (ps == PACKET_DISABLE)
11375 {
11376 static int warning_issued = 0;
11377
11378 if (!warning_issued)
11379 {
11380 warning (_("remote target does not support file"
11381 " transfer, attempting to access files"
11382 " from local filesystem."));
11383 warning_issued = 1;
11384 }
11385
11386 return 1;
11387 }
11388 }
11389
11390 return 0;
11391 }
11392
11393 static int
11394 remote_fileio_errno_to_host (int errnum)
11395 {
11396 switch (errnum)
11397 {
11398 case FILEIO_EPERM:
11399 return EPERM;
11400 case FILEIO_ENOENT:
11401 return ENOENT;
11402 case FILEIO_EINTR:
11403 return EINTR;
11404 case FILEIO_EIO:
11405 return EIO;
11406 case FILEIO_EBADF:
11407 return EBADF;
11408 case FILEIO_EACCES:
11409 return EACCES;
11410 case FILEIO_EFAULT:
11411 return EFAULT;
11412 case FILEIO_EBUSY:
11413 return EBUSY;
11414 case FILEIO_EEXIST:
11415 return EEXIST;
11416 case FILEIO_ENODEV:
11417 return ENODEV;
11418 case FILEIO_ENOTDIR:
11419 return ENOTDIR;
11420 case FILEIO_EISDIR:
11421 return EISDIR;
11422 case FILEIO_EINVAL:
11423 return EINVAL;
11424 case FILEIO_ENFILE:
11425 return ENFILE;
11426 case FILEIO_EMFILE:
11427 return EMFILE;
11428 case FILEIO_EFBIG:
11429 return EFBIG;
11430 case FILEIO_ENOSPC:
11431 return ENOSPC;
11432 case FILEIO_ESPIPE:
11433 return ESPIPE;
11434 case FILEIO_EROFS:
11435 return EROFS;
11436 case FILEIO_ENOSYS:
11437 return ENOSYS;
11438 case FILEIO_ENAMETOOLONG:
11439 return ENAMETOOLONG;
11440 }
11441 return -1;
11442 }
11443
11444 static char *
11445 remote_hostio_error (int errnum)
11446 {
11447 int host_error = remote_fileio_errno_to_host (errnum);
11448
11449 if (host_error == -1)
11450 error (_("Unknown remote I/O error %d"), errnum);
11451 else
11452 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11453 }
11454
11455 static void
11456 remote_hostio_close_cleanup (void *opaque)
11457 {
11458 int fd = *(int *) opaque;
11459 int remote_errno;
11460
11461 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11462 }
11463
11464 void
11465 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11466 {
11467 struct cleanup *back_to, *close_cleanup;
11468 int retcode, fd, remote_errno, bytes, io_size;
11469 FILE *file;
11470 gdb_byte *buffer;
11471 int bytes_in_buffer;
11472 int saw_eof;
11473 ULONGEST offset;
11474 struct remote_state *rs = get_remote_state ();
11475
11476 if (!rs->remote_desc)
11477 error (_("command can only be used with remote target"));
11478
11479 file = gdb_fopen_cloexec (local_file, "rb");
11480 if (file == NULL)
11481 perror_with_name (local_file);
11482 back_to = make_cleanup_fclose (file);
11483
11484 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11485 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11486 | FILEIO_O_TRUNC),
11487 0700, 0, &remote_errno);
11488 if (fd == -1)
11489 remote_hostio_error (remote_errno);
11490
11491 /* Send up to this many bytes at once. They won't all fit in the
11492 remote packet limit, so we'll transfer slightly fewer. */
11493 io_size = get_remote_packet_size ();
11494 buffer = (gdb_byte *) xmalloc (io_size);
11495 make_cleanup (xfree, buffer);
11496
11497 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11498
11499 bytes_in_buffer = 0;
11500 saw_eof = 0;
11501 offset = 0;
11502 while (bytes_in_buffer || !saw_eof)
11503 {
11504 if (!saw_eof)
11505 {
11506 bytes = fread (buffer + bytes_in_buffer, 1,
11507 io_size - bytes_in_buffer,
11508 file);
11509 if (bytes == 0)
11510 {
11511 if (ferror (file))
11512 error (_("Error reading %s."), local_file);
11513 else
11514 {
11515 /* EOF. Unless there is something still in the
11516 buffer from the last iteration, we are done. */
11517 saw_eof = 1;
11518 if (bytes_in_buffer == 0)
11519 break;
11520 }
11521 }
11522 }
11523 else
11524 bytes = 0;
11525
11526 bytes += bytes_in_buffer;
11527 bytes_in_buffer = 0;
11528
11529 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11530 fd, buffer, bytes,
11531 offset, &remote_errno);
11532
11533 if (retcode < 0)
11534 remote_hostio_error (remote_errno);
11535 else if (retcode == 0)
11536 error (_("Remote write of %d bytes returned 0!"), bytes);
11537 else if (retcode < bytes)
11538 {
11539 /* Short write. Save the rest of the read data for the next
11540 write. */
11541 bytes_in_buffer = bytes - retcode;
11542 memmove (buffer, buffer + retcode, bytes_in_buffer);
11543 }
11544
11545 offset += retcode;
11546 }
11547
11548 discard_cleanups (close_cleanup);
11549 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11550 remote_hostio_error (remote_errno);
11551
11552 if (from_tty)
11553 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11554 do_cleanups (back_to);
11555 }
11556
11557 void
11558 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11559 {
11560 struct cleanup *back_to, *close_cleanup;
11561 int fd, remote_errno, bytes, io_size;
11562 FILE *file;
11563 gdb_byte *buffer;
11564 ULONGEST offset;
11565 struct remote_state *rs = get_remote_state ();
11566
11567 if (!rs->remote_desc)
11568 error (_("command can only be used with remote target"));
11569
11570 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11571 remote_file, FILEIO_O_RDONLY, 0, 0,
11572 &remote_errno);
11573 if (fd == -1)
11574 remote_hostio_error (remote_errno);
11575
11576 file = gdb_fopen_cloexec (local_file, "wb");
11577 if (file == NULL)
11578 perror_with_name (local_file);
11579 back_to = make_cleanup_fclose (file);
11580
11581 /* Send up to this many bytes at once. They won't all fit in the
11582 remote packet limit, so we'll transfer slightly fewer. */
11583 io_size = get_remote_packet_size ();
11584 buffer = (gdb_byte *) xmalloc (io_size);
11585 make_cleanup (xfree, buffer);
11586
11587 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11588
11589 offset = 0;
11590 while (1)
11591 {
11592 bytes = remote_hostio_pread (find_target_at (process_stratum),
11593 fd, buffer, io_size, offset, &remote_errno);
11594 if (bytes == 0)
11595 /* Success, but no bytes, means end-of-file. */
11596 break;
11597 if (bytes == -1)
11598 remote_hostio_error (remote_errno);
11599
11600 offset += bytes;
11601
11602 bytes = fwrite (buffer, 1, bytes, file);
11603 if (bytes == 0)
11604 perror_with_name (local_file);
11605 }
11606
11607 discard_cleanups (close_cleanup);
11608 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11609 remote_hostio_error (remote_errno);
11610
11611 if (from_tty)
11612 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11613 do_cleanups (back_to);
11614 }
11615
11616 void
11617 remote_file_delete (const char *remote_file, int from_tty)
11618 {
11619 int retcode, remote_errno;
11620 struct remote_state *rs = get_remote_state ();
11621
11622 if (!rs->remote_desc)
11623 error (_("command can only be used with remote target"));
11624
11625 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11626 NULL, remote_file, &remote_errno);
11627 if (retcode == -1)
11628 remote_hostio_error (remote_errno);
11629
11630 if (from_tty)
11631 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11632 }
11633
11634 static void
11635 remote_put_command (char *args, int from_tty)
11636 {
11637 struct cleanup *back_to;
11638 char **argv;
11639
11640 if (args == NULL)
11641 error_no_arg (_("file to put"));
11642
11643 argv = gdb_buildargv (args);
11644 back_to = make_cleanup_freeargv (argv);
11645 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11646 error (_("Invalid parameters to remote put"));
11647
11648 remote_file_put (argv[0], argv[1], from_tty);
11649
11650 do_cleanups (back_to);
11651 }
11652
11653 static void
11654 remote_get_command (char *args, int from_tty)
11655 {
11656 struct cleanup *back_to;
11657 char **argv;
11658
11659 if (args == NULL)
11660 error_no_arg (_("file to get"));
11661
11662 argv = gdb_buildargv (args);
11663 back_to = make_cleanup_freeargv (argv);
11664 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11665 error (_("Invalid parameters to remote get"));
11666
11667 remote_file_get (argv[0], argv[1], from_tty);
11668
11669 do_cleanups (back_to);
11670 }
11671
11672 static void
11673 remote_delete_command (char *args, int from_tty)
11674 {
11675 struct cleanup *back_to;
11676 char **argv;
11677
11678 if (args == NULL)
11679 error_no_arg (_("file to delete"));
11680
11681 argv = gdb_buildargv (args);
11682 back_to = make_cleanup_freeargv (argv);
11683 if (argv[0] == NULL || argv[1] != NULL)
11684 error (_("Invalid parameters to remote delete"));
11685
11686 remote_file_delete (argv[0], from_tty);
11687
11688 do_cleanups (back_to);
11689 }
11690
11691 static void
11692 remote_command (char *args, int from_tty)
11693 {
11694 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11695 }
11696
11697 static int
11698 remote_can_execute_reverse (struct target_ops *self)
11699 {
11700 if (packet_support (PACKET_bs) == PACKET_ENABLE
11701 || packet_support (PACKET_bc) == PACKET_ENABLE)
11702 return 1;
11703 else
11704 return 0;
11705 }
11706
11707 static int
11708 remote_supports_non_stop (struct target_ops *self)
11709 {
11710 return 1;
11711 }
11712
11713 static int
11714 remote_supports_disable_randomization (struct target_ops *self)
11715 {
11716 /* Only supported in extended mode. */
11717 return 0;
11718 }
11719
11720 static int
11721 remote_supports_multi_process (struct target_ops *self)
11722 {
11723 struct remote_state *rs = get_remote_state ();
11724
11725 return remote_multi_process_p (rs);
11726 }
11727
11728 static int
11729 remote_supports_cond_tracepoints (void)
11730 {
11731 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11732 }
11733
11734 static int
11735 remote_supports_cond_breakpoints (struct target_ops *self)
11736 {
11737 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11738 }
11739
11740 static int
11741 remote_supports_fast_tracepoints (void)
11742 {
11743 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11744 }
11745
11746 static int
11747 remote_supports_static_tracepoints (void)
11748 {
11749 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11750 }
11751
11752 static int
11753 remote_supports_install_in_trace (void)
11754 {
11755 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11756 }
11757
11758 static int
11759 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11760 {
11761 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11762 == PACKET_ENABLE);
11763 }
11764
11765 static int
11766 remote_supports_string_tracing (struct target_ops *self)
11767 {
11768 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11769 }
11770
11771 static int
11772 remote_can_run_breakpoint_commands (struct target_ops *self)
11773 {
11774 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11775 }
11776
11777 static void
11778 remote_trace_init (struct target_ops *self)
11779 {
11780 putpkt ("QTinit");
11781 remote_get_noisy_reply (&target_buf, &target_buf_size);
11782 if (strcmp (target_buf, "OK") != 0)
11783 error (_("Target does not support this command."));
11784 }
11785
11786 static void free_actions_list (char **actions_list);
11787 static void free_actions_list_cleanup_wrapper (void *);
11788 static void
11789 free_actions_list_cleanup_wrapper (void *al)
11790 {
11791 free_actions_list ((char **) al);
11792 }
11793
11794 static void
11795 free_actions_list (char **actions_list)
11796 {
11797 int ndx;
11798
11799 if (actions_list == 0)
11800 return;
11801
11802 for (ndx = 0; actions_list[ndx]; ndx++)
11803 xfree (actions_list[ndx]);
11804
11805 xfree (actions_list);
11806 }
11807
11808 /* Recursive routine to walk through command list including loops, and
11809 download packets for each command. */
11810
11811 static void
11812 remote_download_command_source (int num, ULONGEST addr,
11813 struct command_line *cmds)
11814 {
11815 struct remote_state *rs = get_remote_state ();
11816 struct command_line *cmd;
11817
11818 for (cmd = cmds; cmd; cmd = cmd->next)
11819 {
11820 QUIT; /* Allow user to bail out with ^C. */
11821 strcpy (rs->buf, "QTDPsrc:");
11822 encode_source_string (num, addr, "cmd", cmd->line,
11823 rs->buf + strlen (rs->buf),
11824 rs->buf_size - strlen (rs->buf));
11825 putpkt (rs->buf);
11826 remote_get_noisy_reply (&target_buf, &target_buf_size);
11827 if (strcmp (target_buf, "OK"))
11828 warning (_("Target does not support source download."));
11829
11830 if (cmd->control_type == while_control
11831 || cmd->control_type == while_stepping_control)
11832 {
11833 remote_download_command_source (num, addr, *cmd->body_list);
11834
11835 QUIT; /* Allow user to bail out with ^C. */
11836 strcpy (rs->buf, "QTDPsrc:");
11837 encode_source_string (num, addr, "cmd", "end",
11838 rs->buf + strlen (rs->buf),
11839 rs->buf_size - strlen (rs->buf));
11840 putpkt (rs->buf);
11841 remote_get_noisy_reply (&target_buf, &target_buf_size);
11842 if (strcmp (target_buf, "OK"))
11843 warning (_("Target does not support source download."));
11844 }
11845 }
11846 }
11847
11848 static void
11849 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11850 {
11851 #define BUF_SIZE 2048
11852
11853 CORE_ADDR tpaddr;
11854 char addrbuf[40];
11855 char buf[BUF_SIZE];
11856 char **tdp_actions;
11857 char **stepping_actions;
11858 int ndx;
11859 struct cleanup *old_chain = NULL;
11860 struct agent_expr *aexpr;
11861 struct cleanup *aexpr_chain = NULL;
11862 char *pkt;
11863 struct breakpoint *b = loc->owner;
11864 struct tracepoint *t = (struct tracepoint *) b;
11865
11866 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11867 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11868 tdp_actions);
11869 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11870 stepping_actions);
11871
11872 tpaddr = loc->address;
11873 sprintf_vma (addrbuf, tpaddr);
11874 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11875 addrbuf, /* address */
11876 (b->enable_state == bp_enabled ? 'E' : 'D'),
11877 t->step_count, t->pass_count);
11878 /* Fast tracepoints are mostly handled by the target, but we can
11879 tell the target how big of an instruction block should be moved
11880 around. */
11881 if (b->type == bp_fast_tracepoint)
11882 {
11883 /* Only test for support at download time; we may not know
11884 target capabilities at definition time. */
11885 if (remote_supports_fast_tracepoints ())
11886 {
11887 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11888 NULL))
11889 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11890 gdb_insn_length (loc->gdbarch, tpaddr));
11891 else
11892 /* If it passed validation at definition but fails now,
11893 something is very wrong. */
11894 internal_error (__FILE__, __LINE__,
11895 _("Fast tracepoint not "
11896 "valid during download"));
11897 }
11898 else
11899 /* Fast tracepoints are functionally identical to regular
11900 tracepoints, so don't take lack of support as a reason to
11901 give up on the trace run. */
11902 warning (_("Target does not support fast tracepoints, "
11903 "downloading %d as regular tracepoint"), b->number);
11904 }
11905 else if (b->type == bp_static_tracepoint)
11906 {
11907 /* Only test for support at download time; we may not know
11908 target capabilities at definition time. */
11909 if (remote_supports_static_tracepoints ())
11910 {
11911 struct static_tracepoint_marker marker;
11912
11913 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11914 strcat (buf, ":S");
11915 else
11916 error (_("Static tracepoint not valid during download"));
11917 }
11918 else
11919 /* Fast tracepoints are functionally identical to regular
11920 tracepoints, so don't take lack of support as a reason
11921 to give up on the trace run. */
11922 error (_("Target does not support static tracepoints"));
11923 }
11924 /* If the tracepoint has a conditional, make it into an agent
11925 expression and append to the definition. */
11926 if (loc->cond)
11927 {
11928 /* Only test support at download time, we may not know target
11929 capabilities at definition time. */
11930 if (remote_supports_cond_tracepoints ())
11931 {
11932 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11933 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11934 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11935 aexpr->len);
11936 pkt = buf + strlen (buf);
11937 for (ndx = 0; ndx < aexpr->len; ++ndx)
11938 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11939 *pkt = '\0';
11940 do_cleanups (aexpr_chain);
11941 }
11942 else
11943 warning (_("Target does not support conditional tracepoints, "
11944 "ignoring tp %d cond"), b->number);
11945 }
11946
11947 if (b->commands || *default_collect)
11948 strcat (buf, "-");
11949 putpkt (buf);
11950 remote_get_noisy_reply (&target_buf, &target_buf_size);
11951 if (strcmp (target_buf, "OK"))
11952 error (_("Target does not support tracepoints."));
11953
11954 /* do_single_steps (t); */
11955 if (tdp_actions)
11956 {
11957 for (ndx = 0; tdp_actions[ndx]; ndx++)
11958 {
11959 QUIT; /* Allow user to bail out with ^C. */
11960 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11961 b->number, addrbuf, /* address */
11962 tdp_actions[ndx],
11963 ((tdp_actions[ndx + 1] || stepping_actions)
11964 ? '-' : 0));
11965 putpkt (buf);
11966 remote_get_noisy_reply (&target_buf,
11967 &target_buf_size);
11968 if (strcmp (target_buf, "OK"))
11969 error (_("Error on target while setting tracepoints."));
11970 }
11971 }
11972 if (stepping_actions)
11973 {
11974 for (ndx = 0; stepping_actions[ndx]; ndx++)
11975 {
11976 QUIT; /* Allow user to bail out with ^C. */
11977 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11978 b->number, addrbuf, /* address */
11979 ((ndx == 0) ? "S" : ""),
11980 stepping_actions[ndx],
11981 (stepping_actions[ndx + 1] ? "-" : ""));
11982 putpkt (buf);
11983 remote_get_noisy_reply (&target_buf,
11984 &target_buf_size);
11985 if (strcmp (target_buf, "OK"))
11986 error (_("Error on target while setting tracepoints."));
11987 }
11988 }
11989
11990 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11991 {
11992 if (b->location != NULL)
11993 {
11994 strcpy (buf, "QTDPsrc:");
11995 encode_source_string (b->number, loc->address, "at",
11996 event_location_to_string (b->location),
11997 buf + strlen (buf), 2048 - strlen (buf));
11998 putpkt (buf);
11999 remote_get_noisy_reply (&target_buf, &target_buf_size);
12000 if (strcmp (target_buf, "OK"))
12001 warning (_("Target does not support source download."));
12002 }
12003 if (b->cond_string)
12004 {
12005 strcpy (buf, "QTDPsrc:");
12006 encode_source_string (b->number, loc->address,
12007 "cond", b->cond_string, buf + strlen (buf),
12008 2048 - strlen (buf));
12009 putpkt (buf);
12010 remote_get_noisy_reply (&target_buf, &target_buf_size);
12011 if (strcmp (target_buf, "OK"))
12012 warning (_("Target does not support source download."));
12013 }
12014 remote_download_command_source (b->number, loc->address,
12015 breakpoint_commands (b));
12016 }
12017
12018 do_cleanups (old_chain);
12019 }
12020
12021 static int
12022 remote_can_download_tracepoint (struct target_ops *self)
12023 {
12024 struct remote_state *rs = get_remote_state ();
12025 struct trace_status *ts;
12026 int status;
12027
12028 /* Don't try to install tracepoints until we've relocated our
12029 symbols, and fetched and merged the target's tracepoint list with
12030 ours. */
12031 if (rs->starting_up)
12032 return 0;
12033
12034 ts = current_trace_status ();
12035 status = remote_get_trace_status (self, ts);
12036
12037 if (status == -1 || !ts->running_known || !ts->running)
12038 return 0;
12039
12040 /* If we are in a tracing experiment, but remote stub doesn't support
12041 installing tracepoint in trace, we have to return. */
12042 if (!remote_supports_install_in_trace ())
12043 return 0;
12044
12045 return 1;
12046 }
12047
12048
12049 static void
12050 remote_download_trace_state_variable (struct target_ops *self,
12051 struct trace_state_variable *tsv)
12052 {
12053 struct remote_state *rs = get_remote_state ();
12054 char *p;
12055
12056 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12057 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12058 tsv->builtin);
12059 p = rs->buf + strlen (rs->buf);
12060 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12061 error (_("Trace state variable name too long for tsv definition packet"));
12062 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12063 *p++ = '\0';
12064 putpkt (rs->buf);
12065 remote_get_noisy_reply (&target_buf, &target_buf_size);
12066 if (*target_buf == '\0')
12067 error (_("Target does not support this command."));
12068 if (strcmp (target_buf, "OK") != 0)
12069 error (_("Error on target while downloading trace state variable."));
12070 }
12071
12072 static void
12073 remote_enable_tracepoint (struct target_ops *self,
12074 struct bp_location *location)
12075 {
12076 struct remote_state *rs = get_remote_state ();
12077 char addr_buf[40];
12078
12079 sprintf_vma (addr_buf, location->address);
12080 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12081 location->owner->number, addr_buf);
12082 putpkt (rs->buf);
12083 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12084 if (*rs->buf == '\0')
12085 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12086 if (strcmp (rs->buf, "OK") != 0)
12087 error (_("Error on target while enabling tracepoint."));
12088 }
12089
12090 static void
12091 remote_disable_tracepoint (struct target_ops *self,
12092 struct bp_location *location)
12093 {
12094 struct remote_state *rs = get_remote_state ();
12095 char addr_buf[40];
12096
12097 sprintf_vma (addr_buf, location->address);
12098 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12099 location->owner->number, addr_buf);
12100 putpkt (rs->buf);
12101 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12102 if (*rs->buf == '\0')
12103 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12104 if (strcmp (rs->buf, "OK") != 0)
12105 error (_("Error on target while disabling tracepoint."));
12106 }
12107
12108 static void
12109 remote_trace_set_readonly_regions (struct target_ops *self)
12110 {
12111 asection *s;
12112 bfd *abfd = NULL;
12113 bfd_size_type size;
12114 bfd_vma vma;
12115 int anysecs = 0;
12116 int offset = 0;
12117
12118 if (!exec_bfd)
12119 return; /* No information to give. */
12120
12121 strcpy (target_buf, "QTro");
12122 offset = strlen (target_buf);
12123 for (s = exec_bfd->sections; s; s = s->next)
12124 {
12125 char tmp1[40], tmp2[40];
12126 int sec_length;
12127
12128 if ((s->flags & SEC_LOAD) == 0 ||
12129 /* (s->flags & SEC_CODE) == 0 || */
12130 (s->flags & SEC_READONLY) == 0)
12131 continue;
12132
12133 anysecs = 1;
12134 vma = bfd_get_section_vma (abfd, s);
12135 size = bfd_get_section_size (s);
12136 sprintf_vma (tmp1, vma);
12137 sprintf_vma (tmp2, vma + size);
12138 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12139 if (offset + sec_length + 1 > target_buf_size)
12140 {
12141 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12142 warning (_("\
12143 Too many sections for read-only sections definition packet."));
12144 break;
12145 }
12146 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12147 tmp1, tmp2);
12148 offset += sec_length;
12149 }
12150 if (anysecs)
12151 {
12152 putpkt (target_buf);
12153 getpkt (&target_buf, &target_buf_size, 0);
12154 }
12155 }
12156
12157 static void
12158 remote_trace_start (struct target_ops *self)
12159 {
12160 putpkt ("QTStart");
12161 remote_get_noisy_reply (&target_buf, &target_buf_size);
12162 if (*target_buf == '\0')
12163 error (_("Target does not support this command."));
12164 if (strcmp (target_buf, "OK") != 0)
12165 error (_("Bogus reply from target: %s"), target_buf);
12166 }
12167
12168 static int
12169 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12170 {
12171 /* Initialize it just to avoid a GCC false warning. */
12172 char *p = NULL;
12173 /* FIXME we need to get register block size some other way. */
12174 extern int trace_regblock_size;
12175 enum packet_result result;
12176
12177 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12178 return -1;
12179
12180 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12181
12182 putpkt ("qTStatus");
12183
12184 TRY
12185 {
12186 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12187 }
12188 CATCH (ex, RETURN_MASK_ERROR)
12189 {
12190 if (ex.error != TARGET_CLOSE_ERROR)
12191 {
12192 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12193 return -1;
12194 }
12195 throw_exception (ex);
12196 }
12197 END_CATCH
12198
12199 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12200
12201 /* If the remote target doesn't do tracing, flag it. */
12202 if (result == PACKET_UNKNOWN)
12203 return -1;
12204
12205 /* We're working with a live target. */
12206 ts->filename = NULL;
12207
12208 if (*p++ != 'T')
12209 error (_("Bogus trace status reply from target: %s"), target_buf);
12210
12211 /* Function 'parse_trace_status' sets default value of each field of
12212 'ts' at first, so we don't have to do it here. */
12213 parse_trace_status (p, ts);
12214
12215 return ts->running;
12216 }
12217
12218 static void
12219 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12220 struct uploaded_tp *utp)
12221 {
12222 struct remote_state *rs = get_remote_state ();
12223 char *reply;
12224 struct bp_location *loc;
12225 struct tracepoint *tp = (struct tracepoint *) bp;
12226 size_t size = get_remote_packet_size ();
12227
12228 if (tp)
12229 {
12230 tp->base.hit_count = 0;
12231 tp->traceframe_usage = 0;
12232 for (loc = tp->base.loc; loc; loc = loc->next)
12233 {
12234 /* If the tracepoint was never downloaded, don't go asking for
12235 any status. */
12236 if (tp->number_on_target == 0)
12237 continue;
12238 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12239 phex_nz (loc->address, 0));
12240 putpkt (rs->buf);
12241 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12242 if (reply && *reply)
12243 {
12244 if (*reply == 'V')
12245 parse_tracepoint_status (reply + 1, bp, utp);
12246 }
12247 }
12248 }
12249 else if (utp)
12250 {
12251 utp->hit_count = 0;
12252 utp->traceframe_usage = 0;
12253 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12254 phex_nz (utp->addr, 0));
12255 putpkt (rs->buf);
12256 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12257 if (reply && *reply)
12258 {
12259 if (*reply == 'V')
12260 parse_tracepoint_status (reply + 1, bp, utp);
12261 }
12262 }
12263 }
12264
12265 static void
12266 remote_trace_stop (struct target_ops *self)
12267 {
12268 putpkt ("QTStop");
12269 remote_get_noisy_reply (&target_buf, &target_buf_size);
12270 if (*target_buf == '\0')
12271 error (_("Target does not support this command."));
12272 if (strcmp (target_buf, "OK") != 0)
12273 error (_("Bogus reply from target: %s"), target_buf);
12274 }
12275
12276 static int
12277 remote_trace_find (struct target_ops *self,
12278 enum trace_find_type type, int num,
12279 CORE_ADDR addr1, CORE_ADDR addr2,
12280 int *tpp)
12281 {
12282 struct remote_state *rs = get_remote_state ();
12283 char *endbuf = rs->buf + get_remote_packet_size ();
12284 char *p, *reply;
12285 int target_frameno = -1, target_tracept = -1;
12286
12287 /* Lookups other than by absolute frame number depend on the current
12288 trace selected, so make sure it is correct on the remote end
12289 first. */
12290 if (type != tfind_number)
12291 set_remote_traceframe ();
12292
12293 p = rs->buf;
12294 strcpy (p, "QTFrame:");
12295 p = strchr (p, '\0');
12296 switch (type)
12297 {
12298 case tfind_number:
12299 xsnprintf (p, endbuf - p, "%x", num);
12300 break;
12301 case tfind_pc:
12302 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12303 break;
12304 case tfind_tp:
12305 xsnprintf (p, endbuf - p, "tdp:%x", num);
12306 break;
12307 case tfind_range:
12308 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12309 phex_nz (addr2, 0));
12310 break;
12311 case tfind_outside:
12312 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12313 phex_nz (addr2, 0));
12314 break;
12315 default:
12316 error (_("Unknown trace find type %d"), type);
12317 }
12318
12319 putpkt (rs->buf);
12320 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12321 if (*reply == '\0')
12322 error (_("Target does not support this command."));
12323
12324 while (reply && *reply)
12325 switch (*reply)
12326 {
12327 case 'F':
12328 p = ++reply;
12329 target_frameno = (int) strtol (p, &reply, 16);
12330 if (reply == p)
12331 error (_("Unable to parse trace frame number"));
12332 /* Don't update our remote traceframe number cache on failure
12333 to select a remote traceframe. */
12334 if (target_frameno == -1)
12335 return -1;
12336 break;
12337 case 'T':
12338 p = ++reply;
12339 target_tracept = (int) strtol (p, &reply, 16);
12340 if (reply == p)
12341 error (_("Unable to parse tracepoint number"));
12342 break;
12343 case 'O': /* "OK"? */
12344 if (reply[1] == 'K' && reply[2] == '\0')
12345 reply += 2;
12346 else
12347 error (_("Bogus reply from target: %s"), reply);
12348 break;
12349 default:
12350 error (_("Bogus reply from target: %s"), reply);
12351 }
12352 if (tpp)
12353 *tpp = target_tracept;
12354
12355 rs->remote_traceframe_number = target_frameno;
12356 return target_frameno;
12357 }
12358
12359 static int
12360 remote_get_trace_state_variable_value (struct target_ops *self,
12361 int tsvnum, LONGEST *val)
12362 {
12363 struct remote_state *rs = get_remote_state ();
12364 char *reply;
12365 ULONGEST uval;
12366
12367 set_remote_traceframe ();
12368
12369 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12370 putpkt (rs->buf);
12371 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12372 if (reply && *reply)
12373 {
12374 if (*reply == 'V')
12375 {
12376 unpack_varlen_hex (reply + 1, &uval);
12377 *val = (LONGEST) uval;
12378 return 1;
12379 }
12380 }
12381 return 0;
12382 }
12383
12384 static int
12385 remote_save_trace_data (struct target_ops *self, const char *filename)
12386 {
12387 struct remote_state *rs = get_remote_state ();
12388 char *p, *reply;
12389
12390 p = rs->buf;
12391 strcpy (p, "QTSave:");
12392 p += strlen (p);
12393 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12394 error (_("Remote file name too long for trace save packet"));
12395 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12396 *p++ = '\0';
12397 putpkt (rs->buf);
12398 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12399 if (*reply == '\0')
12400 error (_("Target does not support this command."));
12401 if (strcmp (reply, "OK") != 0)
12402 error (_("Bogus reply from target: %s"), reply);
12403 return 0;
12404 }
12405
12406 /* This is basically a memory transfer, but needs to be its own packet
12407 because we don't know how the target actually organizes its trace
12408 memory, plus we want to be able to ask for as much as possible, but
12409 not be unhappy if we don't get as much as we ask for. */
12410
12411 static LONGEST
12412 remote_get_raw_trace_data (struct target_ops *self,
12413 gdb_byte *buf, ULONGEST offset, LONGEST len)
12414 {
12415 struct remote_state *rs = get_remote_state ();
12416 char *reply;
12417 char *p;
12418 int rslt;
12419
12420 p = rs->buf;
12421 strcpy (p, "qTBuffer:");
12422 p += strlen (p);
12423 p += hexnumstr (p, offset);
12424 *p++ = ',';
12425 p += hexnumstr (p, len);
12426 *p++ = '\0';
12427
12428 putpkt (rs->buf);
12429 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12430 if (reply && *reply)
12431 {
12432 /* 'l' by itself means we're at the end of the buffer and
12433 there is nothing more to get. */
12434 if (*reply == 'l')
12435 return 0;
12436
12437 /* Convert the reply into binary. Limit the number of bytes to
12438 convert according to our passed-in buffer size, rather than
12439 what was returned in the packet; if the target is
12440 unexpectedly generous and gives us a bigger reply than we
12441 asked for, we don't want to crash. */
12442 rslt = hex2bin (target_buf, buf, len);
12443 return rslt;
12444 }
12445
12446 /* Something went wrong, flag as an error. */
12447 return -1;
12448 }
12449
12450 static void
12451 remote_set_disconnected_tracing (struct target_ops *self, int val)
12452 {
12453 struct remote_state *rs = get_remote_state ();
12454
12455 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12456 {
12457 char *reply;
12458
12459 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12460 putpkt (rs->buf);
12461 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12462 if (*reply == '\0')
12463 error (_("Target does not support this command."));
12464 if (strcmp (reply, "OK") != 0)
12465 error (_("Bogus reply from target: %s"), reply);
12466 }
12467 else if (val)
12468 warning (_("Target does not support disconnected tracing."));
12469 }
12470
12471 static int
12472 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12473 {
12474 struct thread_info *info = find_thread_ptid (ptid);
12475
12476 if (info && info->priv)
12477 return info->priv->core;
12478 return -1;
12479 }
12480
12481 static void
12482 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12483 {
12484 struct remote_state *rs = get_remote_state ();
12485 char *reply;
12486
12487 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12488 putpkt (rs->buf);
12489 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12490 if (*reply == '\0')
12491 error (_("Target does not support this command."));
12492 if (strcmp (reply, "OK") != 0)
12493 error (_("Bogus reply from target: %s"), reply);
12494 }
12495
12496 static struct traceframe_info *
12497 remote_traceframe_info (struct target_ops *self)
12498 {
12499 char *text;
12500
12501 text = target_read_stralloc (&current_target,
12502 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12503 if (text != NULL)
12504 {
12505 struct traceframe_info *info;
12506 struct cleanup *back_to = make_cleanup (xfree, text);
12507
12508 info = parse_traceframe_info (text);
12509 do_cleanups (back_to);
12510 return info;
12511 }
12512
12513 return NULL;
12514 }
12515
12516 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12517 instruction on which a fast tracepoint may be placed. Returns -1
12518 if the packet is not supported, and 0 if the minimum instruction
12519 length is unknown. */
12520
12521 static int
12522 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12523 {
12524 struct remote_state *rs = get_remote_state ();
12525 char *reply;
12526
12527 /* If we're not debugging a process yet, the IPA can't be
12528 loaded. */
12529 if (!target_has_execution)
12530 return 0;
12531
12532 /* Make sure the remote is pointing at the right process. */
12533 set_general_process ();
12534
12535 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12536 putpkt (rs->buf);
12537 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12538 if (*reply == '\0')
12539 return -1;
12540 else
12541 {
12542 ULONGEST min_insn_len;
12543
12544 unpack_varlen_hex (reply, &min_insn_len);
12545
12546 return (int) min_insn_len;
12547 }
12548 }
12549
12550 static void
12551 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12552 {
12553 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12554 {
12555 struct remote_state *rs = get_remote_state ();
12556 char *buf = rs->buf;
12557 char *endbuf = rs->buf + get_remote_packet_size ();
12558 enum packet_result result;
12559
12560 gdb_assert (val >= 0 || val == -1);
12561 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12562 /* Send -1 as literal "-1" to avoid host size dependency. */
12563 if (val < 0)
12564 {
12565 *buf++ = '-';
12566 buf += hexnumstr (buf, (ULONGEST) -val);
12567 }
12568 else
12569 buf += hexnumstr (buf, (ULONGEST) val);
12570
12571 putpkt (rs->buf);
12572 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12573 result = packet_ok (rs->buf,
12574 &remote_protocol_packets[PACKET_QTBuffer_size]);
12575
12576 if (result != PACKET_OK)
12577 warning (_("Bogus reply from target: %s"), rs->buf);
12578 }
12579 }
12580
12581 static int
12582 remote_set_trace_notes (struct target_ops *self,
12583 const char *user, const char *notes,
12584 const char *stop_notes)
12585 {
12586 struct remote_state *rs = get_remote_state ();
12587 char *reply;
12588 char *buf = rs->buf;
12589 char *endbuf = rs->buf + get_remote_packet_size ();
12590 int nbytes;
12591
12592 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12593 if (user)
12594 {
12595 buf += xsnprintf (buf, endbuf - buf, "user:");
12596 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12597 buf += 2 * nbytes;
12598 *buf++ = ';';
12599 }
12600 if (notes)
12601 {
12602 buf += xsnprintf (buf, endbuf - buf, "notes:");
12603 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12604 buf += 2 * nbytes;
12605 *buf++ = ';';
12606 }
12607 if (stop_notes)
12608 {
12609 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12610 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12611 buf += 2 * nbytes;
12612 *buf++ = ';';
12613 }
12614 /* Ensure the buffer is terminated. */
12615 *buf = '\0';
12616
12617 putpkt (rs->buf);
12618 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12619 if (*reply == '\0')
12620 return 0;
12621
12622 if (strcmp (reply, "OK") != 0)
12623 error (_("Bogus reply from target: %s"), reply);
12624
12625 return 1;
12626 }
12627
12628 static int
12629 remote_use_agent (struct target_ops *self, int use)
12630 {
12631 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12632 {
12633 struct remote_state *rs = get_remote_state ();
12634
12635 /* If the stub supports QAgent. */
12636 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12637 putpkt (rs->buf);
12638 getpkt (&rs->buf, &rs->buf_size, 0);
12639
12640 if (strcmp (rs->buf, "OK") == 0)
12641 {
12642 use_agent = use;
12643 return 1;
12644 }
12645 }
12646
12647 return 0;
12648 }
12649
12650 static int
12651 remote_can_use_agent (struct target_ops *self)
12652 {
12653 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12654 }
12655
12656 struct btrace_target_info
12657 {
12658 /* The ptid of the traced thread. */
12659 ptid_t ptid;
12660
12661 /* The obtained branch trace configuration. */
12662 struct btrace_config conf;
12663 };
12664
12665 /* Reset our idea of our target's btrace configuration. */
12666
12667 static void
12668 remote_btrace_reset (void)
12669 {
12670 struct remote_state *rs = get_remote_state ();
12671
12672 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12673 }
12674
12675 /* Check whether the target supports branch tracing. */
12676
12677 static int
12678 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12679 {
12680 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12681 return 0;
12682 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12683 return 0;
12684
12685 switch (format)
12686 {
12687 case BTRACE_FORMAT_NONE:
12688 return 0;
12689
12690 case BTRACE_FORMAT_BTS:
12691 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12692
12693 case BTRACE_FORMAT_PT:
12694 /* The trace is decoded on the host. Even if our target supports it,
12695 we still need to have libipt to decode the trace. */
12696 #if defined (HAVE_LIBIPT)
12697 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12698 #else /* !defined (HAVE_LIBIPT) */
12699 return 0;
12700 #endif /* !defined (HAVE_LIBIPT) */
12701 }
12702
12703 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12704 }
12705
12706 /* Synchronize the configuration with the target. */
12707
12708 static void
12709 btrace_sync_conf (const struct btrace_config *conf)
12710 {
12711 struct packet_config *packet;
12712 struct remote_state *rs;
12713 char *buf, *pos, *endbuf;
12714
12715 rs = get_remote_state ();
12716 buf = rs->buf;
12717 endbuf = buf + get_remote_packet_size ();
12718
12719 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12720 if (packet_config_support (packet) == PACKET_ENABLE
12721 && conf->bts.size != rs->btrace_config.bts.size)
12722 {
12723 pos = buf;
12724 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12725 conf->bts.size);
12726
12727 putpkt (buf);
12728 getpkt (&buf, &rs->buf_size, 0);
12729
12730 if (packet_ok (buf, packet) == PACKET_ERROR)
12731 {
12732 if (buf[0] == 'E' && buf[1] == '.')
12733 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12734 else
12735 error (_("Failed to configure the BTS buffer size."));
12736 }
12737
12738 rs->btrace_config.bts.size = conf->bts.size;
12739 }
12740
12741 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12742 if (packet_config_support (packet) == PACKET_ENABLE
12743 && conf->pt.size != rs->btrace_config.pt.size)
12744 {
12745 pos = buf;
12746 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12747 conf->pt.size);
12748
12749 putpkt (buf);
12750 getpkt (&buf, &rs->buf_size, 0);
12751
12752 if (packet_ok (buf, packet) == PACKET_ERROR)
12753 {
12754 if (buf[0] == 'E' && buf[1] == '.')
12755 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12756 else
12757 error (_("Failed to configure the trace buffer size."));
12758 }
12759
12760 rs->btrace_config.pt.size = conf->pt.size;
12761 }
12762 }
12763
12764 /* Read the current thread's btrace configuration from the target and
12765 store it into CONF. */
12766
12767 static void
12768 btrace_read_config (struct btrace_config *conf)
12769 {
12770 char *xml;
12771
12772 xml = target_read_stralloc (&current_target,
12773 TARGET_OBJECT_BTRACE_CONF, "");
12774 if (xml != NULL)
12775 {
12776 struct cleanup *cleanup;
12777
12778 cleanup = make_cleanup (xfree, xml);
12779 parse_xml_btrace_conf (conf, xml);
12780 do_cleanups (cleanup);
12781 }
12782 }
12783
12784 /* Maybe reopen target btrace. */
12785
12786 static void
12787 remote_btrace_maybe_reopen (void)
12788 {
12789 struct remote_state *rs = get_remote_state ();
12790 struct cleanup *cleanup;
12791 struct thread_info *tp;
12792 int btrace_target_pushed = 0;
12793 int warned = 0;
12794
12795 cleanup = make_cleanup_restore_current_thread ();
12796 ALL_NON_EXITED_THREADS (tp)
12797 {
12798 set_general_thread (tp->ptid);
12799
12800 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
12801 btrace_read_config (&rs->btrace_config);
12802
12803 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
12804 continue;
12805
12806 #if !defined (HAVE_LIBIPT)
12807 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
12808 {
12809 if (!warned)
12810 {
12811 warned = 1;
12812 warning (_("GDB does not support Intel Processor Trace. "
12813 "\"record\" will not work in this session."));
12814 }
12815
12816 continue;
12817 }
12818 #endif /* !defined (HAVE_LIBIPT) */
12819
12820 /* Push target, once, but before anything else happens. This way our
12821 changes to the threads will be cleaned up by unpushing the target
12822 in case btrace_read_config () throws. */
12823 if (!btrace_target_pushed)
12824 {
12825 btrace_target_pushed = 1;
12826 record_btrace_push_target ();
12827 printf_filtered (_("Target is recording using %s.\n"),
12828 btrace_format_string (rs->btrace_config.format));
12829 }
12830
12831 tp->btrace.target = XCNEW (struct btrace_target_info);
12832 tp->btrace.target->ptid = tp->ptid;
12833 tp->btrace.target->conf = rs->btrace_config;
12834 }
12835 do_cleanups (cleanup);
12836 }
12837
12838 /* Enable branch tracing. */
12839
12840 static struct btrace_target_info *
12841 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12842 const struct btrace_config *conf)
12843 {
12844 struct btrace_target_info *tinfo = NULL;
12845 struct packet_config *packet = NULL;
12846 struct remote_state *rs = get_remote_state ();
12847 char *buf = rs->buf;
12848 char *endbuf = rs->buf + get_remote_packet_size ();
12849
12850 switch (conf->format)
12851 {
12852 case BTRACE_FORMAT_BTS:
12853 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12854 break;
12855
12856 case BTRACE_FORMAT_PT:
12857 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12858 break;
12859 }
12860
12861 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12862 error (_("Target does not support branch tracing."));
12863
12864 btrace_sync_conf (conf);
12865
12866 set_general_thread (ptid);
12867
12868 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12869 putpkt (rs->buf);
12870 getpkt (&rs->buf, &rs->buf_size, 0);
12871
12872 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12873 {
12874 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12875 error (_("Could not enable branch tracing for %s: %s"),
12876 target_pid_to_str (ptid), rs->buf + 2);
12877 else
12878 error (_("Could not enable branch tracing for %s."),
12879 target_pid_to_str (ptid));
12880 }
12881
12882 tinfo = XCNEW (struct btrace_target_info);
12883 tinfo->ptid = ptid;
12884
12885 /* If we fail to read the configuration, we lose some information, but the
12886 tracing itself is not impacted. */
12887 TRY
12888 {
12889 btrace_read_config (&tinfo->conf);
12890 }
12891 CATCH (err, RETURN_MASK_ERROR)
12892 {
12893 if (err.message != NULL)
12894 warning ("%s", err.message);
12895 }
12896 END_CATCH
12897
12898 return tinfo;
12899 }
12900
12901 /* Disable branch tracing. */
12902
12903 static void
12904 remote_disable_btrace (struct target_ops *self,
12905 struct btrace_target_info *tinfo)
12906 {
12907 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12908 struct remote_state *rs = get_remote_state ();
12909 char *buf = rs->buf;
12910 char *endbuf = rs->buf + get_remote_packet_size ();
12911
12912 if (packet_config_support (packet) != PACKET_ENABLE)
12913 error (_("Target does not support branch tracing."));
12914
12915 set_general_thread (tinfo->ptid);
12916
12917 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12918 putpkt (rs->buf);
12919 getpkt (&rs->buf, &rs->buf_size, 0);
12920
12921 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12922 {
12923 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12924 error (_("Could not disable branch tracing for %s: %s"),
12925 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12926 else
12927 error (_("Could not disable branch tracing for %s."),
12928 target_pid_to_str (tinfo->ptid));
12929 }
12930
12931 xfree (tinfo);
12932 }
12933
12934 /* Teardown branch tracing. */
12935
12936 static void
12937 remote_teardown_btrace (struct target_ops *self,
12938 struct btrace_target_info *tinfo)
12939 {
12940 /* We must not talk to the target during teardown. */
12941 xfree (tinfo);
12942 }
12943
12944 /* Read the branch trace. */
12945
12946 static enum btrace_error
12947 remote_read_btrace (struct target_ops *self,
12948 struct btrace_data *btrace,
12949 struct btrace_target_info *tinfo,
12950 enum btrace_read_type type)
12951 {
12952 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12953 struct cleanup *cleanup;
12954 const char *annex;
12955 char *xml;
12956
12957 if (packet_config_support (packet) != PACKET_ENABLE)
12958 error (_("Target does not support branch tracing."));
12959
12960 #if !defined(HAVE_LIBEXPAT)
12961 error (_("Cannot process branch tracing result. XML parsing not supported."));
12962 #endif
12963
12964 switch (type)
12965 {
12966 case BTRACE_READ_ALL:
12967 annex = "all";
12968 break;
12969 case BTRACE_READ_NEW:
12970 annex = "new";
12971 break;
12972 case BTRACE_READ_DELTA:
12973 annex = "delta";
12974 break;
12975 default:
12976 internal_error (__FILE__, __LINE__,
12977 _("Bad branch tracing read type: %u."),
12978 (unsigned int) type);
12979 }
12980
12981 xml = target_read_stralloc (&current_target,
12982 TARGET_OBJECT_BTRACE, annex);
12983 if (xml == NULL)
12984 return BTRACE_ERR_UNKNOWN;
12985
12986 cleanup = make_cleanup (xfree, xml);
12987 parse_xml_btrace (btrace, xml);
12988 do_cleanups (cleanup);
12989
12990 return BTRACE_ERR_NONE;
12991 }
12992
12993 static const struct btrace_config *
12994 remote_btrace_conf (struct target_ops *self,
12995 const struct btrace_target_info *tinfo)
12996 {
12997 return &tinfo->conf;
12998 }
12999
13000 static int
13001 remote_augmented_libraries_svr4_read (struct target_ops *self)
13002 {
13003 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13004 == PACKET_ENABLE);
13005 }
13006
13007 /* Implementation of to_load. */
13008
13009 static void
13010 remote_load (struct target_ops *self, const char *name, int from_tty)
13011 {
13012 generic_load (name, from_tty);
13013 }
13014
13015 /* Accepts an integer PID; returns a string representing a file that
13016 can be opened on the remote side to get the symbols for the child
13017 process. Returns NULL if the operation is not supported. */
13018
13019 static char *
13020 remote_pid_to_exec_file (struct target_ops *self, int pid)
13021 {
13022 static char *filename = NULL;
13023 struct inferior *inf;
13024 char *annex = NULL;
13025
13026 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13027 return NULL;
13028
13029 if (filename != NULL)
13030 xfree (filename);
13031
13032 inf = find_inferior_pid (pid);
13033 if (inf == NULL)
13034 internal_error (__FILE__, __LINE__,
13035 _("not currently attached to process %d"), pid);
13036
13037 if (!inf->fake_pid_p)
13038 {
13039 const int annex_size = 9;
13040
13041 annex = (char *) alloca (annex_size);
13042 xsnprintf (annex, annex_size, "%x", pid);
13043 }
13044
13045 filename = target_read_stralloc (&current_target,
13046 TARGET_OBJECT_EXEC_FILE, annex);
13047
13048 return filename;
13049 }
13050
13051 /* Implement the to_can_do_single_step target_ops method. */
13052
13053 static int
13054 remote_can_do_single_step (struct target_ops *ops)
13055 {
13056 /* We can only tell whether target supports single step or not by
13057 supported s and S vCont actions if the stub supports vContSupported
13058 feature. If the stub doesn't support vContSupported feature,
13059 we have conservatively to think target doesn't supports single
13060 step. */
13061 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13062 {
13063 struct remote_state *rs = get_remote_state ();
13064
13065 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13066 remote_vcont_probe (rs);
13067
13068 return rs->supports_vCont.s && rs->supports_vCont.S;
13069 }
13070 else
13071 return 0;
13072 }
13073
13074 /* Implementation of the to_execution_direction method for the remote
13075 target. */
13076
13077 static enum exec_direction_kind
13078 remote_execution_direction (struct target_ops *self)
13079 {
13080 struct remote_state *rs = get_remote_state ();
13081
13082 return rs->last_resume_exec_dir;
13083 }
13084
13085 static void
13086 init_remote_ops (void)
13087 {
13088 remote_ops.to_shortname = "remote";
13089 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13090 remote_ops.to_doc =
13091 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13092 Specify the serial device it is connected to\n\
13093 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13094 remote_ops.to_open = remote_open;
13095 remote_ops.to_close = remote_close;
13096 remote_ops.to_detach = remote_detach;
13097 remote_ops.to_disconnect = remote_disconnect;
13098 remote_ops.to_resume = remote_resume;
13099 remote_ops.to_wait = remote_wait;
13100 remote_ops.to_fetch_registers = remote_fetch_registers;
13101 remote_ops.to_store_registers = remote_store_registers;
13102 remote_ops.to_prepare_to_store = remote_prepare_to_store;
13103 remote_ops.to_files_info = remote_files_info;
13104 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13105 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13106 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13107 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13108 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13109 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13110 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13111 remote_ops.to_stopped_data_address = remote_stopped_data_address;
13112 remote_ops.to_watchpoint_addr_within_range =
13113 remote_watchpoint_addr_within_range;
13114 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13115 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13116 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13117 remote_ops.to_region_ok_for_hw_watchpoint
13118 = remote_region_ok_for_hw_watchpoint;
13119 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13120 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13121 remote_ops.to_kill = remote_kill;
13122 remote_ops.to_load = remote_load;
13123 remote_ops.to_mourn_inferior = remote_mourn;
13124 remote_ops.to_pass_signals = remote_pass_signals;
13125 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13126 remote_ops.to_program_signals = remote_program_signals;
13127 remote_ops.to_thread_alive = remote_thread_alive;
13128 remote_ops.to_thread_name = remote_thread_name;
13129 remote_ops.to_update_thread_list = remote_update_thread_list;
13130 remote_ops.to_pid_to_str = remote_pid_to_str;
13131 remote_ops.to_extra_thread_info = remote_threads_extra_info;
13132 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13133 remote_ops.to_stop = remote_stop;
13134 remote_ops.to_interrupt = remote_interrupt;
13135 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13136 remote_ops.to_xfer_partial = remote_xfer_partial;
13137 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
13138 remote_ops.to_rcmd = remote_rcmd;
13139 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13140 remote_ops.to_log_command = serial_log_command;
13141 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13142 remote_ops.to_stratum = process_stratum;
13143 remote_ops.to_has_all_memory = default_child_has_all_memory;
13144 remote_ops.to_has_memory = default_child_has_memory;
13145 remote_ops.to_has_stack = default_child_has_stack;
13146 remote_ops.to_has_registers = default_child_has_registers;
13147 remote_ops.to_has_execution = default_child_has_execution;
13148 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
13149 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13150 remote_ops.to_magic = OPS_MAGIC;
13151 remote_ops.to_memory_map = remote_memory_map;
13152 remote_ops.to_flash_erase = remote_flash_erase;
13153 remote_ops.to_flash_done = remote_flash_done;
13154 remote_ops.to_read_description = remote_read_description;
13155 remote_ops.to_search_memory = remote_search_memory;
13156 remote_ops.to_can_async_p = remote_can_async_p;
13157 remote_ops.to_is_async_p = remote_is_async_p;
13158 remote_ops.to_async = remote_async;
13159 remote_ops.to_thread_events = remote_thread_events;
13160 remote_ops.to_can_do_single_step = remote_can_do_single_step;
13161 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13162 remote_ops.to_terminal_ours = remote_terminal_ours;
13163 remote_ops.to_supports_non_stop = remote_supports_non_stop;
13164 remote_ops.to_supports_multi_process = remote_supports_multi_process;
13165 remote_ops.to_supports_disable_randomization
13166 = remote_supports_disable_randomization;
13167 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13168 remote_ops.to_fileio_open = remote_hostio_open;
13169 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13170 remote_ops.to_fileio_pread = remote_hostio_pread;
13171 remote_ops.to_fileio_fstat = remote_hostio_fstat;
13172 remote_ops.to_fileio_close = remote_hostio_close;
13173 remote_ops.to_fileio_unlink = remote_hostio_unlink;
13174 remote_ops.to_fileio_readlink = remote_hostio_readlink;
13175 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13176 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13177 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13178 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13179 remote_ops.to_trace_init = remote_trace_init;
13180 remote_ops.to_download_tracepoint = remote_download_tracepoint;
13181 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13182 remote_ops.to_download_trace_state_variable
13183 = remote_download_trace_state_variable;
13184 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13185 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13186 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13187 remote_ops.to_trace_start = remote_trace_start;
13188 remote_ops.to_get_trace_status = remote_get_trace_status;
13189 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13190 remote_ops.to_trace_stop = remote_trace_stop;
13191 remote_ops.to_trace_find = remote_trace_find;
13192 remote_ops.to_get_trace_state_variable_value
13193 = remote_get_trace_state_variable_value;
13194 remote_ops.to_save_trace_data = remote_save_trace_data;
13195 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13196 remote_ops.to_upload_trace_state_variables
13197 = remote_upload_trace_state_variables;
13198 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13199 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13200 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13201 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13202 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13203 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13204 remote_ops.to_core_of_thread = remote_core_of_thread;
13205 remote_ops.to_verify_memory = remote_verify_memory;
13206 remote_ops.to_get_tib_address = remote_get_tib_address;
13207 remote_ops.to_set_permissions = remote_set_permissions;
13208 remote_ops.to_static_tracepoint_marker_at
13209 = remote_static_tracepoint_marker_at;
13210 remote_ops.to_static_tracepoint_markers_by_strid
13211 = remote_static_tracepoint_markers_by_strid;
13212 remote_ops.to_traceframe_info = remote_traceframe_info;
13213 remote_ops.to_use_agent = remote_use_agent;
13214 remote_ops.to_can_use_agent = remote_can_use_agent;
13215 remote_ops.to_supports_btrace = remote_supports_btrace;
13216 remote_ops.to_enable_btrace = remote_enable_btrace;
13217 remote_ops.to_disable_btrace = remote_disable_btrace;
13218 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13219 remote_ops.to_read_btrace = remote_read_btrace;
13220 remote_ops.to_btrace_conf = remote_btrace_conf;
13221 remote_ops.to_augmented_libraries_svr4_read =
13222 remote_augmented_libraries_svr4_read;
13223 remote_ops.to_follow_fork = remote_follow_fork;
13224 remote_ops.to_follow_exec = remote_follow_exec;
13225 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13226 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13227 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13228 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13229 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13230 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13231 remote_ops.to_execution_direction = remote_execution_direction;
13232 }
13233
13234 /* Set up the extended remote vector by making a copy of the standard
13235 remote vector and adding to it. */
13236
13237 static void
13238 init_extended_remote_ops (void)
13239 {
13240 extended_remote_ops = remote_ops;
13241
13242 extended_remote_ops.to_shortname = "extended-remote";
13243 extended_remote_ops.to_longname =
13244 "Extended remote serial target in gdb-specific protocol";
13245 extended_remote_ops.to_doc =
13246 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13247 Specify the serial device it is connected to (e.g. /dev/ttya).";
13248 extended_remote_ops.to_open = extended_remote_open;
13249 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13250 extended_remote_ops.to_detach = extended_remote_detach;
13251 extended_remote_ops.to_attach = extended_remote_attach;
13252 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13253 extended_remote_ops.to_supports_disable_randomization
13254 = extended_remote_supports_disable_randomization;
13255 }
13256
13257 static int
13258 remote_can_async_p (struct target_ops *ops)
13259 {
13260 struct remote_state *rs = get_remote_state ();
13261
13262 if (!target_async_permitted)
13263 /* We only enable async when the user specifically asks for it. */
13264 return 0;
13265
13266 /* We're async whenever the serial device is. */
13267 return serial_can_async_p (rs->remote_desc);
13268 }
13269
13270 static int
13271 remote_is_async_p (struct target_ops *ops)
13272 {
13273 struct remote_state *rs = get_remote_state ();
13274
13275 if (!target_async_permitted)
13276 /* We only enable async when the user specifically asks for it. */
13277 return 0;
13278
13279 /* We're async whenever the serial device is. */
13280 return serial_is_async_p (rs->remote_desc);
13281 }
13282
13283 /* Pass the SERIAL event on and up to the client. One day this code
13284 will be able to delay notifying the client of an event until the
13285 point where an entire packet has been received. */
13286
13287 static serial_event_ftype remote_async_serial_handler;
13288
13289 static void
13290 remote_async_serial_handler (struct serial *scb, void *context)
13291 {
13292 /* Don't propogate error information up to the client. Instead let
13293 the client find out about the error by querying the target. */
13294 inferior_event_handler (INF_REG_EVENT, NULL);
13295 }
13296
13297 static void
13298 remote_async_inferior_event_handler (gdb_client_data data)
13299 {
13300 inferior_event_handler (INF_REG_EVENT, NULL);
13301 }
13302
13303 static void
13304 remote_async (struct target_ops *ops, int enable)
13305 {
13306 struct remote_state *rs = get_remote_state ();
13307
13308 if (enable)
13309 {
13310 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13311
13312 /* If there are pending events in the stop reply queue tell the
13313 event loop to process them. */
13314 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13315 mark_async_event_handler (remote_async_inferior_event_token);
13316 /* For simplicity, below we clear the pending events token
13317 without remembering whether it is marked, so here we always
13318 mark it. If there's actually no pending notification to
13319 process, this ends up being a no-op (other than a spurious
13320 event-loop wakeup). */
13321 if (target_is_non_stop_p ())
13322 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13323 }
13324 else
13325 {
13326 serial_async (rs->remote_desc, NULL, NULL);
13327 /* If the core is disabling async, it doesn't want to be
13328 disturbed with target events. Clear all async event sources
13329 too. */
13330 clear_async_event_handler (remote_async_inferior_event_token);
13331 if (target_is_non_stop_p ())
13332 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13333 }
13334 }
13335
13336 /* Implementation of the to_thread_events method. */
13337
13338 static void
13339 remote_thread_events (struct target_ops *ops, int enable)
13340 {
13341 struct remote_state *rs = get_remote_state ();
13342 size_t size = get_remote_packet_size ();
13343
13344 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13345 return;
13346
13347 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13348 putpkt (rs->buf);
13349 getpkt (&rs->buf, &rs->buf_size, 0);
13350
13351 switch (packet_ok (rs->buf,
13352 &remote_protocol_packets[PACKET_QThreadEvents]))
13353 {
13354 case PACKET_OK:
13355 if (strcmp (rs->buf, "OK") != 0)
13356 error (_("Remote refused setting thread events: %s"), rs->buf);
13357 break;
13358 case PACKET_ERROR:
13359 warning (_("Remote failure reply: %s"), rs->buf);
13360 break;
13361 case PACKET_UNKNOWN:
13362 break;
13363 }
13364 }
13365
13366 static void
13367 set_remote_cmd (char *args, int from_tty)
13368 {
13369 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13370 }
13371
13372 static void
13373 show_remote_cmd (char *args, int from_tty)
13374 {
13375 /* We can't just use cmd_show_list here, because we want to skip
13376 the redundant "show remote Z-packet" and the legacy aliases. */
13377 struct cleanup *showlist_chain;
13378 struct cmd_list_element *list = remote_show_cmdlist;
13379 struct ui_out *uiout = current_uiout;
13380
13381 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13382 for (; list != NULL; list = list->next)
13383 if (strcmp (list->name, "Z-packet") == 0)
13384 continue;
13385 else if (list->type == not_set_cmd)
13386 /* Alias commands are exactly like the original, except they
13387 don't have the normal type. */
13388 continue;
13389 else
13390 {
13391 struct cleanup *option_chain
13392 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13393
13394 ui_out_field_string (uiout, "name", list->name);
13395 ui_out_text (uiout, ": ");
13396 if (list->type == show_cmd)
13397 do_show_command ((char *) NULL, from_tty, list);
13398 else
13399 cmd_func (list, NULL, from_tty);
13400 /* Close the tuple. */
13401 do_cleanups (option_chain);
13402 }
13403
13404 /* Close the tuple. */
13405 do_cleanups (showlist_chain);
13406 }
13407
13408
13409 /* Function to be called whenever a new objfile (shlib) is detected. */
13410 static void
13411 remote_new_objfile (struct objfile *objfile)
13412 {
13413 struct remote_state *rs = get_remote_state ();
13414
13415 if (rs->remote_desc != 0) /* Have a remote connection. */
13416 remote_check_symbols ();
13417 }
13418
13419 /* Pull all the tracepoints defined on the target and create local
13420 data structures representing them. We don't want to create real
13421 tracepoints yet, we don't want to mess up the user's existing
13422 collection. */
13423
13424 static int
13425 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13426 {
13427 struct remote_state *rs = get_remote_state ();
13428 char *p;
13429
13430 /* Ask for a first packet of tracepoint definition. */
13431 putpkt ("qTfP");
13432 getpkt (&rs->buf, &rs->buf_size, 0);
13433 p = rs->buf;
13434 while (*p && *p != 'l')
13435 {
13436 parse_tracepoint_definition (p, utpp);
13437 /* Ask for another packet of tracepoint definition. */
13438 putpkt ("qTsP");
13439 getpkt (&rs->buf, &rs->buf_size, 0);
13440 p = rs->buf;
13441 }
13442 return 0;
13443 }
13444
13445 static int
13446 remote_upload_trace_state_variables (struct target_ops *self,
13447 struct uploaded_tsv **utsvp)
13448 {
13449 struct remote_state *rs = get_remote_state ();
13450 char *p;
13451
13452 /* Ask for a first packet of variable definition. */
13453 putpkt ("qTfV");
13454 getpkt (&rs->buf, &rs->buf_size, 0);
13455 p = rs->buf;
13456 while (*p && *p != 'l')
13457 {
13458 parse_tsv_definition (p, utsvp);
13459 /* Ask for another packet of variable definition. */
13460 putpkt ("qTsV");
13461 getpkt (&rs->buf, &rs->buf_size, 0);
13462 p = rs->buf;
13463 }
13464 return 0;
13465 }
13466
13467 /* The "set/show range-stepping" show hook. */
13468
13469 static void
13470 show_range_stepping (struct ui_file *file, int from_tty,
13471 struct cmd_list_element *c,
13472 const char *value)
13473 {
13474 fprintf_filtered (file,
13475 _("Debugger's willingness to use range stepping "
13476 "is %s.\n"), value);
13477 }
13478
13479 /* The "set/show range-stepping" set hook. */
13480
13481 static void
13482 set_range_stepping (char *ignore_args, int from_tty,
13483 struct cmd_list_element *c)
13484 {
13485 struct remote_state *rs = get_remote_state ();
13486
13487 /* Whene enabling, check whether range stepping is actually
13488 supported by the target, and warn if not. */
13489 if (use_range_stepping)
13490 {
13491 if (rs->remote_desc != NULL)
13492 {
13493 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13494 remote_vcont_probe (rs);
13495
13496 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13497 && rs->supports_vCont.r)
13498 return;
13499 }
13500
13501 warning (_("Range stepping is not supported by the current target"));
13502 }
13503 }
13504
13505 void
13506 _initialize_remote (void)
13507 {
13508 struct cmd_list_element *cmd;
13509 const char *cmd_name;
13510
13511 /* architecture specific data */
13512 remote_gdbarch_data_handle =
13513 gdbarch_data_register_post_init (init_remote_state);
13514 remote_g_packet_data_handle =
13515 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13516
13517 remote_pspace_data
13518 = register_program_space_data_with_cleanup (NULL,
13519 remote_pspace_data_cleanup);
13520
13521 /* Initialize the per-target state. At the moment there is only one
13522 of these, not one per target. Only one target is active at a
13523 time. */
13524 remote_state = new_remote_state ();
13525
13526 init_remote_ops ();
13527 add_target (&remote_ops);
13528
13529 init_extended_remote_ops ();
13530 add_target (&extended_remote_ops);
13531
13532 /* Hook into new objfile notification. */
13533 observer_attach_new_objfile (remote_new_objfile);
13534 /* We're no longer interested in notification events of an inferior
13535 when it exits. */
13536 observer_attach_inferior_exit (discard_pending_stop_replies);
13537
13538 #if 0
13539 init_remote_threadtests ();
13540 #endif
13541
13542 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13543 /* set/show remote ... */
13544
13545 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13546 Remote protocol specific variables\n\
13547 Configure various remote-protocol specific variables such as\n\
13548 the packets being used"),
13549 &remote_set_cmdlist, "set remote ",
13550 0 /* allow-unknown */, &setlist);
13551 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13552 Remote protocol specific variables\n\
13553 Configure various remote-protocol specific variables such as\n\
13554 the packets being used"),
13555 &remote_show_cmdlist, "show remote ",
13556 0 /* allow-unknown */, &showlist);
13557
13558 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13559 Compare section data on target to the exec file.\n\
13560 Argument is a single section name (default: all loaded sections).\n\
13561 To compare only read-only loaded sections, specify the -r option."),
13562 &cmdlist);
13563
13564 add_cmd ("packet", class_maintenance, packet_command, _("\
13565 Send an arbitrary packet to a remote target.\n\
13566 maintenance packet TEXT\n\
13567 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13568 this command sends the string TEXT to the inferior, and displays the\n\
13569 response packet. GDB supplies the initial `$' character, and the\n\
13570 terminating `#' character and checksum."),
13571 &maintenancelist);
13572
13573 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13574 Set whether to send break if interrupted."), _("\
13575 Show whether to send break if interrupted."), _("\
13576 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13577 set_remotebreak, show_remotebreak,
13578 &setlist, &showlist);
13579 cmd_name = "remotebreak";
13580 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13581 deprecate_cmd (cmd, "set remote interrupt-sequence");
13582 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13583 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13584 deprecate_cmd (cmd, "show remote interrupt-sequence");
13585
13586 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13587 interrupt_sequence_modes, &interrupt_sequence_mode,
13588 _("\
13589 Set interrupt sequence to remote target."), _("\
13590 Show interrupt sequence to remote target."), _("\
13591 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13592 NULL, show_interrupt_sequence,
13593 &remote_set_cmdlist,
13594 &remote_show_cmdlist);
13595
13596 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13597 &interrupt_on_connect, _("\
13598 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13599 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13600 If set, interrupt sequence is sent to remote target."),
13601 NULL, NULL,
13602 &remote_set_cmdlist, &remote_show_cmdlist);
13603
13604 /* Install commands for configuring memory read/write packets. */
13605
13606 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13607 Set the maximum number of bytes per memory write packet (deprecated)."),
13608 &setlist);
13609 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13610 Show the maximum number of bytes per memory write packet (deprecated)."),
13611 &showlist);
13612 add_cmd ("memory-write-packet-size", no_class,
13613 set_memory_write_packet_size, _("\
13614 Set the maximum number of bytes per memory-write packet.\n\
13615 Specify the number of bytes in a packet or 0 (zero) for the\n\
13616 default packet size. The actual limit is further reduced\n\
13617 dependent on the target. Specify ``fixed'' to disable the\n\
13618 further restriction and ``limit'' to enable that restriction."),
13619 &remote_set_cmdlist);
13620 add_cmd ("memory-read-packet-size", no_class,
13621 set_memory_read_packet_size, _("\
13622 Set the maximum number of bytes per memory-read packet.\n\
13623 Specify the number of bytes in a packet or 0 (zero) for the\n\
13624 default packet size. The actual limit is further reduced\n\
13625 dependent on the target. Specify ``fixed'' to disable the\n\
13626 further restriction and ``limit'' to enable that restriction."),
13627 &remote_set_cmdlist);
13628 add_cmd ("memory-write-packet-size", no_class,
13629 show_memory_write_packet_size,
13630 _("Show the maximum number of bytes per memory-write packet."),
13631 &remote_show_cmdlist);
13632 add_cmd ("memory-read-packet-size", no_class,
13633 show_memory_read_packet_size,
13634 _("Show the maximum number of bytes per memory-read packet."),
13635 &remote_show_cmdlist);
13636
13637 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13638 &remote_hw_watchpoint_limit, _("\
13639 Set the maximum number of target hardware watchpoints."), _("\
13640 Show the maximum number of target hardware watchpoints."), _("\
13641 Specify a negative limit for unlimited."),
13642 NULL, NULL, /* FIXME: i18n: The maximum
13643 number of target hardware
13644 watchpoints is %s. */
13645 &remote_set_cmdlist, &remote_show_cmdlist);
13646 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13647 &remote_hw_watchpoint_length_limit, _("\
13648 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13649 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13650 Specify a negative limit for unlimited."),
13651 NULL, NULL, /* FIXME: i18n: The maximum
13652 length (in bytes) of a target
13653 hardware watchpoint is %s. */
13654 &remote_set_cmdlist, &remote_show_cmdlist);
13655 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13656 &remote_hw_breakpoint_limit, _("\
13657 Set the maximum number of target hardware breakpoints."), _("\
13658 Show the maximum number of target hardware breakpoints."), _("\
13659 Specify a negative limit for unlimited."),
13660 NULL, NULL, /* FIXME: i18n: The maximum
13661 number of target hardware
13662 breakpoints is %s. */
13663 &remote_set_cmdlist, &remote_show_cmdlist);
13664
13665 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13666 &remote_address_size, _("\
13667 Set the maximum size of the address (in bits) in a memory packet."), _("\
13668 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13669 NULL,
13670 NULL, /* FIXME: i18n: */
13671 &setlist, &showlist);
13672
13673 init_all_packet_configs ();
13674
13675 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13676 "X", "binary-download", 1);
13677
13678 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13679 "vCont", "verbose-resume", 0);
13680
13681 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13682 "QPassSignals", "pass-signals", 0);
13683
13684 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13685 "QCatchSyscalls", "catch-syscalls", 0);
13686
13687 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13688 "QProgramSignals", "program-signals", 0);
13689
13690 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13691 "qSymbol", "symbol-lookup", 0);
13692
13693 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13694 "P", "set-register", 1);
13695
13696 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13697 "p", "fetch-register", 1);
13698
13699 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13700 "Z0", "software-breakpoint", 0);
13701
13702 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13703 "Z1", "hardware-breakpoint", 0);
13704
13705 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13706 "Z2", "write-watchpoint", 0);
13707
13708 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13709 "Z3", "read-watchpoint", 0);
13710
13711 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13712 "Z4", "access-watchpoint", 0);
13713
13714 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13715 "qXfer:auxv:read", "read-aux-vector", 0);
13716
13717 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13718 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13719
13720 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13721 "qXfer:features:read", "target-features", 0);
13722
13723 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13724 "qXfer:libraries:read", "library-info", 0);
13725
13726 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13727 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13728
13729 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13730 "qXfer:memory-map:read", "memory-map", 0);
13731
13732 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13733 "qXfer:spu:read", "read-spu-object", 0);
13734
13735 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13736 "qXfer:spu:write", "write-spu-object", 0);
13737
13738 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13739 "qXfer:osdata:read", "osdata", 0);
13740
13741 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13742 "qXfer:threads:read", "threads", 0);
13743
13744 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13745 "qXfer:siginfo:read", "read-siginfo-object", 0);
13746
13747 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13748 "qXfer:siginfo:write", "write-siginfo-object", 0);
13749
13750 add_packet_config_cmd
13751 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13752 "qXfer:traceframe-info:read", "traceframe-info", 0);
13753
13754 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13755 "qXfer:uib:read", "unwind-info-block", 0);
13756
13757 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13758 "qGetTLSAddr", "get-thread-local-storage-address",
13759 0);
13760
13761 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13762 "qGetTIBAddr", "get-thread-information-block-address",
13763 0);
13764
13765 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13766 "bc", "reverse-continue", 0);
13767
13768 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13769 "bs", "reverse-step", 0);
13770
13771 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13772 "qSupported", "supported-packets", 0);
13773
13774 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13775 "qSearch:memory", "search-memory", 0);
13776
13777 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13778 "qTStatus", "trace-status", 0);
13779
13780 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13781 "vFile:setfs", "hostio-setfs", 0);
13782
13783 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13784 "vFile:open", "hostio-open", 0);
13785
13786 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13787 "vFile:pread", "hostio-pread", 0);
13788
13789 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13790 "vFile:pwrite", "hostio-pwrite", 0);
13791
13792 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13793 "vFile:close", "hostio-close", 0);
13794
13795 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13796 "vFile:unlink", "hostio-unlink", 0);
13797
13798 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13799 "vFile:readlink", "hostio-readlink", 0);
13800
13801 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13802 "vFile:fstat", "hostio-fstat", 0);
13803
13804 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13805 "vAttach", "attach", 0);
13806
13807 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13808 "vRun", "run", 0);
13809
13810 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13811 "QStartNoAckMode", "noack", 0);
13812
13813 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13814 "vKill", "kill", 0);
13815
13816 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13817 "qAttached", "query-attached", 0);
13818
13819 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13820 "ConditionalTracepoints",
13821 "conditional-tracepoints", 0);
13822
13823 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13824 "ConditionalBreakpoints",
13825 "conditional-breakpoints", 0);
13826
13827 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13828 "BreakpointCommands",
13829 "breakpoint-commands", 0);
13830
13831 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13832 "FastTracepoints", "fast-tracepoints", 0);
13833
13834 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13835 "TracepointSource", "TracepointSource", 0);
13836
13837 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13838 "QAllow", "allow", 0);
13839
13840 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13841 "StaticTracepoints", "static-tracepoints", 0);
13842
13843 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13844 "InstallInTrace", "install-in-trace", 0);
13845
13846 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13847 "qXfer:statictrace:read", "read-sdata-object", 0);
13848
13849 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13850 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13851
13852 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13853 "QDisableRandomization", "disable-randomization", 0);
13854
13855 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13856 "QAgent", "agent", 0);
13857
13858 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13859 "QTBuffer:size", "trace-buffer-size", 0);
13860
13861 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13862 "Qbtrace:off", "disable-btrace", 0);
13863
13864 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13865 "Qbtrace:bts", "enable-btrace-bts", 0);
13866
13867 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13868 "Qbtrace:pt", "enable-btrace-pt", 0);
13869
13870 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13871 "qXfer:btrace", "read-btrace", 0);
13872
13873 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13874 "qXfer:btrace-conf", "read-btrace-conf", 0);
13875
13876 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13877 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13878
13879 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13880 "multiprocess-feature", "multiprocess-feature", 0);
13881
13882 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13883 "swbreak-feature", "swbreak-feature", 0);
13884
13885 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13886 "hwbreak-feature", "hwbreak-feature", 0);
13887
13888 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13889 "fork-event-feature", "fork-event-feature", 0);
13890
13891 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13892 "vfork-event-feature", "vfork-event-feature", 0);
13893
13894 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13895 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13896
13897 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13898 "vContSupported", "verbose-resume-supported", 0);
13899
13900 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13901 "exec-event-feature", "exec-event-feature", 0);
13902
13903 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13904 "vCtrlC", "ctrl-c", 0);
13905
13906 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13907 "QThreadEvents", "thread-events", 0);
13908
13909 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13910 "N stop reply", "no-resumed-stop-reply", 0);
13911
13912 /* Assert that we've registered "set remote foo-packet" commands
13913 for all packet configs. */
13914 {
13915 int i;
13916
13917 for (i = 0; i < PACKET_MAX; i++)
13918 {
13919 /* Ideally all configs would have a command associated. Some
13920 still don't though. */
13921 int excepted;
13922
13923 switch (i)
13924 {
13925 case PACKET_QNonStop:
13926 case PACKET_EnableDisableTracepoints_feature:
13927 case PACKET_tracenz_feature:
13928 case PACKET_DisconnectedTracing_feature:
13929 case PACKET_augmented_libraries_svr4_read_feature:
13930 case PACKET_qCRC:
13931 /* Additions to this list need to be well justified:
13932 pre-existing packets are OK; new packets are not. */
13933 excepted = 1;
13934 break;
13935 default:
13936 excepted = 0;
13937 break;
13938 }
13939
13940 /* This catches both forgetting to add a config command, and
13941 forgetting to remove a packet from the exception list. */
13942 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13943 }
13944 }
13945
13946 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13947 Z sub-packet has its own set and show commands, but users may
13948 have sets to this variable in their .gdbinit files (or in their
13949 documentation). */
13950 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13951 &remote_Z_packet_detect, _("\
13952 Set use of remote protocol `Z' packets"), _("\
13953 Show use of remote protocol `Z' packets "), _("\
13954 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13955 packets."),
13956 set_remote_protocol_Z_packet_cmd,
13957 show_remote_protocol_Z_packet_cmd,
13958 /* FIXME: i18n: Use of remote protocol
13959 `Z' packets is %s. */
13960 &remote_set_cmdlist, &remote_show_cmdlist);
13961
13962 add_prefix_cmd ("remote", class_files, remote_command, _("\
13963 Manipulate files on the remote system\n\
13964 Transfer files to and from the remote target system."),
13965 &remote_cmdlist, "remote ",
13966 0 /* allow-unknown */, &cmdlist);
13967
13968 add_cmd ("put", class_files, remote_put_command,
13969 _("Copy a local file to the remote system."),
13970 &remote_cmdlist);
13971
13972 add_cmd ("get", class_files, remote_get_command,
13973 _("Copy a remote file to the local system."),
13974 &remote_cmdlist);
13975
13976 add_cmd ("delete", class_files, remote_delete_command,
13977 _("Delete a remote file."),
13978 &remote_cmdlist);
13979
13980 add_setshow_string_noescape_cmd ("exec-file", class_files,
13981 &remote_exec_file_var, _("\
13982 Set the remote pathname for \"run\""), _("\
13983 Show the remote pathname for \"run\""), NULL,
13984 set_remote_exec_file,
13985 show_remote_exec_file,
13986 &remote_set_cmdlist,
13987 &remote_show_cmdlist);
13988
13989 add_setshow_boolean_cmd ("range-stepping", class_run,
13990 &use_range_stepping, _("\
13991 Enable or disable range stepping."), _("\
13992 Show whether target-assisted range stepping is enabled."), _("\
13993 If on, and the target supports it, when stepping a source line, GDB\n\
13994 tells the target to step the corresponding range of addresses itself instead\n\
13995 of issuing multiple single-steps. This speeds up source level\n\
13996 stepping. If off, GDB always issues single-steps, even if range\n\
13997 stepping is supported by the target. The default is on."),
13998 set_range_stepping,
13999 show_range_stepping,
14000 &setlist,
14001 &showlist);
14002
14003 /* Eventually initialize fileio. See fileio.c */
14004 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14005
14006 /* Take advantage of the fact that the TID field is not used, to tag
14007 special ptids with it set to != 0. */
14008 magic_null_ptid = ptid_build (42000, -1, 1);
14009 not_sent_ptid = ptid_build (42000, -2, 1);
14010 any_thread_ptid = ptid_build (42000, 0, 1);
14011
14012 target_buf_size = 2048;
14013 target_buf = (char *) xmalloc (target_buf_size);
14014 }
14015
This page took 0.305304 seconds and 5 git commands to generate.