btrace: fix test build error in gdb.btrace/instruction_history.c
[deliverable/binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2016 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observer.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73
74 /* Temp hacks for tracepoint encoding migration. */
75 static char *target_buf;
76 static long target_buf_size;
77
78 /* Per-program-space data key. */
79 static const struct program_space_data *remote_pspace_data;
80
81 /* The variable registered as the control variable used by the
82 remote exec-file commands. While the remote exec-file setting is
83 per-program-space, the set/show machinery uses this as the
84 location of the remote exec-file value. */
85 static char *remote_exec_file_var;
86
87 /* The size to align memory write packets, when practical. The protocol
88 does not guarantee any alignment, and gdb will generate short
89 writes and unaligned writes, but even as a best-effort attempt this
90 can improve bulk transfers. For instance, if a write is misaligned
91 relative to the target's data bus, the stub may need to make an extra
92 round trip fetching data from the target. This doesn't make a
93 huge difference, but it's easy to do, so we try to be helpful.
94
95 The alignment chosen is arbitrary; usually data bus width is
96 important here, not the possibly larger cache line size. */
97 enum { REMOTE_ALIGN_WRITES = 16 };
98
99 /* Prototypes for local functions. */
100 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
101 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
102 int forever, int *is_notif);
103
104 static void remote_files_info (struct target_ops *ignore);
105
106 static void remote_prepare_to_store (struct target_ops *self,
107 struct regcache *regcache);
108
109 static void remote_open_1 (const char *, int, struct target_ops *,
110 int extended_p);
111
112 static void remote_close (struct target_ops *self);
113
114 struct remote_state;
115
116 static int remote_vkill (int pid, struct remote_state *rs);
117
118 static void remote_kill_k (void);
119
120 static void remote_mourn (struct target_ops *ops);
121
122 static void extended_remote_restart (void);
123
124 static void remote_send (char **buf, long *sizeof_buf_p);
125
126 static int readchar (int timeout);
127
128 static void remote_serial_write (const char *str, int len);
129
130 static void remote_kill (struct target_ops *ops);
131
132 static int remote_can_async_p (struct target_ops *);
133
134 static int remote_is_async_p (struct target_ops *);
135
136 static void remote_async (struct target_ops *ops, int enable);
137
138 static void remote_thread_events (struct target_ops *ops, int enable);
139
140 static void interrupt_query (void);
141
142 static void set_general_thread (struct ptid ptid);
143 static void set_continue_thread (struct ptid ptid);
144
145 static void get_offsets (void);
146
147 static void skip_frame (void);
148
149 static long read_frame (char **buf_p, long *sizeof_buf);
150
151 static int hexnumlen (ULONGEST num);
152
153 static void init_remote_ops (void);
154
155 static void init_extended_remote_ops (void);
156
157 static void remote_stop (struct target_ops *self, ptid_t);
158
159 static int stubhex (int ch);
160
161 static int hexnumstr (char *, ULONGEST);
162
163 static int hexnumnstr (char *, ULONGEST, int);
164
165 static CORE_ADDR remote_address_masked (CORE_ADDR);
166
167 static void print_packet (const char *);
168
169 static void compare_sections_command (char *, int);
170
171 static void packet_command (char *, int);
172
173 static int stub_unpack_int (char *buff, int fieldlength);
174
175 static ptid_t remote_current_thread (ptid_t oldptid);
176
177 static int putpkt_binary (const char *buf, int cnt);
178
179 static void check_binary_download (CORE_ADDR addr);
180
181 struct packet_config;
182
183 static void show_packet_config_cmd (struct packet_config *config);
184
185 static void show_remote_protocol_packet_cmd (struct ui_file *file,
186 int from_tty,
187 struct cmd_list_element *c,
188 const char *value);
189
190 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
191 static ptid_t read_ptid (char *buf, char **obuf);
192
193 static void remote_set_permissions (struct target_ops *self);
194
195 static int remote_get_trace_status (struct target_ops *self,
196 struct trace_status *ts);
197
198 static int remote_upload_tracepoints (struct target_ops *self,
199 struct uploaded_tp **utpp);
200
201 static int remote_upload_trace_state_variables (struct target_ops *self,
202 struct uploaded_tsv **utsvp);
203
204 static void remote_query_supported (void);
205
206 static void remote_check_symbols (void);
207
208 void _initialize_remote (void);
209
210 struct stop_reply;
211 static void stop_reply_xfree (struct stop_reply *);
212 static void remote_parse_stop_reply (char *, struct stop_reply *);
213 static void push_stop_reply (struct stop_reply *);
214 static void discard_pending_stop_replies_in_queue (struct remote_state *);
215 static int peek_stop_reply (ptid_t ptid);
216
217 struct threads_listing_context;
218 static void remove_new_fork_children (struct threads_listing_context *);
219
220 static void remote_async_inferior_event_handler (gdb_client_data);
221
222 static void remote_terminal_ours (struct target_ops *self);
223
224 static int remote_read_description_p (struct target_ops *target);
225
226 static void remote_console_output (char *msg);
227
228 static int remote_supports_cond_breakpoints (struct target_ops *self);
229
230 static int remote_can_run_breakpoint_commands (struct target_ops *self);
231
232 static void remote_btrace_reset (void);
233
234 static int stop_reply_queue_length (void);
235
236 static void readahead_cache_invalidate (void);
237
238 static void remote_unpush_and_throw (void);
239
240 /* For "remote". */
241
242 static struct cmd_list_element *remote_cmdlist;
243
244 /* For "set remote" and "show remote". */
245
246 static struct cmd_list_element *remote_set_cmdlist;
247 static struct cmd_list_element *remote_show_cmdlist;
248
249 /* Stub vCont actions support.
250
251 Each field is a boolean flag indicating whether the stub reports
252 support for the corresponding action. */
253
254 struct vCont_action_support
255 {
256 /* vCont;t */
257 int t;
258
259 /* vCont;r */
260 int r;
261
262 /* vCont;s */
263 int s;
264
265 /* vCont;S */
266 int S;
267 };
268
269 /* Controls whether GDB is willing to use range stepping. */
270
271 static int use_range_stepping = 1;
272
273 #define OPAQUETHREADBYTES 8
274
275 /* a 64 bit opaque identifier */
276 typedef unsigned char threadref[OPAQUETHREADBYTES];
277
278 /* About this many threadisds fit in a packet. */
279
280 #define MAXTHREADLISTRESULTS 32
281
282 /* Data for the vFile:pread readahead cache. */
283
284 struct readahead_cache
285 {
286 /* The file descriptor for the file that is being cached. -1 if the
287 cache is invalid. */
288 int fd;
289
290 /* The offset into the file that the cache buffer corresponds
291 to. */
292 ULONGEST offset;
293
294 /* The buffer holding the cache contents. */
295 gdb_byte *buf;
296 /* The buffer's size. We try to read as much as fits into a packet
297 at a time. */
298 size_t bufsize;
299
300 /* Cache hit and miss counters. */
301 ULONGEST hit_count;
302 ULONGEST miss_count;
303 };
304
305 /* Description of the remote protocol state for the currently
306 connected target. This is per-target state, and independent of the
307 selected architecture. */
308
309 struct remote_state
310 {
311 /* A buffer to use for incoming packets, and its current size. The
312 buffer is grown dynamically for larger incoming packets.
313 Outgoing packets may also be constructed in this buffer.
314 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
315 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
316 packets. */
317 char *buf;
318 long buf_size;
319
320 /* True if we're going through initial connection setup (finding out
321 about the remote side's threads, relocating symbols, etc.). */
322 int starting_up;
323
324 /* If we negotiated packet size explicitly (and thus can bypass
325 heuristics for the largest packet size that will not overflow
326 a buffer in the stub), this will be set to that packet size.
327 Otherwise zero, meaning to use the guessed size. */
328 long explicit_packet_size;
329
330 /* remote_wait is normally called when the target is running and
331 waits for a stop reply packet. But sometimes we need to call it
332 when the target is already stopped. We can send a "?" packet
333 and have remote_wait read the response. Or, if we already have
334 the response, we can stash it in BUF and tell remote_wait to
335 skip calling getpkt. This flag is set when BUF contains a
336 stop reply packet and the target is not waiting. */
337 int cached_wait_status;
338
339 /* True, if in no ack mode. That is, neither GDB nor the stub will
340 expect acks from each other. The connection is assumed to be
341 reliable. */
342 int noack_mode;
343
344 /* True if we're connected in extended remote mode. */
345 int extended;
346
347 /* True if we resumed the target and we're waiting for the target to
348 stop. In the mean time, we can't start another command/query.
349 The remote server wouldn't be ready to process it, so we'd
350 timeout waiting for a reply that would never come and eventually
351 we'd close the connection. This can happen in asynchronous mode
352 because we allow GDB commands while the target is running. */
353 int waiting_for_stop_reply;
354
355 /* The status of the stub support for the various vCont actions. */
356 struct vCont_action_support supports_vCont;
357
358 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
359 responded to that. */
360 int ctrlc_pending_p;
361
362 /* True if we saw a Ctrl-C while reading or writing from/to the
363 remote descriptor. At that point it is not safe to send a remote
364 interrupt packet, so we instead remember we saw the Ctrl-C and
365 process it once we're done with sending/receiving the current
366 packet, which should be shortly. If however that takes too long,
367 and the user presses Ctrl-C again, we offer to disconnect. */
368 int got_ctrlc_during_io;
369
370 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
371 remote_open knows that we don't have a file open when the program
372 starts. */
373 struct serial *remote_desc;
374
375 /* These are the threads which we last sent to the remote system. The
376 TID member will be -1 for all or -2 for not sent yet. */
377 ptid_t general_thread;
378 ptid_t continue_thread;
379
380 /* This is the traceframe which we last selected on the remote system.
381 It will be -1 if no traceframe is selected. */
382 int remote_traceframe_number;
383
384 char *last_pass_packet;
385
386 /* The last QProgramSignals packet sent to the target. We bypass
387 sending a new program signals list down to the target if the new
388 packet is exactly the same as the last we sent. IOW, we only let
389 the target know about program signals list changes. */
390 char *last_program_signals_packet;
391
392 enum gdb_signal last_sent_signal;
393
394 int last_sent_step;
395
396 char *finished_object;
397 char *finished_annex;
398 ULONGEST finished_offset;
399
400 /* Should we try the 'ThreadInfo' query packet?
401
402 This variable (NOT available to the user: auto-detect only!)
403 determines whether GDB will use the new, simpler "ThreadInfo"
404 query or the older, more complex syntax for thread queries.
405 This is an auto-detect variable (set to true at each connect,
406 and set to false when the target fails to recognize it). */
407 int use_threadinfo_query;
408 int use_threadextra_query;
409
410 threadref echo_nextthread;
411 threadref nextthread;
412 threadref resultthreadlist[MAXTHREADLISTRESULTS];
413
414 /* The state of remote notification. */
415 struct remote_notif_state *notif_state;
416
417 /* The branch trace configuration. */
418 struct btrace_config btrace_config;
419
420 /* The argument to the last "vFile:setfs:" packet we sent, used
421 to avoid sending repeated unnecessary "vFile:setfs:" packets.
422 Initialized to -1 to indicate that no "vFile:setfs:" packet
423 has yet been sent. */
424 int fs_pid;
425
426 /* A readahead cache for vFile:pread. Often, reading a binary
427 involves a sequence of small reads. E.g., when parsing an ELF
428 file. A readahead cache helps mostly the case of remote
429 debugging on a connection with higher latency, due to the
430 request/reply nature of the RSP. We only cache data for a single
431 file descriptor at a time. */
432 struct readahead_cache readahead_cache;
433 };
434
435 /* Private data that we'll store in (struct thread_info)->private. */
436 struct private_thread_info
437 {
438 char *extra;
439 char *name;
440 int core;
441
442 /* Whether the target stopped for a breakpoint/watchpoint. */
443 enum target_stop_reason stop_reason;
444
445 /* This is set to the data address of the access causing the target
446 to stop for a watchpoint. */
447 CORE_ADDR watch_data_address;
448 };
449
450 static void
451 free_private_thread_info (struct private_thread_info *info)
452 {
453 xfree (info->extra);
454 xfree (info->name);
455 xfree (info);
456 }
457
458 /* This data could be associated with a target, but we do not always
459 have access to the current target when we need it, so for now it is
460 static. This will be fine for as long as only one target is in use
461 at a time. */
462 static struct remote_state *remote_state;
463
464 static struct remote_state *
465 get_remote_state_raw (void)
466 {
467 return remote_state;
468 }
469
470 /* Allocate a new struct remote_state with xmalloc, initialize it, and
471 return it. */
472
473 static struct remote_state *
474 new_remote_state (void)
475 {
476 struct remote_state *result = XCNEW (struct remote_state);
477
478 /* The default buffer size is unimportant; it will be expanded
479 whenever a larger buffer is needed. */
480 result->buf_size = 400;
481 result->buf = (char *) xmalloc (result->buf_size);
482 result->remote_traceframe_number = -1;
483 result->last_sent_signal = GDB_SIGNAL_0;
484 result->fs_pid = -1;
485
486 return result;
487 }
488
489 /* Description of the remote protocol for a given architecture. */
490
491 struct packet_reg
492 {
493 long offset; /* Offset into G packet. */
494 long regnum; /* GDB's internal register number. */
495 LONGEST pnum; /* Remote protocol register number. */
496 int in_g_packet; /* Always part of G packet. */
497 /* long size in bytes; == register_size (target_gdbarch (), regnum);
498 at present. */
499 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
500 at present. */
501 };
502
503 struct remote_arch_state
504 {
505 /* Description of the remote protocol registers. */
506 long sizeof_g_packet;
507
508 /* Description of the remote protocol registers indexed by REGNUM
509 (making an array gdbarch_num_regs in size). */
510 struct packet_reg *regs;
511
512 /* This is the size (in chars) of the first response to the ``g''
513 packet. It is used as a heuristic when determining the maximum
514 size of memory-read and memory-write packets. A target will
515 typically only reserve a buffer large enough to hold the ``g''
516 packet. The size does not include packet overhead (headers and
517 trailers). */
518 long actual_register_packet_size;
519
520 /* This is the maximum size (in chars) of a non read/write packet.
521 It is also used as a cap on the size of read/write packets. */
522 long remote_packet_size;
523 };
524
525 /* Utility: generate error from an incoming stub packet. */
526 static void
527 trace_error (char *buf)
528 {
529 if (*buf++ != 'E')
530 return; /* not an error msg */
531 switch (*buf)
532 {
533 case '1': /* malformed packet error */
534 if (*++buf == '0') /* general case: */
535 error (_("remote.c: error in outgoing packet."));
536 else
537 error (_("remote.c: error in outgoing packet at field #%ld."),
538 strtol (buf, NULL, 16));
539 default:
540 error (_("Target returns error code '%s'."), buf);
541 }
542 }
543
544 /* Utility: wait for reply from stub, while accepting "O" packets. */
545 static char *
546 remote_get_noisy_reply (char **buf_p,
547 long *sizeof_buf)
548 {
549 do /* Loop on reply from remote stub. */
550 {
551 char *buf;
552
553 QUIT; /* Allow user to bail out with ^C. */
554 getpkt (buf_p, sizeof_buf, 0);
555 buf = *buf_p;
556 if (buf[0] == 'E')
557 trace_error (buf);
558 else if (startswith (buf, "qRelocInsn:"))
559 {
560 ULONGEST ul;
561 CORE_ADDR from, to, org_to;
562 char *p, *pp;
563 int adjusted_size = 0;
564 int relocated = 0;
565
566 p = buf + strlen ("qRelocInsn:");
567 pp = unpack_varlen_hex (p, &ul);
568 if (*pp != ';')
569 error (_("invalid qRelocInsn packet: %s"), buf);
570 from = ul;
571
572 p = pp + 1;
573 unpack_varlen_hex (p, &ul);
574 to = ul;
575
576 org_to = to;
577
578 TRY
579 {
580 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
581 relocated = 1;
582 }
583 CATCH (ex, RETURN_MASK_ALL)
584 {
585 if (ex.error == MEMORY_ERROR)
586 {
587 /* Propagate memory errors silently back to the
588 target. The stub may have limited the range of
589 addresses we can write to, for example. */
590 }
591 else
592 {
593 /* Something unexpectedly bad happened. Be verbose
594 so we can tell what, and propagate the error back
595 to the stub, so it doesn't get stuck waiting for
596 a response. */
597 exception_fprintf (gdb_stderr, ex,
598 _("warning: relocating instruction: "));
599 }
600 putpkt ("E01");
601 }
602 END_CATCH
603
604 if (relocated)
605 {
606 adjusted_size = to - org_to;
607
608 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
609 putpkt (buf);
610 }
611 }
612 else if (buf[0] == 'O' && buf[1] != 'K')
613 remote_console_output (buf + 1); /* 'O' message from stub */
614 else
615 return buf; /* Here's the actual reply. */
616 }
617 while (1);
618 }
619
620 /* Handle for retreving the remote protocol data from gdbarch. */
621 static struct gdbarch_data *remote_gdbarch_data_handle;
622
623 static struct remote_arch_state *
624 get_remote_arch_state (void)
625 {
626 gdb_assert (target_gdbarch () != NULL);
627 return ((struct remote_arch_state *)
628 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
629 }
630
631 /* Fetch the global remote target state. */
632
633 static struct remote_state *
634 get_remote_state (void)
635 {
636 /* Make sure that the remote architecture state has been
637 initialized, because doing so might reallocate rs->buf. Any
638 function which calls getpkt also needs to be mindful of changes
639 to rs->buf, but this call limits the number of places which run
640 into trouble. */
641 get_remote_arch_state ();
642
643 return get_remote_state_raw ();
644 }
645
646 /* Cleanup routine for the remote module's pspace data. */
647
648 static void
649 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
650 {
651 char *remote_exec_file = (char *) arg;
652
653 xfree (remote_exec_file);
654 }
655
656 /* Fetch the remote exec-file from the current program space. */
657
658 static const char *
659 get_remote_exec_file (void)
660 {
661 char *remote_exec_file;
662
663 remote_exec_file
664 = (char *) program_space_data (current_program_space,
665 remote_pspace_data);
666 if (remote_exec_file == NULL)
667 return "";
668
669 return remote_exec_file;
670 }
671
672 /* Set the remote exec file for PSPACE. */
673
674 static void
675 set_pspace_remote_exec_file (struct program_space *pspace,
676 char *remote_exec_file)
677 {
678 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
679
680 xfree (old_file);
681 set_program_space_data (pspace, remote_pspace_data,
682 xstrdup (remote_exec_file));
683 }
684
685 /* The "set/show remote exec-file" set command hook. */
686
687 static void
688 set_remote_exec_file (char *ignored, int from_tty,
689 struct cmd_list_element *c)
690 {
691 gdb_assert (remote_exec_file_var != NULL);
692 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
693 }
694
695 /* The "set/show remote exec-file" show command hook. */
696
697 static void
698 show_remote_exec_file (struct ui_file *file, int from_tty,
699 struct cmd_list_element *cmd, const char *value)
700 {
701 fprintf_filtered (file, "%s\n", remote_exec_file_var);
702 }
703
704 static int
705 compare_pnums (const void *lhs_, const void *rhs_)
706 {
707 const struct packet_reg * const *lhs
708 = (const struct packet_reg * const *) lhs_;
709 const struct packet_reg * const *rhs
710 = (const struct packet_reg * const *) rhs_;
711
712 if ((*lhs)->pnum < (*rhs)->pnum)
713 return -1;
714 else if ((*lhs)->pnum == (*rhs)->pnum)
715 return 0;
716 else
717 return 1;
718 }
719
720 static int
721 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
722 {
723 int regnum, num_remote_regs, offset;
724 struct packet_reg **remote_regs;
725
726 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
727 {
728 struct packet_reg *r = &regs[regnum];
729
730 if (register_size (gdbarch, regnum) == 0)
731 /* Do not try to fetch zero-sized (placeholder) registers. */
732 r->pnum = -1;
733 else
734 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
735
736 r->regnum = regnum;
737 }
738
739 /* Define the g/G packet format as the contents of each register
740 with a remote protocol number, in order of ascending protocol
741 number. */
742
743 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
744 for (num_remote_regs = 0, regnum = 0;
745 regnum < gdbarch_num_regs (gdbarch);
746 regnum++)
747 if (regs[regnum].pnum != -1)
748 remote_regs[num_remote_regs++] = &regs[regnum];
749
750 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
751 compare_pnums);
752
753 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
754 {
755 remote_regs[regnum]->in_g_packet = 1;
756 remote_regs[regnum]->offset = offset;
757 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
758 }
759
760 return offset;
761 }
762
763 /* Given the architecture described by GDBARCH, return the remote
764 protocol register's number and the register's offset in the g/G
765 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
766 If the target does not have a mapping for REGNUM, return false,
767 otherwise, return true. */
768
769 int
770 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
771 int *pnum, int *poffset)
772 {
773 struct packet_reg *regs;
774 struct cleanup *old_chain;
775
776 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
777
778 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
779 old_chain = make_cleanup (xfree, regs);
780
781 map_regcache_remote_table (gdbarch, regs);
782
783 *pnum = regs[regnum].pnum;
784 *poffset = regs[regnum].offset;
785
786 do_cleanups (old_chain);
787
788 return *pnum != -1;
789 }
790
791 static void *
792 init_remote_state (struct gdbarch *gdbarch)
793 {
794 struct remote_state *rs = get_remote_state_raw ();
795 struct remote_arch_state *rsa;
796
797 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
798
799 /* Use the architecture to build a regnum<->pnum table, which will be
800 1:1 unless a feature set specifies otherwise. */
801 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
802 gdbarch_num_regs (gdbarch),
803 struct packet_reg);
804
805 /* Record the maximum possible size of the g packet - it may turn out
806 to be smaller. */
807 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
808
809 /* Default maximum number of characters in a packet body. Many
810 remote stubs have a hardwired buffer size of 400 bytes
811 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
812 as the maximum packet-size to ensure that the packet and an extra
813 NUL character can always fit in the buffer. This stops GDB
814 trashing stubs that try to squeeze an extra NUL into what is
815 already a full buffer (As of 1999-12-04 that was most stubs). */
816 rsa->remote_packet_size = 400 - 1;
817
818 /* This one is filled in when a ``g'' packet is received. */
819 rsa->actual_register_packet_size = 0;
820
821 /* Should rsa->sizeof_g_packet needs more space than the
822 default, adjust the size accordingly. Remember that each byte is
823 encoded as two characters. 32 is the overhead for the packet
824 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
825 (``$NN:G...#NN'') is a better guess, the below has been padded a
826 little. */
827 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
828 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
829
830 /* Make sure that the packet buffer is plenty big enough for
831 this architecture. */
832 if (rs->buf_size < rsa->remote_packet_size)
833 {
834 rs->buf_size = 2 * rsa->remote_packet_size;
835 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
836 }
837
838 return rsa;
839 }
840
841 /* Return the current allowed size of a remote packet. This is
842 inferred from the current architecture, and should be used to
843 limit the length of outgoing packets. */
844 static long
845 get_remote_packet_size (void)
846 {
847 struct remote_state *rs = get_remote_state ();
848 struct remote_arch_state *rsa = get_remote_arch_state ();
849
850 if (rs->explicit_packet_size)
851 return rs->explicit_packet_size;
852
853 return rsa->remote_packet_size;
854 }
855
856 static struct packet_reg *
857 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
858 {
859 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
860 return NULL;
861 else
862 {
863 struct packet_reg *r = &rsa->regs[regnum];
864
865 gdb_assert (r->regnum == regnum);
866 return r;
867 }
868 }
869
870 static struct packet_reg *
871 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
872 {
873 int i;
874
875 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
876 {
877 struct packet_reg *r = &rsa->regs[i];
878
879 if (r->pnum == pnum)
880 return r;
881 }
882 return NULL;
883 }
884
885 static struct target_ops remote_ops;
886
887 static struct target_ops extended_remote_ops;
888
889 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
890 ``forever'' still use the normal timeout mechanism. This is
891 currently used by the ASYNC code to guarentee that target reads
892 during the initial connect always time-out. Once getpkt has been
893 modified to return a timeout indication and, in turn
894 remote_wait()/wait_for_inferior() have gained a timeout parameter
895 this can go away. */
896 static int wait_forever_enabled_p = 1;
897
898 /* Allow the user to specify what sequence to send to the remote
899 when he requests a program interruption: Although ^C is usually
900 what remote systems expect (this is the default, here), it is
901 sometimes preferable to send a break. On other systems such
902 as the Linux kernel, a break followed by g, which is Magic SysRq g
903 is required in order to interrupt the execution. */
904 const char interrupt_sequence_control_c[] = "Ctrl-C";
905 const char interrupt_sequence_break[] = "BREAK";
906 const char interrupt_sequence_break_g[] = "BREAK-g";
907 static const char *const interrupt_sequence_modes[] =
908 {
909 interrupt_sequence_control_c,
910 interrupt_sequence_break,
911 interrupt_sequence_break_g,
912 NULL
913 };
914 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
915
916 static void
917 show_interrupt_sequence (struct ui_file *file, int from_tty,
918 struct cmd_list_element *c,
919 const char *value)
920 {
921 if (interrupt_sequence_mode == interrupt_sequence_control_c)
922 fprintf_filtered (file,
923 _("Send the ASCII ETX character (Ctrl-c) "
924 "to the remote target to interrupt the "
925 "execution of the program.\n"));
926 else if (interrupt_sequence_mode == interrupt_sequence_break)
927 fprintf_filtered (file,
928 _("send a break signal to the remote target "
929 "to interrupt the execution of the program.\n"));
930 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
931 fprintf_filtered (file,
932 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
933 "the remote target to interrupt the execution "
934 "of Linux kernel.\n"));
935 else
936 internal_error (__FILE__, __LINE__,
937 _("Invalid value for interrupt_sequence_mode: %s."),
938 interrupt_sequence_mode);
939 }
940
941 /* This boolean variable specifies whether interrupt_sequence is sent
942 to the remote target when gdb connects to it.
943 This is mostly needed when you debug the Linux kernel: The Linux kernel
944 expects BREAK g which is Magic SysRq g for connecting gdb. */
945 static int interrupt_on_connect = 0;
946
947 /* This variable is used to implement the "set/show remotebreak" commands.
948 Since these commands are now deprecated in favor of "set/show remote
949 interrupt-sequence", it no longer has any effect on the code. */
950 static int remote_break;
951
952 static void
953 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
954 {
955 if (remote_break)
956 interrupt_sequence_mode = interrupt_sequence_break;
957 else
958 interrupt_sequence_mode = interrupt_sequence_control_c;
959 }
960
961 static void
962 show_remotebreak (struct ui_file *file, int from_tty,
963 struct cmd_list_element *c,
964 const char *value)
965 {
966 }
967
968 /* This variable sets the number of bits in an address that are to be
969 sent in a memory ("M" or "m") packet. Normally, after stripping
970 leading zeros, the entire address would be sent. This variable
971 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
972 initial implementation of remote.c restricted the address sent in
973 memory packets to ``host::sizeof long'' bytes - (typically 32
974 bits). Consequently, for 64 bit targets, the upper 32 bits of an
975 address was never sent. Since fixing this bug may cause a break in
976 some remote targets this variable is principly provided to
977 facilitate backward compatibility. */
978
979 static unsigned int remote_address_size;
980
981 /* Temporary to track who currently owns the terminal. See
982 remote_terminal_* for more details. */
983
984 static int remote_async_terminal_ours_p;
985
986 \f
987 /* User configurable variables for the number of characters in a
988 memory read/write packet. MIN (rsa->remote_packet_size,
989 rsa->sizeof_g_packet) is the default. Some targets need smaller
990 values (fifo overruns, et.al.) and some users need larger values
991 (speed up transfers). The variables ``preferred_*'' (the user
992 request), ``current_*'' (what was actually set) and ``forced_*''
993 (Positive - a soft limit, negative - a hard limit). */
994
995 struct memory_packet_config
996 {
997 char *name;
998 long size;
999 int fixed_p;
1000 };
1001
1002 /* The default max memory-write-packet-size. The 16k is historical.
1003 (It came from older GDB's using alloca for buffers and the
1004 knowledge (folklore?) that some hosts don't cope very well with
1005 large alloca calls.) */
1006 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1007
1008 /* The minimum remote packet size for memory transfers. Ensures we
1009 can write at least one byte. */
1010 #define MIN_MEMORY_PACKET_SIZE 20
1011
1012 /* Compute the current size of a read/write packet. Since this makes
1013 use of ``actual_register_packet_size'' the computation is dynamic. */
1014
1015 static long
1016 get_memory_packet_size (struct memory_packet_config *config)
1017 {
1018 struct remote_state *rs = get_remote_state ();
1019 struct remote_arch_state *rsa = get_remote_arch_state ();
1020
1021 long what_they_get;
1022 if (config->fixed_p)
1023 {
1024 if (config->size <= 0)
1025 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1026 else
1027 what_they_get = config->size;
1028 }
1029 else
1030 {
1031 what_they_get = get_remote_packet_size ();
1032 /* Limit the packet to the size specified by the user. */
1033 if (config->size > 0
1034 && what_they_get > config->size)
1035 what_they_get = config->size;
1036
1037 /* Limit it to the size of the targets ``g'' response unless we have
1038 permission from the stub to use a larger packet size. */
1039 if (rs->explicit_packet_size == 0
1040 && rsa->actual_register_packet_size > 0
1041 && what_they_get > rsa->actual_register_packet_size)
1042 what_they_get = rsa->actual_register_packet_size;
1043 }
1044 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1045 what_they_get = MIN_MEMORY_PACKET_SIZE;
1046
1047 /* Make sure there is room in the global buffer for this packet
1048 (including its trailing NUL byte). */
1049 if (rs->buf_size < what_they_get + 1)
1050 {
1051 rs->buf_size = 2 * what_they_get;
1052 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1053 }
1054
1055 return what_they_get;
1056 }
1057
1058 /* Update the size of a read/write packet. If they user wants
1059 something really big then do a sanity check. */
1060
1061 static void
1062 set_memory_packet_size (char *args, struct memory_packet_config *config)
1063 {
1064 int fixed_p = config->fixed_p;
1065 long size = config->size;
1066
1067 if (args == NULL)
1068 error (_("Argument required (integer, `fixed' or `limited')."));
1069 else if (strcmp (args, "hard") == 0
1070 || strcmp (args, "fixed") == 0)
1071 fixed_p = 1;
1072 else if (strcmp (args, "soft") == 0
1073 || strcmp (args, "limit") == 0)
1074 fixed_p = 0;
1075 else
1076 {
1077 char *end;
1078
1079 size = strtoul (args, &end, 0);
1080 if (args == end)
1081 error (_("Invalid %s (bad syntax)."), config->name);
1082
1083 /* Instead of explicitly capping the size of a packet to or
1084 disallowing it, the user is allowed to set the size to
1085 something arbitrarily large. */
1086 }
1087
1088 /* So that the query shows the correct value. */
1089 if (size <= 0)
1090 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1091
1092 /* Extra checks? */
1093 if (fixed_p && !config->fixed_p)
1094 {
1095 if (! query (_("The target may not be able to correctly handle a %s\n"
1096 "of %ld bytes. Change the packet size? "),
1097 config->name, size))
1098 error (_("Packet size not changed."));
1099 }
1100 /* Update the config. */
1101 config->fixed_p = fixed_p;
1102 config->size = size;
1103 }
1104
1105 static void
1106 show_memory_packet_size (struct memory_packet_config *config)
1107 {
1108 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1109 if (config->fixed_p)
1110 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1111 get_memory_packet_size (config));
1112 else
1113 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1114 get_memory_packet_size (config));
1115 }
1116
1117 static struct memory_packet_config memory_write_packet_config =
1118 {
1119 "memory-write-packet-size",
1120 };
1121
1122 static void
1123 set_memory_write_packet_size (char *args, int from_tty)
1124 {
1125 set_memory_packet_size (args, &memory_write_packet_config);
1126 }
1127
1128 static void
1129 show_memory_write_packet_size (char *args, int from_tty)
1130 {
1131 show_memory_packet_size (&memory_write_packet_config);
1132 }
1133
1134 static long
1135 get_memory_write_packet_size (void)
1136 {
1137 return get_memory_packet_size (&memory_write_packet_config);
1138 }
1139
1140 static struct memory_packet_config memory_read_packet_config =
1141 {
1142 "memory-read-packet-size",
1143 };
1144
1145 static void
1146 set_memory_read_packet_size (char *args, int from_tty)
1147 {
1148 set_memory_packet_size (args, &memory_read_packet_config);
1149 }
1150
1151 static void
1152 show_memory_read_packet_size (char *args, int from_tty)
1153 {
1154 show_memory_packet_size (&memory_read_packet_config);
1155 }
1156
1157 static long
1158 get_memory_read_packet_size (void)
1159 {
1160 long size = get_memory_packet_size (&memory_read_packet_config);
1161
1162 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1163 extra buffer size argument before the memory read size can be
1164 increased beyond this. */
1165 if (size > get_remote_packet_size ())
1166 size = get_remote_packet_size ();
1167 return size;
1168 }
1169
1170 \f
1171 /* Generic configuration support for packets the stub optionally
1172 supports. Allows the user to specify the use of the packet as well
1173 as allowing GDB to auto-detect support in the remote stub. */
1174
1175 enum packet_support
1176 {
1177 PACKET_SUPPORT_UNKNOWN = 0,
1178 PACKET_ENABLE,
1179 PACKET_DISABLE
1180 };
1181
1182 struct packet_config
1183 {
1184 const char *name;
1185 const char *title;
1186
1187 /* If auto, GDB auto-detects support for this packet or feature,
1188 either through qSupported, or by trying the packet and looking
1189 at the response. If true, GDB assumes the target supports this
1190 packet. If false, the packet is disabled. Configs that don't
1191 have an associated command always have this set to auto. */
1192 enum auto_boolean detect;
1193
1194 /* Does the target support this packet? */
1195 enum packet_support support;
1196 };
1197
1198 /* Analyze a packet's return value and update the packet config
1199 accordingly. */
1200
1201 enum packet_result
1202 {
1203 PACKET_ERROR,
1204 PACKET_OK,
1205 PACKET_UNKNOWN
1206 };
1207
1208 static enum packet_support packet_config_support (struct packet_config *config);
1209 static enum packet_support packet_support (int packet);
1210
1211 static void
1212 show_packet_config_cmd (struct packet_config *config)
1213 {
1214 char *support = "internal-error";
1215
1216 switch (packet_config_support (config))
1217 {
1218 case PACKET_ENABLE:
1219 support = "enabled";
1220 break;
1221 case PACKET_DISABLE:
1222 support = "disabled";
1223 break;
1224 case PACKET_SUPPORT_UNKNOWN:
1225 support = "unknown";
1226 break;
1227 }
1228 switch (config->detect)
1229 {
1230 case AUTO_BOOLEAN_AUTO:
1231 printf_filtered (_("Support for the `%s' packet "
1232 "is auto-detected, currently %s.\n"),
1233 config->name, support);
1234 break;
1235 case AUTO_BOOLEAN_TRUE:
1236 case AUTO_BOOLEAN_FALSE:
1237 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1238 config->name, support);
1239 break;
1240 }
1241 }
1242
1243 static void
1244 add_packet_config_cmd (struct packet_config *config, const char *name,
1245 const char *title, int legacy)
1246 {
1247 char *set_doc;
1248 char *show_doc;
1249 char *cmd_name;
1250
1251 config->name = name;
1252 config->title = title;
1253 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1254 name, title);
1255 show_doc = xstrprintf ("Show current use of remote "
1256 "protocol `%s' (%s) packet",
1257 name, title);
1258 /* set/show TITLE-packet {auto,on,off} */
1259 cmd_name = xstrprintf ("%s-packet", title);
1260 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1261 &config->detect, set_doc,
1262 show_doc, NULL, /* help_doc */
1263 NULL,
1264 show_remote_protocol_packet_cmd,
1265 &remote_set_cmdlist, &remote_show_cmdlist);
1266 /* The command code copies the documentation strings. */
1267 xfree (set_doc);
1268 xfree (show_doc);
1269 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1270 if (legacy)
1271 {
1272 char *legacy_name;
1273
1274 legacy_name = xstrprintf ("%s-packet", name);
1275 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1276 &remote_set_cmdlist);
1277 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1278 &remote_show_cmdlist);
1279 }
1280 }
1281
1282 static enum packet_result
1283 packet_check_result (const char *buf)
1284 {
1285 if (buf[0] != '\0')
1286 {
1287 /* The stub recognized the packet request. Check that the
1288 operation succeeded. */
1289 if (buf[0] == 'E'
1290 && isxdigit (buf[1]) && isxdigit (buf[2])
1291 && buf[3] == '\0')
1292 /* "Enn" - definitly an error. */
1293 return PACKET_ERROR;
1294
1295 /* Always treat "E." as an error. This will be used for
1296 more verbose error messages, such as E.memtypes. */
1297 if (buf[0] == 'E' && buf[1] == '.')
1298 return PACKET_ERROR;
1299
1300 /* The packet may or may not be OK. Just assume it is. */
1301 return PACKET_OK;
1302 }
1303 else
1304 /* The stub does not support the packet. */
1305 return PACKET_UNKNOWN;
1306 }
1307
1308 static enum packet_result
1309 packet_ok (const char *buf, struct packet_config *config)
1310 {
1311 enum packet_result result;
1312
1313 if (config->detect != AUTO_BOOLEAN_TRUE
1314 && config->support == PACKET_DISABLE)
1315 internal_error (__FILE__, __LINE__,
1316 _("packet_ok: attempt to use a disabled packet"));
1317
1318 result = packet_check_result (buf);
1319 switch (result)
1320 {
1321 case PACKET_OK:
1322 case PACKET_ERROR:
1323 /* The stub recognized the packet request. */
1324 if (config->support == PACKET_SUPPORT_UNKNOWN)
1325 {
1326 if (remote_debug)
1327 fprintf_unfiltered (gdb_stdlog,
1328 "Packet %s (%s) is supported\n",
1329 config->name, config->title);
1330 config->support = PACKET_ENABLE;
1331 }
1332 break;
1333 case PACKET_UNKNOWN:
1334 /* The stub does not support the packet. */
1335 if (config->detect == AUTO_BOOLEAN_AUTO
1336 && config->support == PACKET_ENABLE)
1337 {
1338 /* If the stub previously indicated that the packet was
1339 supported then there is a protocol error. */
1340 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1341 config->name, config->title);
1342 }
1343 else if (config->detect == AUTO_BOOLEAN_TRUE)
1344 {
1345 /* The user set it wrong. */
1346 error (_("Enabled packet %s (%s) not recognized by stub"),
1347 config->name, config->title);
1348 }
1349
1350 if (remote_debug)
1351 fprintf_unfiltered (gdb_stdlog,
1352 "Packet %s (%s) is NOT supported\n",
1353 config->name, config->title);
1354 config->support = PACKET_DISABLE;
1355 break;
1356 }
1357
1358 return result;
1359 }
1360
1361 enum {
1362 PACKET_vCont = 0,
1363 PACKET_X,
1364 PACKET_qSymbol,
1365 PACKET_P,
1366 PACKET_p,
1367 PACKET_Z0,
1368 PACKET_Z1,
1369 PACKET_Z2,
1370 PACKET_Z3,
1371 PACKET_Z4,
1372 PACKET_vFile_setfs,
1373 PACKET_vFile_open,
1374 PACKET_vFile_pread,
1375 PACKET_vFile_pwrite,
1376 PACKET_vFile_close,
1377 PACKET_vFile_unlink,
1378 PACKET_vFile_readlink,
1379 PACKET_vFile_fstat,
1380 PACKET_qXfer_auxv,
1381 PACKET_qXfer_features,
1382 PACKET_qXfer_exec_file,
1383 PACKET_qXfer_libraries,
1384 PACKET_qXfer_libraries_svr4,
1385 PACKET_qXfer_memory_map,
1386 PACKET_qXfer_spu_read,
1387 PACKET_qXfer_spu_write,
1388 PACKET_qXfer_osdata,
1389 PACKET_qXfer_threads,
1390 PACKET_qXfer_statictrace_read,
1391 PACKET_qXfer_traceframe_info,
1392 PACKET_qXfer_uib,
1393 PACKET_qGetTIBAddr,
1394 PACKET_qGetTLSAddr,
1395 PACKET_qSupported,
1396 PACKET_qTStatus,
1397 PACKET_QPassSignals,
1398 PACKET_QCatchSyscalls,
1399 PACKET_QProgramSignals,
1400 PACKET_qCRC,
1401 PACKET_qSearch_memory,
1402 PACKET_vAttach,
1403 PACKET_vRun,
1404 PACKET_QStartNoAckMode,
1405 PACKET_vKill,
1406 PACKET_qXfer_siginfo_read,
1407 PACKET_qXfer_siginfo_write,
1408 PACKET_qAttached,
1409
1410 /* Support for conditional tracepoints. */
1411 PACKET_ConditionalTracepoints,
1412
1413 /* Support for target-side breakpoint conditions. */
1414 PACKET_ConditionalBreakpoints,
1415
1416 /* Support for target-side breakpoint commands. */
1417 PACKET_BreakpointCommands,
1418
1419 /* Support for fast tracepoints. */
1420 PACKET_FastTracepoints,
1421
1422 /* Support for static tracepoints. */
1423 PACKET_StaticTracepoints,
1424
1425 /* Support for installing tracepoints while a trace experiment is
1426 running. */
1427 PACKET_InstallInTrace,
1428
1429 PACKET_bc,
1430 PACKET_bs,
1431 PACKET_TracepointSource,
1432 PACKET_QAllow,
1433 PACKET_qXfer_fdpic,
1434 PACKET_QDisableRandomization,
1435 PACKET_QAgent,
1436 PACKET_QTBuffer_size,
1437 PACKET_Qbtrace_off,
1438 PACKET_Qbtrace_bts,
1439 PACKET_Qbtrace_pt,
1440 PACKET_qXfer_btrace,
1441
1442 /* Support for the QNonStop packet. */
1443 PACKET_QNonStop,
1444
1445 /* Support for the QThreadEvents packet. */
1446 PACKET_QThreadEvents,
1447
1448 /* Support for multi-process extensions. */
1449 PACKET_multiprocess_feature,
1450
1451 /* Support for enabling and disabling tracepoints while a trace
1452 experiment is running. */
1453 PACKET_EnableDisableTracepoints_feature,
1454
1455 /* Support for collecting strings using the tracenz bytecode. */
1456 PACKET_tracenz_feature,
1457
1458 /* Support for continuing to run a trace experiment while GDB is
1459 disconnected. */
1460 PACKET_DisconnectedTracing_feature,
1461
1462 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1463 PACKET_augmented_libraries_svr4_read_feature,
1464
1465 /* Support for the qXfer:btrace-conf:read packet. */
1466 PACKET_qXfer_btrace_conf,
1467
1468 /* Support for the Qbtrace-conf:bts:size packet. */
1469 PACKET_Qbtrace_conf_bts_size,
1470
1471 /* Support for swbreak+ feature. */
1472 PACKET_swbreak_feature,
1473
1474 /* Support for hwbreak+ feature. */
1475 PACKET_hwbreak_feature,
1476
1477 /* Support for fork events. */
1478 PACKET_fork_event_feature,
1479
1480 /* Support for vfork events. */
1481 PACKET_vfork_event_feature,
1482
1483 /* Support for the Qbtrace-conf:pt:size packet. */
1484 PACKET_Qbtrace_conf_pt_size,
1485
1486 /* Support for exec events. */
1487 PACKET_exec_event_feature,
1488
1489 /* Support for query supported vCont actions. */
1490 PACKET_vContSupported,
1491
1492 /* Support remote CTRL-C. */
1493 PACKET_vCtrlC,
1494
1495 /* Support TARGET_WAITKIND_NO_RESUMED. */
1496 PACKET_no_resumed,
1497
1498 PACKET_MAX
1499 };
1500
1501 static struct packet_config remote_protocol_packets[PACKET_MAX];
1502
1503 /* Returns the packet's corresponding "set remote foo-packet" command
1504 state. See struct packet_config for more details. */
1505
1506 static enum auto_boolean
1507 packet_set_cmd_state (int packet)
1508 {
1509 return remote_protocol_packets[packet].detect;
1510 }
1511
1512 /* Returns whether a given packet or feature is supported. This takes
1513 into account the state of the corresponding "set remote foo-packet"
1514 command, which may be used to bypass auto-detection. */
1515
1516 static enum packet_support
1517 packet_config_support (struct packet_config *config)
1518 {
1519 switch (config->detect)
1520 {
1521 case AUTO_BOOLEAN_TRUE:
1522 return PACKET_ENABLE;
1523 case AUTO_BOOLEAN_FALSE:
1524 return PACKET_DISABLE;
1525 case AUTO_BOOLEAN_AUTO:
1526 return config->support;
1527 default:
1528 gdb_assert_not_reached (_("bad switch"));
1529 }
1530 }
1531
1532 /* Same as packet_config_support, but takes the packet's enum value as
1533 argument. */
1534
1535 static enum packet_support
1536 packet_support (int packet)
1537 {
1538 struct packet_config *config = &remote_protocol_packets[packet];
1539
1540 return packet_config_support (config);
1541 }
1542
1543 static void
1544 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1545 struct cmd_list_element *c,
1546 const char *value)
1547 {
1548 struct packet_config *packet;
1549
1550 for (packet = remote_protocol_packets;
1551 packet < &remote_protocol_packets[PACKET_MAX];
1552 packet++)
1553 {
1554 if (&packet->detect == c->var)
1555 {
1556 show_packet_config_cmd (packet);
1557 return;
1558 }
1559 }
1560 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1561 c->name);
1562 }
1563
1564 /* Should we try one of the 'Z' requests? */
1565
1566 enum Z_packet_type
1567 {
1568 Z_PACKET_SOFTWARE_BP,
1569 Z_PACKET_HARDWARE_BP,
1570 Z_PACKET_WRITE_WP,
1571 Z_PACKET_READ_WP,
1572 Z_PACKET_ACCESS_WP,
1573 NR_Z_PACKET_TYPES
1574 };
1575
1576 /* For compatibility with older distributions. Provide a ``set remote
1577 Z-packet ...'' command that updates all the Z packet types. */
1578
1579 static enum auto_boolean remote_Z_packet_detect;
1580
1581 static void
1582 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1583 struct cmd_list_element *c)
1584 {
1585 int i;
1586
1587 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1588 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1589 }
1590
1591 static void
1592 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1593 struct cmd_list_element *c,
1594 const char *value)
1595 {
1596 int i;
1597
1598 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1599 {
1600 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1601 }
1602 }
1603
1604 /* Returns true if the multi-process extensions are in effect. */
1605
1606 static int
1607 remote_multi_process_p (struct remote_state *rs)
1608 {
1609 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1610 }
1611
1612 /* Returns true if fork events are supported. */
1613
1614 static int
1615 remote_fork_event_p (struct remote_state *rs)
1616 {
1617 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1618 }
1619
1620 /* Returns true if vfork events are supported. */
1621
1622 static int
1623 remote_vfork_event_p (struct remote_state *rs)
1624 {
1625 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1626 }
1627
1628 /* Returns true if exec events are supported. */
1629
1630 static int
1631 remote_exec_event_p (struct remote_state *rs)
1632 {
1633 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1634 }
1635
1636 /* Insert fork catchpoint target routine. If fork events are enabled
1637 then return success, nothing more to do. */
1638
1639 static int
1640 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1641 {
1642 struct remote_state *rs = get_remote_state ();
1643
1644 return !remote_fork_event_p (rs);
1645 }
1646
1647 /* Remove fork catchpoint target routine. Nothing to do, just
1648 return success. */
1649
1650 static int
1651 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1652 {
1653 return 0;
1654 }
1655
1656 /* Insert vfork catchpoint target routine. If vfork events are enabled
1657 then return success, nothing more to do. */
1658
1659 static int
1660 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1661 {
1662 struct remote_state *rs = get_remote_state ();
1663
1664 return !remote_vfork_event_p (rs);
1665 }
1666
1667 /* Remove vfork catchpoint target routine. Nothing to do, just
1668 return success. */
1669
1670 static int
1671 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1672 {
1673 return 0;
1674 }
1675
1676 /* Insert exec catchpoint target routine. If exec events are
1677 enabled, just return success. */
1678
1679 static int
1680 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1681 {
1682 struct remote_state *rs = get_remote_state ();
1683
1684 return !remote_exec_event_p (rs);
1685 }
1686
1687 /* Remove exec catchpoint target routine. Nothing to do, just
1688 return success. */
1689
1690 static int
1691 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1692 {
1693 return 0;
1694 }
1695
1696 \f
1697 /* Asynchronous signal handle registered as event loop source for
1698 when we have pending events ready to be passed to the core. */
1699
1700 static struct async_event_handler *remote_async_inferior_event_token;
1701
1702 \f
1703
1704 static ptid_t magic_null_ptid;
1705 static ptid_t not_sent_ptid;
1706 static ptid_t any_thread_ptid;
1707
1708 /* Find out if the stub attached to PID (and hence GDB should offer to
1709 detach instead of killing it when bailing out). */
1710
1711 static int
1712 remote_query_attached (int pid)
1713 {
1714 struct remote_state *rs = get_remote_state ();
1715 size_t size = get_remote_packet_size ();
1716
1717 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1718 return 0;
1719
1720 if (remote_multi_process_p (rs))
1721 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1722 else
1723 xsnprintf (rs->buf, size, "qAttached");
1724
1725 putpkt (rs->buf);
1726 getpkt (&rs->buf, &rs->buf_size, 0);
1727
1728 switch (packet_ok (rs->buf,
1729 &remote_protocol_packets[PACKET_qAttached]))
1730 {
1731 case PACKET_OK:
1732 if (strcmp (rs->buf, "1") == 0)
1733 return 1;
1734 break;
1735 case PACKET_ERROR:
1736 warning (_("Remote failure reply: %s"), rs->buf);
1737 break;
1738 case PACKET_UNKNOWN:
1739 break;
1740 }
1741
1742 return 0;
1743 }
1744
1745 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1746 has been invented by GDB, instead of reported by the target. Since
1747 we can be connected to a remote system before before knowing about
1748 any inferior, mark the target with execution when we find the first
1749 inferior. If ATTACHED is 1, then we had just attached to this
1750 inferior. If it is 0, then we just created this inferior. If it
1751 is -1, then try querying the remote stub to find out if it had
1752 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1753 attempt to open this inferior's executable as the main executable
1754 if no main executable is open already. */
1755
1756 static struct inferior *
1757 remote_add_inferior (int fake_pid_p, int pid, int attached,
1758 int try_open_exec)
1759 {
1760 struct inferior *inf;
1761
1762 /* Check whether this process we're learning about is to be
1763 considered attached, or if is to be considered to have been
1764 spawned by the stub. */
1765 if (attached == -1)
1766 attached = remote_query_attached (pid);
1767
1768 if (gdbarch_has_global_solist (target_gdbarch ()))
1769 {
1770 /* If the target shares code across all inferiors, then every
1771 attach adds a new inferior. */
1772 inf = add_inferior (pid);
1773
1774 /* ... and every inferior is bound to the same program space.
1775 However, each inferior may still have its own address
1776 space. */
1777 inf->aspace = maybe_new_address_space ();
1778 inf->pspace = current_program_space;
1779 }
1780 else
1781 {
1782 /* In the traditional debugging scenario, there's a 1-1 match
1783 between program/address spaces. We simply bind the inferior
1784 to the program space's address space. */
1785 inf = current_inferior ();
1786 inferior_appeared (inf, pid);
1787 }
1788
1789 inf->attach_flag = attached;
1790 inf->fake_pid_p = fake_pid_p;
1791
1792 /* If no main executable is currently open then attempt to
1793 open the file that was executed to create this inferior. */
1794 if (try_open_exec && get_exec_file (0) == NULL)
1795 exec_file_locate_attach (pid, 1);
1796
1797 return inf;
1798 }
1799
1800 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1801 according to RUNNING. */
1802
1803 static void
1804 remote_add_thread (ptid_t ptid, int running, int executing)
1805 {
1806 struct remote_state *rs = get_remote_state ();
1807
1808 /* GDB historically didn't pull threads in the initial connection
1809 setup. If the remote target doesn't even have a concept of
1810 threads (e.g., a bare-metal target), even if internally we
1811 consider that a single-threaded target, mentioning a new thread
1812 might be confusing to the user. Be silent then, preserving the
1813 age old behavior. */
1814 if (rs->starting_up)
1815 add_thread_silent (ptid);
1816 else
1817 add_thread (ptid);
1818
1819 set_executing (ptid, executing);
1820 set_running (ptid, running);
1821 }
1822
1823 /* Come here when we learn about a thread id from the remote target.
1824 It may be the first time we hear about such thread, so take the
1825 opportunity to add it to GDB's thread list. In case this is the
1826 first time we're noticing its corresponding inferior, add it to
1827 GDB's inferior list as well. EXECUTING indicates whether the
1828 thread is (internally) executing or stopped. */
1829
1830 static void
1831 remote_notice_new_inferior (ptid_t currthread, int executing)
1832 {
1833 /* In non-stop mode, we assume new found threads are (externally)
1834 running until proven otherwise with a stop reply. In all-stop,
1835 we can only get here if all threads are stopped. */
1836 int running = target_is_non_stop_p () ? 1 : 0;
1837
1838 /* If this is a new thread, add it to GDB's thread list.
1839 If we leave it up to WFI to do this, bad things will happen. */
1840
1841 if (in_thread_list (currthread) && is_exited (currthread))
1842 {
1843 /* We're seeing an event on a thread id we knew had exited.
1844 This has to be a new thread reusing the old id. Add it. */
1845 remote_add_thread (currthread, running, executing);
1846 return;
1847 }
1848
1849 if (!in_thread_list (currthread))
1850 {
1851 struct inferior *inf = NULL;
1852 int pid = ptid_get_pid (currthread);
1853
1854 if (ptid_is_pid (inferior_ptid)
1855 && pid == ptid_get_pid (inferior_ptid))
1856 {
1857 /* inferior_ptid has no thread member yet. This can happen
1858 with the vAttach -> remote_wait,"TAAthread:" path if the
1859 stub doesn't support qC. This is the first stop reported
1860 after an attach, so this is the main thread. Update the
1861 ptid in the thread list. */
1862 if (in_thread_list (pid_to_ptid (pid)))
1863 thread_change_ptid (inferior_ptid, currthread);
1864 else
1865 {
1866 remote_add_thread (currthread, running, executing);
1867 inferior_ptid = currthread;
1868 }
1869 return;
1870 }
1871
1872 if (ptid_equal (magic_null_ptid, inferior_ptid))
1873 {
1874 /* inferior_ptid is not set yet. This can happen with the
1875 vRun -> remote_wait,"TAAthread:" path if the stub
1876 doesn't support qC. This is the first stop reported
1877 after an attach, so this is the main thread. Update the
1878 ptid in the thread list. */
1879 thread_change_ptid (inferior_ptid, currthread);
1880 return;
1881 }
1882
1883 /* When connecting to a target remote, or to a target
1884 extended-remote which already was debugging an inferior, we
1885 may not know about it yet. Add it before adding its child
1886 thread, so notifications are emitted in a sensible order. */
1887 if (!in_inferior_list (ptid_get_pid (currthread)))
1888 {
1889 struct remote_state *rs = get_remote_state ();
1890 int fake_pid_p = !remote_multi_process_p (rs);
1891
1892 inf = remote_add_inferior (fake_pid_p,
1893 ptid_get_pid (currthread), -1, 1);
1894 }
1895
1896 /* This is really a new thread. Add it. */
1897 remote_add_thread (currthread, running, executing);
1898
1899 /* If we found a new inferior, let the common code do whatever
1900 it needs to with it (e.g., read shared libraries, insert
1901 breakpoints), unless we're just setting up an all-stop
1902 connection. */
1903 if (inf != NULL)
1904 {
1905 struct remote_state *rs = get_remote_state ();
1906
1907 if (!rs->starting_up)
1908 notice_new_inferior (currthread, executing, 0);
1909 }
1910 }
1911 }
1912
1913 /* Return the private thread data, creating it if necessary. */
1914
1915 static struct private_thread_info *
1916 demand_private_info (ptid_t ptid)
1917 {
1918 struct thread_info *info = find_thread_ptid (ptid);
1919
1920 gdb_assert (info);
1921
1922 if (!info->priv)
1923 {
1924 info->priv = XNEW (struct private_thread_info);
1925 info->private_dtor = free_private_thread_info;
1926 info->priv->core = -1;
1927 info->priv->extra = NULL;
1928 info->priv->name = NULL;
1929 }
1930
1931 return info->priv;
1932 }
1933
1934 /* Call this function as a result of
1935 1) A halt indication (T packet) containing a thread id
1936 2) A direct query of currthread
1937 3) Successful execution of set thread */
1938
1939 static void
1940 record_currthread (struct remote_state *rs, ptid_t currthread)
1941 {
1942 rs->general_thread = currthread;
1943 }
1944
1945 /* If 'QPassSignals' is supported, tell the remote stub what signals
1946 it can simply pass through to the inferior without reporting. */
1947
1948 static void
1949 remote_pass_signals (struct target_ops *self,
1950 int numsigs, unsigned char *pass_signals)
1951 {
1952 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1953 {
1954 char *pass_packet, *p;
1955 int count = 0, i;
1956 struct remote_state *rs = get_remote_state ();
1957
1958 gdb_assert (numsigs < 256);
1959 for (i = 0; i < numsigs; i++)
1960 {
1961 if (pass_signals[i])
1962 count++;
1963 }
1964 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1965 strcpy (pass_packet, "QPassSignals:");
1966 p = pass_packet + strlen (pass_packet);
1967 for (i = 0; i < numsigs; i++)
1968 {
1969 if (pass_signals[i])
1970 {
1971 if (i >= 16)
1972 *p++ = tohex (i >> 4);
1973 *p++ = tohex (i & 15);
1974 if (count)
1975 *p++ = ';';
1976 else
1977 break;
1978 count--;
1979 }
1980 }
1981 *p = 0;
1982 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1983 {
1984 putpkt (pass_packet);
1985 getpkt (&rs->buf, &rs->buf_size, 0);
1986 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1987 if (rs->last_pass_packet)
1988 xfree (rs->last_pass_packet);
1989 rs->last_pass_packet = pass_packet;
1990 }
1991 else
1992 xfree (pass_packet);
1993 }
1994 }
1995
1996 /* If 'QCatchSyscalls' is supported, tell the remote stub
1997 to report syscalls to GDB. */
1998
1999 static int
2000 remote_set_syscall_catchpoint (struct target_ops *self,
2001 int pid, int needed, int any_count,
2002 int table_size, int *table)
2003 {
2004 char *catch_packet;
2005 enum packet_result result;
2006 int n_sysno = 0;
2007
2008 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2009 {
2010 /* Not supported. */
2011 return 1;
2012 }
2013
2014 if (needed && !any_count)
2015 {
2016 int i;
2017
2018 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2019 for (i = 0; i < table_size; i++)
2020 {
2021 if (table[i] != 0)
2022 n_sysno++;
2023 }
2024 }
2025
2026 if (remote_debug)
2027 {
2028 fprintf_unfiltered (gdb_stdlog,
2029 "remote_set_syscall_catchpoint "
2030 "pid %d needed %d any_count %d n_sysno %d\n",
2031 pid, needed, any_count, n_sysno);
2032 }
2033
2034 if (needed)
2035 {
2036 /* Prepare a packet with the sysno list, assuming max 8+1
2037 characters for a sysno. If the resulting packet size is too
2038 big, fallback on the non-selective packet. */
2039 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2040
2041 catch_packet = (char *) xmalloc (maxpktsz);
2042 strcpy (catch_packet, "QCatchSyscalls:1");
2043 if (!any_count)
2044 {
2045 int i;
2046 char *p;
2047
2048 p = catch_packet;
2049 p += strlen (p);
2050
2051 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2052 for (i = 0; i < table_size; i++)
2053 {
2054 if (table[i] != 0)
2055 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2056 }
2057 }
2058 if (strlen (catch_packet) > get_remote_packet_size ())
2059 {
2060 /* catch_packet too big. Fallback to less efficient
2061 non selective mode, with GDB doing the filtering. */
2062 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2063 }
2064 }
2065 else
2066 catch_packet = xstrdup ("QCatchSyscalls:0");
2067
2068 {
2069 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2070 struct remote_state *rs = get_remote_state ();
2071
2072 putpkt (catch_packet);
2073 getpkt (&rs->buf, &rs->buf_size, 0);
2074 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2075 do_cleanups (old_chain);
2076 if (result == PACKET_OK)
2077 return 0;
2078 else
2079 return -1;
2080 }
2081 }
2082
2083 /* If 'QProgramSignals' is supported, tell the remote stub what
2084 signals it should pass through to the inferior when detaching. */
2085
2086 static void
2087 remote_program_signals (struct target_ops *self,
2088 int numsigs, unsigned char *signals)
2089 {
2090 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2091 {
2092 char *packet, *p;
2093 int count = 0, i;
2094 struct remote_state *rs = get_remote_state ();
2095
2096 gdb_assert (numsigs < 256);
2097 for (i = 0; i < numsigs; i++)
2098 {
2099 if (signals[i])
2100 count++;
2101 }
2102 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2103 strcpy (packet, "QProgramSignals:");
2104 p = packet + strlen (packet);
2105 for (i = 0; i < numsigs; i++)
2106 {
2107 if (signal_pass_state (i))
2108 {
2109 if (i >= 16)
2110 *p++ = tohex (i >> 4);
2111 *p++ = tohex (i & 15);
2112 if (count)
2113 *p++ = ';';
2114 else
2115 break;
2116 count--;
2117 }
2118 }
2119 *p = 0;
2120 if (!rs->last_program_signals_packet
2121 || strcmp (rs->last_program_signals_packet, packet) != 0)
2122 {
2123 putpkt (packet);
2124 getpkt (&rs->buf, &rs->buf_size, 0);
2125 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2126 xfree (rs->last_program_signals_packet);
2127 rs->last_program_signals_packet = packet;
2128 }
2129 else
2130 xfree (packet);
2131 }
2132 }
2133
2134 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2135 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2136 thread. If GEN is set, set the general thread, if not, then set
2137 the step/continue thread. */
2138 static void
2139 set_thread (struct ptid ptid, int gen)
2140 {
2141 struct remote_state *rs = get_remote_state ();
2142 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2143 char *buf = rs->buf;
2144 char *endbuf = rs->buf + get_remote_packet_size ();
2145
2146 if (ptid_equal (state, ptid))
2147 return;
2148
2149 *buf++ = 'H';
2150 *buf++ = gen ? 'g' : 'c';
2151 if (ptid_equal (ptid, magic_null_ptid))
2152 xsnprintf (buf, endbuf - buf, "0");
2153 else if (ptid_equal (ptid, any_thread_ptid))
2154 xsnprintf (buf, endbuf - buf, "0");
2155 else if (ptid_equal (ptid, minus_one_ptid))
2156 xsnprintf (buf, endbuf - buf, "-1");
2157 else
2158 write_ptid (buf, endbuf, ptid);
2159 putpkt (rs->buf);
2160 getpkt (&rs->buf, &rs->buf_size, 0);
2161 if (gen)
2162 rs->general_thread = ptid;
2163 else
2164 rs->continue_thread = ptid;
2165 }
2166
2167 static void
2168 set_general_thread (struct ptid ptid)
2169 {
2170 set_thread (ptid, 1);
2171 }
2172
2173 static void
2174 set_continue_thread (struct ptid ptid)
2175 {
2176 set_thread (ptid, 0);
2177 }
2178
2179 /* Change the remote current process. Which thread within the process
2180 ends up selected isn't important, as long as it is the same process
2181 as what INFERIOR_PTID points to.
2182
2183 This comes from that fact that there is no explicit notion of
2184 "selected process" in the protocol. The selected process for
2185 general operations is the process the selected general thread
2186 belongs to. */
2187
2188 static void
2189 set_general_process (void)
2190 {
2191 struct remote_state *rs = get_remote_state ();
2192
2193 /* If the remote can't handle multiple processes, don't bother. */
2194 if (!remote_multi_process_p (rs))
2195 return;
2196
2197 /* We only need to change the remote current thread if it's pointing
2198 at some other process. */
2199 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2200 set_general_thread (inferior_ptid);
2201 }
2202
2203 \f
2204 /* Return nonzero if this is the main thread that we made up ourselves
2205 to model non-threaded targets as single-threaded. */
2206
2207 static int
2208 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2209 {
2210 if (ptid_equal (ptid, magic_null_ptid))
2211 /* The main thread is always alive. */
2212 return 1;
2213
2214 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2215 /* The main thread is always alive. This can happen after a
2216 vAttach, if the remote side doesn't support
2217 multi-threading. */
2218 return 1;
2219
2220 return 0;
2221 }
2222
2223 /* Return nonzero if the thread PTID is still alive on the remote
2224 system. */
2225
2226 static int
2227 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2228 {
2229 struct remote_state *rs = get_remote_state ();
2230 char *p, *endp;
2231
2232 /* Check if this is a thread that we made up ourselves to model
2233 non-threaded targets as single-threaded. */
2234 if (remote_thread_always_alive (ops, ptid))
2235 return 1;
2236
2237 p = rs->buf;
2238 endp = rs->buf + get_remote_packet_size ();
2239
2240 *p++ = 'T';
2241 write_ptid (p, endp, ptid);
2242
2243 putpkt (rs->buf);
2244 getpkt (&rs->buf, &rs->buf_size, 0);
2245 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2246 }
2247
2248 /* Return a pointer to a thread name if we know it and NULL otherwise.
2249 The thread_info object owns the memory for the name. */
2250
2251 static const char *
2252 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2253 {
2254 if (info->priv != NULL)
2255 return info->priv->name;
2256
2257 return NULL;
2258 }
2259
2260 /* About these extended threadlist and threadinfo packets. They are
2261 variable length packets but, the fields within them are often fixed
2262 length. They are redundent enough to send over UDP as is the
2263 remote protocol in general. There is a matching unit test module
2264 in libstub. */
2265
2266 /* WARNING: This threadref data structure comes from the remote O.S.,
2267 libstub protocol encoding, and remote.c. It is not particularly
2268 changable. */
2269
2270 /* Right now, the internal structure is int. We want it to be bigger.
2271 Plan to fix this. */
2272
2273 typedef int gdb_threadref; /* Internal GDB thread reference. */
2274
2275 /* gdb_ext_thread_info is an internal GDB data structure which is
2276 equivalent to the reply of the remote threadinfo packet. */
2277
2278 struct gdb_ext_thread_info
2279 {
2280 threadref threadid; /* External form of thread reference. */
2281 int active; /* Has state interesting to GDB?
2282 regs, stack. */
2283 char display[256]; /* Brief state display, name,
2284 blocked/suspended. */
2285 char shortname[32]; /* To be used to name threads. */
2286 char more_display[256]; /* Long info, statistics, queue depth,
2287 whatever. */
2288 };
2289
2290 /* The volume of remote transfers can be limited by submitting
2291 a mask containing bits specifying the desired information.
2292 Use a union of these values as the 'selection' parameter to
2293 get_thread_info. FIXME: Make these TAG names more thread specific. */
2294
2295 #define TAG_THREADID 1
2296 #define TAG_EXISTS 2
2297 #define TAG_DISPLAY 4
2298 #define TAG_THREADNAME 8
2299 #define TAG_MOREDISPLAY 16
2300
2301 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2302
2303 static char *unpack_nibble (char *buf, int *val);
2304
2305 static char *unpack_byte (char *buf, int *value);
2306
2307 static char *pack_int (char *buf, int value);
2308
2309 static char *unpack_int (char *buf, int *value);
2310
2311 static char *unpack_string (char *src, char *dest, int length);
2312
2313 static char *pack_threadid (char *pkt, threadref *id);
2314
2315 static char *unpack_threadid (char *inbuf, threadref *id);
2316
2317 void int_to_threadref (threadref *id, int value);
2318
2319 static int threadref_to_int (threadref *ref);
2320
2321 static void copy_threadref (threadref *dest, threadref *src);
2322
2323 static int threadmatch (threadref *dest, threadref *src);
2324
2325 static char *pack_threadinfo_request (char *pkt, int mode,
2326 threadref *id);
2327
2328 static int remote_unpack_thread_info_response (char *pkt,
2329 threadref *expectedref,
2330 struct gdb_ext_thread_info
2331 *info);
2332
2333
2334 static int remote_get_threadinfo (threadref *threadid,
2335 int fieldset, /*TAG mask */
2336 struct gdb_ext_thread_info *info);
2337
2338 static char *pack_threadlist_request (char *pkt, int startflag,
2339 int threadcount,
2340 threadref *nextthread);
2341
2342 static int parse_threadlist_response (char *pkt,
2343 int result_limit,
2344 threadref *original_echo,
2345 threadref *resultlist,
2346 int *doneflag);
2347
2348 static int remote_get_threadlist (int startflag,
2349 threadref *nextthread,
2350 int result_limit,
2351 int *done,
2352 int *result_count,
2353 threadref *threadlist);
2354
2355 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2356
2357 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2358 void *context, int looplimit);
2359
2360 static int remote_newthread_step (threadref *ref, void *context);
2361
2362
2363 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2364 buffer we're allowed to write to. Returns
2365 BUF+CHARACTERS_WRITTEN. */
2366
2367 static char *
2368 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2369 {
2370 int pid, tid;
2371 struct remote_state *rs = get_remote_state ();
2372
2373 if (remote_multi_process_p (rs))
2374 {
2375 pid = ptid_get_pid (ptid);
2376 if (pid < 0)
2377 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2378 else
2379 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2380 }
2381 tid = ptid_get_lwp (ptid);
2382 if (tid < 0)
2383 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2384 else
2385 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2386
2387 return buf;
2388 }
2389
2390 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2391 passed the last parsed char. Returns null_ptid on error. */
2392
2393 static ptid_t
2394 read_ptid (char *buf, char **obuf)
2395 {
2396 char *p = buf;
2397 char *pp;
2398 ULONGEST pid = 0, tid = 0;
2399
2400 if (*p == 'p')
2401 {
2402 /* Multi-process ptid. */
2403 pp = unpack_varlen_hex (p + 1, &pid);
2404 if (*pp != '.')
2405 error (_("invalid remote ptid: %s"), p);
2406
2407 p = pp;
2408 pp = unpack_varlen_hex (p + 1, &tid);
2409 if (obuf)
2410 *obuf = pp;
2411 return ptid_build (pid, tid, 0);
2412 }
2413
2414 /* No multi-process. Just a tid. */
2415 pp = unpack_varlen_hex (p, &tid);
2416
2417 /* Return null_ptid when no thread id is found. */
2418 if (p == pp)
2419 {
2420 if (obuf)
2421 *obuf = pp;
2422 return null_ptid;
2423 }
2424
2425 /* Since the stub is not sending a process id, then default to
2426 what's in inferior_ptid, unless it's null at this point. If so,
2427 then since there's no way to know the pid of the reported
2428 threads, use the magic number. */
2429 if (ptid_equal (inferior_ptid, null_ptid))
2430 pid = ptid_get_pid (magic_null_ptid);
2431 else
2432 pid = ptid_get_pid (inferior_ptid);
2433
2434 if (obuf)
2435 *obuf = pp;
2436 return ptid_build (pid, tid, 0);
2437 }
2438
2439 static int
2440 stubhex (int ch)
2441 {
2442 if (ch >= 'a' && ch <= 'f')
2443 return ch - 'a' + 10;
2444 if (ch >= '0' && ch <= '9')
2445 return ch - '0';
2446 if (ch >= 'A' && ch <= 'F')
2447 return ch - 'A' + 10;
2448 return -1;
2449 }
2450
2451 static int
2452 stub_unpack_int (char *buff, int fieldlength)
2453 {
2454 int nibble;
2455 int retval = 0;
2456
2457 while (fieldlength)
2458 {
2459 nibble = stubhex (*buff++);
2460 retval |= nibble;
2461 fieldlength--;
2462 if (fieldlength)
2463 retval = retval << 4;
2464 }
2465 return retval;
2466 }
2467
2468 static char *
2469 unpack_nibble (char *buf, int *val)
2470 {
2471 *val = fromhex (*buf++);
2472 return buf;
2473 }
2474
2475 static char *
2476 unpack_byte (char *buf, int *value)
2477 {
2478 *value = stub_unpack_int (buf, 2);
2479 return buf + 2;
2480 }
2481
2482 static char *
2483 pack_int (char *buf, int value)
2484 {
2485 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2486 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2487 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2488 buf = pack_hex_byte (buf, (value & 0xff));
2489 return buf;
2490 }
2491
2492 static char *
2493 unpack_int (char *buf, int *value)
2494 {
2495 *value = stub_unpack_int (buf, 8);
2496 return buf + 8;
2497 }
2498
2499 #if 0 /* Currently unused, uncomment when needed. */
2500 static char *pack_string (char *pkt, char *string);
2501
2502 static char *
2503 pack_string (char *pkt, char *string)
2504 {
2505 char ch;
2506 int len;
2507
2508 len = strlen (string);
2509 if (len > 200)
2510 len = 200; /* Bigger than most GDB packets, junk??? */
2511 pkt = pack_hex_byte (pkt, len);
2512 while (len-- > 0)
2513 {
2514 ch = *string++;
2515 if ((ch == '\0') || (ch == '#'))
2516 ch = '*'; /* Protect encapsulation. */
2517 *pkt++ = ch;
2518 }
2519 return pkt;
2520 }
2521 #endif /* 0 (unused) */
2522
2523 static char *
2524 unpack_string (char *src, char *dest, int length)
2525 {
2526 while (length--)
2527 *dest++ = *src++;
2528 *dest = '\0';
2529 return src;
2530 }
2531
2532 static char *
2533 pack_threadid (char *pkt, threadref *id)
2534 {
2535 char *limit;
2536 unsigned char *altid;
2537
2538 altid = (unsigned char *) id;
2539 limit = pkt + BUF_THREAD_ID_SIZE;
2540 while (pkt < limit)
2541 pkt = pack_hex_byte (pkt, *altid++);
2542 return pkt;
2543 }
2544
2545
2546 static char *
2547 unpack_threadid (char *inbuf, threadref *id)
2548 {
2549 char *altref;
2550 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2551 int x, y;
2552
2553 altref = (char *) id;
2554
2555 while (inbuf < limit)
2556 {
2557 x = stubhex (*inbuf++);
2558 y = stubhex (*inbuf++);
2559 *altref++ = (x << 4) | y;
2560 }
2561 return inbuf;
2562 }
2563
2564 /* Externally, threadrefs are 64 bits but internally, they are still
2565 ints. This is due to a mismatch of specifications. We would like
2566 to use 64bit thread references internally. This is an adapter
2567 function. */
2568
2569 void
2570 int_to_threadref (threadref *id, int value)
2571 {
2572 unsigned char *scan;
2573
2574 scan = (unsigned char *) id;
2575 {
2576 int i = 4;
2577 while (i--)
2578 *scan++ = 0;
2579 }
2580 *scan++ = (value >> 24) & 0xff;
2581 *scan++ = (value >> 16) & 0xff;
2582 *scan++ = (value >> 8) & 0xff;
2583 *scan++ = (value & 0xff);
2584 }
2585
2586 static int
2587 threadref_to_int (threadref *ref)
2588 {
2589 int i, value = 0;
2590 unsigned char *scan;
2591
2592 scan = *ref;
2593 scan += 4;
2594 i = 4;
2595 while (i-- > 0)
2596 value = (value << 8) | ((*scan++) & 0xff);
2597 return value;
2598 }
2599
2600 static void
2601 copy_threadref (threadref *dest, threadref *src)
2602 {
2603 int i;
2604 unsigned char *csrc, *cdest;
2605
2606 csrc = (unsigned char *) src;
2607 cdest = (unsigned char *) dest;
2608 i = 8;
2609 while (i--)
2610 *cdest++ = *csrc++;
2611 }
2612
2613 static int
2614 threadmatch (threadref *dest, threadref *src)
2615 {
2616 /* Things are broken right now, so just assume we got a match. */
2617 #if 0
2618 unsigned char *srcp, *destp;
2619 int i, result;
2620 srcp = (char *) src;
2621 destp = (char *) dest;
2622
2623 result = 1;
2624 while (i-- > 0)
2625 result &= (*srcp++ == *destp++) ? 1 : 0;
2626 return result;
2627 #endif
2628 return 1;
2629 }
2630
2631 /*
2632 threadid:1, # always request threadid
2633 context_exists:2,
2634 display:4,
2635 unique_name:8,
2636 more_display:16
2637 */
2638
2639 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2640
2641 static char *
2642 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2643 {
2644 *pkt++ = 'q'; /* Info Query */
2645 *pkt++ = 'P'; /* process or thread info */
2646 pkt = pack_int (pkt, mode); /* mode */
2647 pkt = pack_threadid (pkt, id); /* threadid */
2648 *pkt = '\0'; /* terminate */
2649 return pkt;
2650 }
2651
2652 /* These values tag the fields in a thread info response packet. */
2653 /* Tagging the fields allows us to request specific fields and to
2654 add more fields as time goes by. */
2655
2656 #define TAG_THREADID 1 /* Echo the thread identifier. */
2657 #define TAG_EXISTS 2 /* Is this process defined enough to
2658 fetch registers and its stack? */
2659 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2660 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2661 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2662 the process. */
2663
2664 static int
2665 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2666 struct gdb_ext_thread_info *info)
2667 {
2668 struct remote_state *rs = get_remote_state ();
2669 int mask, length;
2670 int tag;
2671 threadref ref;
2672 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2673 int retval = 1;
2674
2675 /* info->threadid = 0; FIXME: implement zero_threadref. */
2676 info->active = 0;
2677 info->display[0] = '\0';
2678 info->shortname[0] = '\0';
2679 info->more_display[0] = '\0';
2680
2681 /* Assume the characters indicating the packet type have been
2682 stripped. */
2683 pkt = unpack_int (pkt, &mask); /* arg mask */
2684 pkt = unpack_threadid (pkt, &ref);
2685
2686 if (mask == 0)
2687 warning (_("Incomplete response to threadinfo request."));
2688 if (!threadmatch (&ref, expectedref))
2689 { /* This is an answer to a different request. */
2690 warning (_("ERROR RMT Thread info mismatch."));
2691 return 0;
2692 }
2693 copy_threadref (&info->threadid, &ref);
2694
2695 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2696
2697 /* Packets are terminated with nulls. */
2698 while ((pkt < limit) && mask && *pkt)
2699 {
2700 pkt = unpack_int (pkt, &tag); /* tag */
2701 pkt = unpack_byte (pkt, &length); /* length */
2702 if (!(tag & mask)) /* Tags out of synch with mask. */
2703 {
2704 warning (_("ERROR RMT: threadinfo tag mismatch."));
2705 retval = 0;
2706 break;
2707 }
2708 if (tag == TAG_THREADID)
2709 {
2710 if (length != 16)
2711 {
2712 warning (_("ERROR RMT: length of threadid is not 16."));
2713 retval = 0;
2714 break;
2715 }
2716 pkt = unpack_threadid (pkt, &ref);
2717 mask = mask & ~TAG_THREADID;
2718 continue;
2719 }
2720 if (tag == TAG_EXISTS)
2721 {
2722 info->active = stub_unpack_int (pkt, length);
2723 pkt += length;
2724 mask = mask & ~(TAG_EXISTS);
2725 if (length > 8)
2726 {
2727 warning (_("ERROR RMT: 'exists' length too long."));
2728 retval = 0;
2729 break;
2730 }
2731 continue;
2732 }
2733 if (tag == TAG_THREADNAME)
2734 {
2735 pkt = unpack_string (pkt, &info->shortname[0], length);
2736 mask = mask & ~TAG_THREADNAME;
2737 continue;
2738 }
2739 if (tag == TAG_DISPLAY)
2740 {
2741 pkt = unpack_string (pkt, &info->display[0], length);
2742 mask = mask & ~TAG_DISPLAY;
2743 continue;
2744 }
2745 if (tag == TAG_MOREDISPLAY)
2746 {
2747 pkt = unpack_string (pkt, &info->more_display[0], length);
2748 mask = mask & ~TAG_MOREDISPLAY;
2749 continue;
2750 }
2751 warning (_("ERROR RMT: unknown thread info tag."));
2752 break; /* Not a tag we know about. */
2753 }
2754 return retval;
2755 }
2756
2757 static int
2758 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2759 struct gdb_ext_thread_info *info)
2760 {
2761 struct remote_state *rs = get_remote_state ();
2762 int result;
2763
2764 pack_threadinfo_request (rs->buf, fieldset, threadid);
2765 putpkt (rs->buf);
2766 getpkt (&rs->buf, &rs->buf_size, 0);
2767
2768 if (rs->buf[0] == '\0')
2769 return 0;
2770
2771 result = remote_unpack_thread_info_response (rs->buf + 2,
2772 threadid, info);
2773 return result;
2774 }
2775
2776 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2777
2778 static char *
2779 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2780 threadref *nextthread)
2781 {
2782 *pkt++ = 'q'; /* info query packet */
2783 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2784 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2785 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2786 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2787 *pkt = '\0';
2788 return pkt;
2789 }
2790
2791 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2792
2793 static int
2794 parse_threadlist_response (char *pkt, int result_limit,
2795 threadref *original_echo, threadref *resultlist,
2796 int *doneflag)
2797 {
2798 struct remote_state *rs = get_remote_state ();
2799 char *limit;
2800 int count, resultcount, done;
2801
2802 resultcount = 0;
2803 /* Assume the 'q' and 'M chars have been stripped. */
2804 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2805 /* done parse past here */
2806 pkt = unpack_byte (pkt, &count); /* count field */
2807 pkt = unpack_nibble (pkt, &done);
2808 /* The first threadid is the argument threadid. */
2809 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2810 while ((count-- > 0) && (pkt < limit))
2811 {
2812 pkt = unpack_threadid (pkt, resultlist++);
2813 if (resultcount++ >= result_limit)
2814 break;
2815 }
2816 if (doneflag)
2817 *doneflag = done;
2818 return resultcount;
2819 }
2820
2821 /* Fetch the next batch of threads from the remote. Returns -1 if the
2822 qL packet is not supported, 0 on error and 1 on success. */
2823
2824 static int
2825 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2826 int *done, int *result_count, threadref *threadlist)
2827 {
2828 struct remote_state *rs = get_remote_state ();
2829 int result = 1;
2830
2831 /* Trancate result limit to be smaller than the packet size. */
2832 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2833 >= get_remote_packet_size ())
2834 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2835
2836 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2837 putpkt (rs->buf);
2838 getpkt (&rs->buf, &rs->buf_size, 0);
2839 if (*rs->buf == '\0')
2840 {
2841 /* Packet not supported. */
2842 return -1;
2843 }
2844
2845 *result_count =
2846 parse_threadlist_response (rs->buf + 2, result_limit,
2847 &rs->echo_nextthread, threadlist, done);
2848
2849 if (!threadmatch (&rs->echo_nextthread, nextthread))
2850 {
2851 /* FIXME: This is a good reason to drop the packet. */
2852 /* Possably, there is a duplicate response. */
2853 /* Possabilities :
2854 retransmit immediatly - race conditions
2855 retransmit after timeout - yes
2856 exit
2857 wait for packet, then exit
2858 */
2859 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2860 return 0; /* I choose simply exiting. */
2861 }
2862 if (*result_count <= 0)
2863 {
2864 if (*done != 1)
2865 {
2866 warning (_("RMT ERROR : failed to get remote thread list."));
2867 result = 0;
2868 }
2869 return result; /* break; */
2870 }
2871 if (*result_count > result_limit)
2872 {
2873 *result_count = 0;
2874 warning (_("RMT ERROR: threadlist response longer than requested."));
2875 return 0;
2876 }
2877 return result;
2878 }
2879
2880 /* Fetch the list of remote threads, with the qL packet, and call
2881 STEPFUNCTION for each thread found. Stops iterating and returns 1
2882 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2883 STEPFUNCTION returns false. If the packet is not supported,
2884 returns -1. */
2885
2886 static int
2887 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2888 int looplimit)
2889 {
2890 struct remote_state *rs = get_remote_state ();
2891 int done, i, result_count;
2892 int startflag = 1;
2893 int result = 1;
2894 int loopcount = 0;
2895
2896 done = 0;
2897 while (!done)
2898 {
2899 if (loopcount++ > looplimit)
2900 {
2901 result = 0;
2902 warning (_("Remote fetch threadlist -infinite loop-."));
2903 break;
2904 }
2905 result = remote_get_threadlist (startflag, &rs->nextthread,
2906 MAXTHREADLISTRESULTS,
2907 &done, &result_count,
2908 rs->resultthreadlist);
2909 if (result <= 0)
2910 break;
2911 /* Clear for later iterations. */
2912 startflag = 0;
2913 /* Setup to resume next batch of thread references, set nextthread. */
2914 if (result_count >= 1)
2915 copy_threadref (&rs->nextthread,
2916 &rs->resultthreadlist[result_count - 1]);
2917 i = 0;
2918 while (result_count--)
2919 {
2920 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2921 {
2922 result = 0;
2923 break;
2924 }
2925 }
2926 }
2927 return result;
2928 }
2929
2930 /* A thread found on the remote target. */
2931
2932 typedef struct thread_item
2933 {
2934 /* The thread's PTID. */
2935 ptid_t ptid;
2936
2937 /* The thread's extra info. May be NULL. */
2938 char *extra;
2939
2940 /* The thread's name. May be NULL. */
2941 char *name;
2942
2943 /* The core the thread was running on. -1 if not known. */
2944 int core;
2945 } thread_item_t;
2946 DEF_VEC_O(thread_item_t);
2947
2948 /* Context passed around to the various methods listing remote
2949 threads. As new threads are found, they're added to the ITEMS
2950 vector. */
2951
2952 struct threads_listing_context
2953 {
2954 /* The threads found on the remote target. */
2955 VEC (thread_item_t) *items;
2956 };
2957
2958 /* Discard the contents of the constructed thread listing context. */
2959
2960 static void
2961 clear_threads_listing_context (void *p)
2962 {
2963 struct threads_listing_context *context
2964 = (struct threads_listing_context *) p;
2965 int i;
2966 struct thread_item *item;
2967
2968 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2969 {
2970 xfree (item->extra);
2971 xfree (item->name);
2972 }
2973
2974 VEC_free (thread_item_t, context->items);
2975 }
2976
2977 /* Remove the thread specified as the related_pid field of WS
2978 from the CONTEXT list. */
2979
2980 static void
2981 threads_listing_context_remove (struct target_waitstatus *ws,
2982 struct threads_listing_context *context)
2983 {
2984 struct thread_item *item;
2985 int i;
2986 ptid_t child_ptid = ws->value.related_pid;
2987
2988 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2989 {
2990 if (ptid_equal (item->ptid, child_ptid))
2991 {
2992 VEC_ordered_remove (thread_item_t, context->items, i);
2993 break;
2994 }
2995 }
2996 }
2997
2998 static int
2999 remote_newthread_step (threadref *ref, void *data)
3000 {
3001 struct threads_listing_context *context
3002 = (struct threads_listing_context *) data;
3003 struct thread_item item;
3004 int pid = ptid_get_pid (inferior_ptid);
3005
3006 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3007 item.core = -1;
3008 item.name = NULL;
3009 item.extra = NULL;
3010
3011 VEC_safe_push (thread_item_t, context->items, &item);
3012
3013 return 1; /* continue iterator */
3014 }
3015
3016 #define CRAZY_MAX_THREADS 1000
3017
3018 static ptid_t
3019 remote_current_thread (ptid_t oldpid)
3020 {
3021 struct remote_state *rs = get_remote_state ();
3022
3023 putpkt ("qC");
3024 getpkt (&rs->buf, &rs->buf_size, 0);
3025 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3026 {
3027 char *obuf;
3028 ptid_t result;
3029
3030 result = read_ptid (&rs->buf[2], &obuf);
3031 if (*obuf != '\0' && remote_debug)
3032 fprintf_unfiltered (gdb_stdlog,
3033 "warning: garbage in qC reply\n");
3034
3035 return result;
3036 }
3037 else
3038 return oldpid;
3039 }
3040
3041 /* List remote threads using the deprecated qL packet. */
3042
3043 static int
3044 remote_get_threads_with_ql (struct target_ops *ops,
3045 struct threads_listing_context *context)
3046 {
3047 if (remote_threadlist_iterator (remote_newthread_step, context,
3048 CRAZY_MAX_THREADS) >= 0)
3049 return 1;
3050
3051 return 0;
3052 }
3053
3054 #if defined(HAVE_LIBEXPAT)
3055
3056 static void
3057 start_thread (struct gdb_xml_parser *parser,
3058 const struct gdb_xml_element *element,
3059 void *user_data, VEC(gdb_xml_value_s) *attributes)
3060 {
3061 struct threads_listing_context *data
3062 = (struct threads_listing_context *) user_data;
3063
3064 struct thread_item item;
3065 char *id;
3066 struct gdb_xml_value *attr;
3067
3068 id = (char *) xml_find_attribute (attributes, "id")->value;
3069 item.ptid = read_ptid (id, NULL);
3070
3071 attr = xml_find_attribute (attributes, "core");
3072 if (attr != NULL)
3073 item.core = *(ULONGEST *) attr->value;
3074 else
3075 item.core = -1;
3076
3077 attr = xml_find_attribute (attributes, "name");
3078 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3079
3080 item.extra = 0;
3081
3082 VEC_safe_push (thread_item_t, data->items, &item);
3083 }
3084
3085 static void
3086 end_thread (struct gdb_xml_parser *parser,
3087 const struct gdb_xml_element *element,
3088 void *user_data, const char *body_text)
3089 {
3090 struct threads_listing_context *data
3091 = (struct threads_listing_context *) user_data;
3092
3093 if (body_text && *body_text)
3094 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3095 }
3096
3097 const struct gdb_xml_attribute thread_attributes[] = {
3098 { "id", GDB_XML_AF_NONE, NULL, NULL },
3099 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3100 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3101 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3102 };
3103
3104 const struct gdb_xml_element thread_children[] = {
3105 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3106 };
3107
3108 const struct gdb_xml_element threads_children[] = {
3109 { "thread", thread_attributes, thread_children,
3110 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3111 start_thread, end_thread },
3112 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3113 };
3114
3115 const struct gdb_xml_element threads_elements[] = {
3116 { "threads", NULL, threads_children,
3117 GDB_XML_EF_NONE, NULL, NULL },
3118 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3119 };
3120
3121 #endif
3122
3123 /* List remote threads using qXfer:threads:read. */
3124
3125 static int
3126 remote_get_threads_with_qxfer (struct target_ops *ops,
3127 struct threads_listing_context *context)
3128 {
3129 #if defined(HAVE_LIBEXPAT)
3130 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3131 {
3132 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3133 struct cleanup *back_to = make_cleanup (xfree, xml);
3134
3135 if (xml != NULL && *xml != '\0')
3136 {
3137 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3138 threads_elements, xml, context);
3139 }
3140
3141 do_cleanups (back_to);
3142 return 1;
3143 }
3144 #endif
3145
3146 return 0;
3147 }
3148
3149 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3150
3151 static int
3152 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3153 struct threads_listing_context *context)
3154 {
3155 struct remote_state *rs = get_remote_state ();
3156
3157 if (rs->use_threadinfo_query)
3158 {
3159 char *bufp;
3160
3161 putpkt ("qfThreadInfo");
3162 getpkt (&rs->buf, &rs->buf_size, 0);
3163 bufp = rs->buf;
3164 if (bufp[0] != '\0') /* q packet recognized */
3165 {
3166 while (*bufp++ == 'm') /* reply contains one or more TID */
3167 {
3168 do
3169 {
3170 struct thread_item item;
3171
3172 item.ptid = read_ptid (bufp, &bufp);
3173 item.core = -1;
3174 item.name = NULL;
3175 item.extra = NULL;
3176
3177 VEC_safe_push (thread_item_t, context->items, &item);
3178 }
3179 while (*bufp++ == ','); /* comma-separated list */
3180 putpkt ("qsThreadInfo");
3181 getpkt (&rs->buf, &rs->buf_size, 0);
3182 bufp = rs->buf;
3183 }
3184 return 1;
3185 }
3186 else
3187 {
3188 /* Packet not recognized. */
3189 rs->use_threadinfo_query = 0;
3190 }
3191 }
3192
3193 return 0;
3194 }
3195
3196 /* Implement the to_update_thread_list function for the remote
3197 targets. */
3198
3199 static void
3200 remote_update_thread_list (struct target_ops *ops)
3201 {
3202 struct threads_listing_context context;
3203 struct cleanup *old_chain;
3204 int got_list = 0;
3205
3206 context.items = NULL;
3207 old_chain = make_cleanup (clear_threads_listing_context, &context);
3208
3209 /* We have a few different mechanisms to fetch the thread list. Try
3210 them all, starting with the most preferred one first, falling
3211 back to older methods. */
3212 if (remote_get_threads_with_qxfer (ops, &context)
3213 || remote_get_threads_with_qthreadinfo (ops, &context)
3214 || remote_get_threads_with_ql (ops, &context))
3215 {
3216 int i;
3217 struct thread_item *item;
3218 struct thread_info *tp, *tmp;
3219
3220 got_list = 1;
3221
3222 if (VEC_empty (thread_item_t, context.items)
3223 && remote_thread_always_alive (ops, inferior_ptid))
3224 {
3225 /* Some targets don't really support threads, but still
3226 reply an (empty) thread list in response to the thread
3227 listing packets, instead of replying "packet not
3228 supported". Exit early so we don't delete the main
3229 thread. */
3230 do_cleanups (old_chain);
3231 return;
3232 }
3233
3234 /* CONTEXT now holds the current thread list on the remote
3235 target end. Delete GDB-side threads no longer found on the
3236 target. */
3237 ALL_THREADS_SAFE (tp, tmp)
3238 {
3239 for (i = 0;
3240 VEC_iterate (thread_item_t, context.items, i, item);
3241 ++i)
3242 {
3243 if (ptid_equal (item->ptid, tp->ptid))
3244 break;
3245 }
3246
3247 if (i == VEC_length (thread_item_t, context.items))
3248 {
3249 /* Not found. */
3250 delete_thread (tp->ptid);
3251 }
3252 }
3253
3254 /* Remove any unreported fork child threads from CONTEXT so
3255 that we don't interfere with follow fork, which is where
3256 creation of such threads is handled. */
3257 remove_new_fork_children (&context);
3258
3259 /* And now add threads we don't know about yet to our list. */
3260 for (i = 0;
3261 VEC_iterate (thread_item_t, context.items, i, item);
3262 ++i)
3263 {
3264 if (!ptid_equal (item->ptid, null_ptid))
3265 {
3266 struct private_thread_info *info;
3267 /* In non-stop mode, we assume new found threads are
3268 executing until proven otherwise with a stop reply.
3269 In all-stop, we can only get here if all threads are
3270 stopped. */
3271 int executing = target_is_non_stop_p () ? 1 : 0;
3272
3273 remote_notice_new_inferior (item->ptid, executing);
3274
3275 info = demand_private_info (item->ptid);
3276 info->core = item->core;
3277 info->extra = item->extra;
3278 item->extra = NULL;
3279 info->name = item->name;
3280 item->name = NULL;
3281 }
3282 }
3283 }
3284
3285 if (!got_list)
3286 {
3287 /* If no thread listing method is supported, then query whether
3288 each known thread is alive, one by one, with the T packet.
3289 If the target doesn't support threads at all, then this is a
3290 no-op. See remote_thread_alive. */
3291 prune_threads ();
3292 }
3293
3294 do_cleanups (old_chain);
3295 }
3296
3297 /*
3298 * Collect a descriptive string about the given thread.
3299 * The target may say anything it wants to about the thread
3300 * (typically info about its blocked / runnable state, name, etc.).
3301 * This string will appear in the info threads display.
3302 *
3303 * Optional: targets are not required to implement this function.
3304 */
3305
3306 static char *
3307 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3308 {
3309 struct remote_state *rs = get_remote_state ();
3310 int result;
3311 int set;
3312 threadref id;
3313 struct gdb_ext_thread_info threadinfo;
3314 static char display_buf[100]; /* arbitrary... */
3315 int n = 0; /* position in display_buf */
3316
3317 if (rs->remote_desc == 0) /* paranoia */
3318 internal_error (__FILE__, __LINE__,
3319 _("remote_threads_extra_info"));
3320
3321 if (ptid_equal (tp->ptid, magic_null_ptid)
3322 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3323 /* This is the main thread which was added by GDB. The remote
3324 server doesn't know about it. */
3325 return NULL;
3326
3327 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3328 {
3329 struct thread_info *info = find_thread_ptid (tp->ptid);
3330
3331 if (info && info->priv)
3332 return info->priv->extra;
3333 else
3334 return NULL;
3335 }
3336
3337 if (rs->use_threadextra_query)
3338 {
3339 char *b = rs->buf;
3340 char *endb = rs->buf + get_remote_packet_size ();
3341
3342 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3343 b += strlen (b);
3344 write_ptid (b, endb, tp->ptid);
3345
3346 putpkt (rs->buf);
3347 getpkt (&rs->buf, &rs->buf_size, 0);
3348 if (rs->buf[0] != 0)
3349 {
3350 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3351 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3352 display_buf [result] = '\0';
3353 return display_buf;
3354 }
3355 }
3356
3357 /* If the above query fails, fall back to the old method. */
3358 rs->use_threadextra_query = 0;
3359 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3360 | TAG_MOREDISPLAY | TAG_DISPLAY;
3361 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3362 if (remote_get_threadinfo (&id, set, &threadinfo))
3363 if (threadinfo.active)
3364 {
3365 if (*threadinfo.shortname)
3366 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3367 " Name: %s,", threadinfo.shortname);
3368 if (*threadinfo.display)
3369 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3370 " State: %s,", threadinfo.display);
3371 if (*threadinfo.more_display)
3372 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3373 " Priority: %s", threadinfo.more_display);
3374
3375 if (n > 0)
3376 {
3377 /* For purely cosmetic reasons, clear up trailing commas. */
3378 if (',' == display_buf[n-1])
3379 display_buf[n-1] = ' ';
3380 return display_buf;
3381 }
3382 }
3383 return NULL;
3384 }
3385 \f
3386
3387 static int
3388 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3389 struct static_tracepoint_marker *marker)
3390 {
3391 struct remote_state *rs = get_remote_state ();
3392 char *p = rs->buf;
3393
3394 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3395 p += strlen (p);
3396 p += hexnumstr (p, addr);
3397 putpkt (rs->buf);
3398 getpkt (&rs->buf, &rs->buf_size, 0);
3399 p = rs->buf;
3400
3401 if (*p == 'E')
3402 error (_("Remote failure reply: %s"), p);
3403
3404 if (*p++ == 'm')
3405 {
3406 parse_static_tracepoint_marker_definition (p, &p, marker);
3407 return 1;
3408 }
3409
3410 return 0;
3411 }
3412
3413 static VEC(static_tracepoint_marker_p) *
3414 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3415 const char *strid)
3416 {
3417 struct remote_state *rs = get_remote_state ();
3418 VEC(static_tracepoint_marker_p) *markers = NULL;
3419 struct static_tracepoint_marker *marker = NULL;
3420 struct cleanup *old_chain;
3421 char *p;
3422
3423 /* Ask for a first packet of static tracepoint marker
3424 definition. */
3425 putpkt ("qTfSTM");
3426 getpkt (&rs->buf, &rs->buf_size, 0);
3427 p = rs->buf;
3428 if (*p == 'E')
3429 error (_("Remote failure reply: %s"), p);
3430
3431 old_chain = make_cleanup (free_current_marker, &marker);
3432
3433 while (*p++ == 'm')
3434 {
3435 if (marker == NULL)
3436 marker = XCNEW (struct static_tracepoint_marker);
3437
3438 do
3439 {
3440 parse_static_tracepoint_marker_definition (p, &p, marker);
3441
3442 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3443 {
3444 VEC_safe_push (static_tracepoint_marker_p,
3445 markers, marker);
3446 marker = NULL;
3447 }
3448 else
3449 {
3450 release_static_tracepoint_marker (marker);
3451 memset (marker, 0, sizeof (*marker));
3452 }
3453 }
3454 while (*p++ == ','); /* comma-separated list */
3455 /* Ask for another packet of static tracepoint definition. */
3456 putpkt ("qTsSTM");
3457 getpkt (&rs->buf, &rs->buf_size, 0);
3458 p = rs->buf;
3459 }
3460
3461 do_cleanups (old_chain);
3462 return markers;
3463 }
3464
3465 \f
3466 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3467
3468 static ptid_t
3469 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3470 {
3471 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3472 }
3473 \f
3474
3475 /* Restart the remote side; this is an extended protocol operation. */
3476
3477 static void
3478 extended_remote_restart (void)
3479 {
3480 struct remote_state *rs = get_remote_state ();
3481
3482 /* Send the restart command; for reasons I don't understand the
3483 remote side really expects a number after the "R". */
3484 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3485 putpkt (rs->buf);
3486
3487 remote_fileio_reset ();
3488 }
3489 \f
3490 /* Clean up connection to a remote debugger. */
3491
3492 static void
3493 remote_close (struct target_ops *self)
3494 {
3495 struct remote_state *rs = get_remote_state ();
3496
3497 if (rs->remote_desc == NULL)
3498 return; /* already closed */
3499
3500 /* Make sure we leave stdin registered in the event loop. */
3501 remote_terminal_ours (self);
3502
3503 serial_close (rs->remote_desc);
3504 rs->remote_desc = NULL;
3505
3506 /* We don't have a connection to the remote stub anymore. Get rid
3507 of all the inferiors and their threads we were controlling.
3508 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3509 will be unable to find the thread corresponding to (pid, 0, 0). */
3510 inferior_ptid = null_ptid;
3511 discard_all_inferiors ();
3512
3513 /* We are closing the remote target, so we should discard
3514 everything of this target. */
3515 discard_pending_stop_replies_in_queue (rs);
3516
3517 if (remote_async_inferior_event_token)
3518 delete_async_event_handler (&remote_async_inferior_event_token);
3519
3520 remote_notif_state_xfree (rs->notif_state);
3521
3522 trace_reset_local_state ();
3523 }
3524
3525 /* Query the remote side for the text, data and bss offsets. */
3526
3527 static void
3528 get_offsets (void)
3529 {
3530 struct remote_state *rs = get_remote_state ();
3531 char *buf;
3532 char *ptr;
3533 int lose, num_segments = 0, do_sections, do_segments;
3534 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3535 struct section_offsets *offs;
3536 struct symfile_segment_data *data;
3537
3538 if (symfile_objfile == NULL)
3539 return;
3540
3541 putpkt ("qOffsets");
3542 getpkt (&rs->buf, &rs->buf_size, 0);
3543 buf = rs->buf;
3544
3545 if (buf[0] == '\000')
3546 return; /* Return silently. Stub doesn't support
3547 this command. */
3548 if (buf[0] == 'E')
3549 {
3550 warning (_("Remote failure reply: %s"), buf);
3551 return;
3552 }
3553
3554 /* Pick up each field in turn. This used to be done with scanf, but
3555 scanf will make trouble if CORE_ADDR size doesn't match
3556 conversion directives correctly. The following code will work
3557 with any size of CORE_ADDR. */
3558 text_addr = data_addr = bss_addr = 0;
3559 ptr = buf;
3560 lose = 0;
3561
3562 if (startswith (ptr, "Text="))
3563 {
3564 ptr += 5;
3565 /* Don't use strtol, could lose on big values. */
3566 while (*ptr && *ptr != ';')
3567 text_addr = (text_addr << 4) + fromhex (*ptr++);
3568
3569 if (startswith (ptr, ";Data="))
3570 {
3571 ptr += 6;
3572 while (*ptr && *ptr != ';')
3573 data_addr = (data_addr << 4) + fromhex (*ptr++);
3574 }
3575 else
3576 lose = 1;
3577
3578 if (!lose && startswith (ptr, ";Bss="))
3579 {
3580 ptr += 5;
3581 while (*ptr && *ptr != ';')
3582 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3583
3584 if (bss_addr != data_addr)
3585 warning (_("Target reported unsupported offsets: %s"), buf);
3586 }
3587 else
3588 lose = 1;
3589 }
3590 else if (startswith (ptr, "TextSeg="))
3591 {
3592 ptr += 8;
3593 /* Don't use strtol, could lose on big values. */
3594 while (*ptr && *ptr != ';')
3595 text_addr = (text_addr << 4) + fromhex (*ptr++);
3596 num_segments = 1;
3597
3598 if (startswith (ptr, ";DataSeg="))
3599 {
3600 ptr += 9;
3601 while (*ptr && *ptr != ';')
3602 data_addr = (data_addr << 4) + fromhex (*ptr++);
3603 num_segments++;
3604 }
3605 }
3606 else
3607 lose = 1;
3608
3609 if (lose)
3610 error (_("Malformed response to offset query, %s"), buf);
3611 else if (*ptr != '\0')
3612 warning (_("Target reported unsupported offsets: %s"), buf);
3613
3614 offs = ((struct section_offsets *)
3615 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3616 memcpy (offs, symfile_objfile->section_offsets,
3617 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3618
3619 data = get_symfile_segment_data (symfile_objfile->obfd);
3620 do_segments = (data != NULL);
3621 do_sections = num_segments == 0;
3622
3623 if (num_segments > 0)
3624 {
3625 segments[0] = text_addr;
3626 segments[1] = data_addr;
3627 }
3628 /* If we have two segments, we can still try to relocate everything
3629 by assuming that the .text and .data offsets apply to the whole
3630 text and data segments. Convert the offsets given in the packet
3631 to base addresses for symfile_map_offsets_to_segments. */
3632 else if (data && data->num_segments == 2)
3633 {
3634 segments[0] = data->segment_bases[0] + text_addr;
3635 segments[1] = data->segment_bases[1] + data_addr;
3636 num_segments = 2;
3637 }
3638 /* If the object file has only one segment, assume that it is text
3639 rather than data; main programs with no writable data are rare,
3640 but programs with no code are useless. Of course the code might
3641 have ended up in the data segment... to detect that we would need
3642 the permissions here. */
3643 else if (data && data->num_segments == 1)
3644 {
3645 segments[0] = data->segment_bases[0] + text_addr;
3646 num_segments = 1;
3647 }
3648 /* There's no way to relocate by segment. */
3649 else
3650 do_segments = 0;
3651
3652 if (do_segments)
3653 {
3654 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3655 offs, num_segments, segments);
3656
3657 if (ret == 0 && !do_sections)
3658 error (_("Can not handle qOffsets TextSeg "
3659 "response with this symbol file"));
3660
3661 if (ret > 0)
3662 do_sections = 0;
3663 }
3664
3665 if (data)
3666 free_symfile_segment_data (data);
3667
3668 if (do_sections)
3669 {
3670 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3671
3672 /* This is a temporary kludge to force data and bss to use the
3673 same offsets because that's what nlmconv does now. The real
3674 solution requires changes to the stub and remote.c that I
3675 don't have time to do right now. */
3676
3677 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3678 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3679 }
3680
3681 objfile_relocate (symfile_objfile, offs);
3682 }
3683
3684 /* Send interrupt_sequence to remote target. */
3685 static void
3686 send_interrupt_sequence (void)
3687 {
3688 struct remote_state *rs = get_remote_state ();
3689
3690 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3691 remote_serial_write ("\x03", 1);
3692 else if (interrupt_sequence_mode == interrupt_sequence_break)
3693 serial_send_break (rs->remote_desc);
3694 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3695 {
3696 serial_send_break (rs->remote_desc);
3697 remote_serial_write ("g", 1);
3698 }
3699 else
3700 internal_error (__FILE__, __LINE__,
3701 _("Invalid value for interrupt_sequence_mode: %s."),
3702 interrupt_sequence_mode);
3703 }
3704
3705
3706 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3707 and extract the PTID. Returns NULL_PTID if not found. */
3708
3709 static ptid_t
3710 stop_reply_extract_thread (char *stop_reply)
3711 {
3712 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3713 {
3714 char *p;
3715
3716 /* Txx r:val ; r:val (...) */
3717 p = &stop_reply[3];
3718
3719 /* Look for "register" named "thread". */
3720 while (*p != '\0')
3721 {
3722 char *p1;
3723
3724 p1 = strchr (p, ':');
3725 if (p1 == NULL)
3726 return null_ptid;
3727
3728 if (strncmp (p, "thread", p1 - p) == 0)
3729 return read_ptid (++p1, &p);
3730
3731 p1 = strchr (p, ';');
3732 if (p1 == NULL)
3733 return null_ptid;
3734 p1++;
3735
3736 p = p1;
3737 }
3738 }
3739
3740 return null_ptid;
3741 }
3742
3743 /* Determine the remote side's current thread. If we have a stop
3744 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3745 "thread" register we can extract the current thread from. If not,
3746 ask the remote which is the current thread with qC. The former
3747 method avoids a roundtrip. */
3748
3749 static ptid_t
3750 get_current_thread (char *wait_status)
3751 {
3752 ptid_t ptid = null_ptid;
3753
3754 /* Note we don't use remote_parse_stop_reply as that makes use of
3755 the target architecture, which we haven't yet fully determined at
3756 this point. */
3757 if (wait_status != NULL)
3758 ptid = stop_reply_extract_thread (wait_status);
3759 if (ptid_equal (ptid, null_ptid))
3760 ptid = remote_current_thread (inferior_ptid);
3761
3762 return ptid;
3763 }
3764
3765 /* Query the remote target for which is the current thread/process,
3766 add it to our tables, and update INFERIOR_PTID. The caller is
3767 responsible for setting the state such that the remote end is ready
3768 to return the current thread.
3769
3770 This function is called after handling the '?' or 'vRun' packets,
3771 whose response is a stop reply from which we can also try
3772 extracting the thread. If the target doesn't support the explicit
3773 qC query, we infer the current thread from that stop reply, passed
3774 in in WAIT_STATUS, which may be NULL. */
3775
3776 static void
3777 add_current_inferior_and_thread (char *wait_status)
3778 {
3779 struct remote_state *rs = get_remote_state ();
3780 int fake_pid_p = 0;
3781 ptid_t ptid;
3782
3783 inferior_ptid = null_ptid;
3784
3785 /* Now, if we have thread information, update inferior_ptid. */
3786 ptid = get_current_thread (wait_status);
3787
3788 if (!ptid_equal (ptid, null_ptid))
3789 {
3790 if (!remote_multi_process_p (rs))
3791 fake_pid_p = 1;
3792
3793 inferior_ptid = ptid;
3794 }
3795 else
3796 {
3797 /* Without this, some commands which require an active target
3798 (such as kill) won't work. This variable serves (at least)
3799 double duty as both the pid of the target process (if it has
3800 such), and as a flag indicating that a target is active. */
3801 inferior_ptid = magic_null_ptid;
3802 fake_pid_p = 1;
3803 }
3804
3805 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3806
3807 /* Add the main thread. */
3808 add_thread_silent (inferior_ptid);
3809 }
3810
3811 /* Print info about a thread that was found already stopped on
3812 connection. */
3813
3814 static void
3815 print_one_stopped_thread (struct thread_info *thread)
3816 {
3817 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3818
3819 switch_to_thread (thread->ptid);
3820 stop_pc = get_frame_pc (get_current_frame ());
3821 set_current_sal_from_frame (get_current_frame ());
3822
3823 thread->suspend.waitstatus_pending_p = 0;
3824
3825 if (ws->kind == TARGET_WAITKIND_STOPPED)
3826 {
3827 enum gdb_signal sig = ws->value.sig;
3828
3829 if (signal_print_state (sig))
3830 observer_notify_signal_received (sig);
3831 }
3832 observer_notify_normal_stop (NULL, 1);
3833 }
3834
3835 /* Process all initial stop replies the remote side sent in response
3836 to the ? packet. These indicate threads that were already stopped
3837 on initial connection. We mark these threads as stopped and print
3838 their current frame before giving the user the prompt. */
3839
3840 static void
3841 process_initial_stop_replies (int from_tty)
3842 {
3843 int pending_stop_replies = stop_reply_queue_length ();
3844 struct inferior *inf;
3845 struct thread_info *thread;
3846 struct thread_info *selected = NULL;
3847 struct thread_info *lowest_stopped = NULL;
3848 struct thread_info *first = NULL;
3849
3850 /* Consume the initial pending events. */
3851 while (pending_stop_replies-- > 0)
3852 {
3853 ptid_t waiton_ptid = minus_one_ptid;
3854 ptid_t event_ptid;
3855 struct target_waitstatus ws;
3856 int ignore_event = 0;
3857 struct thread_info *thread;
3858
3859 memset (&ws, 0, sizeof (ws));
3860 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3861 if (remote_debug)
3862 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3863
3864 switch (ws.kind)
3865 {
3866 case TARGET_WAITKIND_IGNORE:
3867 case TARGET_WAITKIND_NO_RESUMED:
3868 case TARGET_WAITKIND_SIGNALLED:
3869 case TARGET_WAITKIND_EXITED:
3870 /* We shouldn't see these, but if we do, just ignore. */
3871 if (remote_debug)
3872 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3873 ignore_event = 1;
3874 break;
3875
3876 case TARGET_WAITKIND_EXECD:
3877 xfree (ws.value.execd_pathname);
3878 break;
3879 default:
3880 break;
3881 }
3882
3883 if (ignore_event)
3884 continue;
3885
3886 thread = find_thread_ptid (event_ptid);
3887
3888 if (ws.kind == TARGET_WAITKIND_STOPPED)
3889 {
3890 enum gdb_signal sig = ws.value.sig;
3891
3892 /* Stubs traditionally report SIGTRAP as initial signal,
3893 instead of signal 0. Suppress it. */
3894 if (sig == GDB_SIGNAL_TRAP)
3895 sig = GDB_SIGNAL_0;
3896 thread->suspend.stop_signal = sig;
3897 ws.value.sig = sig;
3898 }
3899
3900 thread->suspend.waitstatus = ws;
3901
3902 if (ws.kind != TARGET_WAITKIND_STOPPED
3903 || ws.value.sig != GDB_SIGNAL_0)
3904 thread->suspend.waitstatus_pending_p = 1;
3905
3906 set_executing (event_ptid, 0);
3907 set_running (event_ptid, 0);
3908 }
3909
3910 /* "Notice" the new inferiors before anything related to
3911 registers/memory. */
3912 ALL_INFERIORS (inf)
3913 {
3914 if (inf->pid == 0)
3915 continue;
3916
3917 inf->needs_setup = 1;
3918
3919 if (non_stop)
3920 {
3921 thread = any_live_thread_of_process (inf->pid);
3922 notice_new_inferior (thread->ptid,
3923 thread->state == THREAD_RUNNING,
3924 from_tty);
3925 }
3926 }
3927
3928 /* If all-stop on top of non-stop, pause all threads. Note this
3929 records the threads' stop pc, so must be done after "noticing"
3930 the inferiors. */
3931 if (!non_stop)
3932 {
3933 stop_all_threads ();
3934
3935 /* If all threads of an inferior were already stopped, we
3936 haven't setup the inferior yet. */
3937 ALL_INFERIORS (inf)
3938 {
3939 if (inf->pid == 0)
3940 continue;
3941
3942 if (inf->needs_setup)
3943 {
3944 thread = any_live_thread_of_process (inf->pid);
3945 switch_to_thread_no_regs (thread);
3946 setup_inferior (0);
3947 }
3948 }
3949 }
3950
3951 /* Now go over all threads that are stopped, and print their current
3952 frame. If all-stop, then if there's a signalled thread, pick
3953 that as current. */
3954 ALL_NON_EXITED_THREADS (thread)
3955 {
3956 if (first == NULL)
3957 first = thread;
3958
3959 if (!non_stop)
3960 set_running (thread->ptid, 0);
3961 else if (thread->state != THREAD_STOPPED)
3962 continue;
3963
3964 if (selected == NULL
3965 && thread->suspend.waitstatus_pending_p)
3966 selected = thread;
3967
3968 if (lowest_stopped == NULL
3969 || thread->inf->num < lowest_stopped->inf->num
3970 || thread->per_inf_num < lowest_stopped->per_inf_num)
3971 lowest_stopped = thread;
3972
3973 if (non_stop)
3974 print_one_stopped_thread (thread);
3975 }
3976
3977 /* In all-stop, we only print the status of one thread, and leave
3978 others with their status pending. */
3979 if (!non_stop)
3980 {
3981 thread = selected;
3982 if (thread == NULL)
3983 thread = lowest_stopped;
3984 if (thread == NULL)
3985 thread = first;
3986
3987 print_one_stopped_thread (thread);
3988 }
3989
3990 /* For "info program". */
3991 thread = inferior_thread ();
3992 if (thread->state == THREAD_STOPPED)
3993 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3994 }
3995
3996 /* Start the remote connection and sync state. */
3997
3998 static void
3999 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4000 {
4001 struct remote_state *rs = get_remote_state ();
4002 struct packet_config *noack_config;
4003 char *wait_status = NULL;
4004
4005 /* Signal other parts that we're going through the initial setup,
4006 and so things may not be stable yet. E.g., we don't try to
4007 install tracepoints until we've relocated symbols. Also, a
4008 Ctrl-C before we're connected and synced up can't interrupt the
4009 target. Instead, it offers to drop the (potentially wedged)
4010 connection. */
4011 rs->starting_up = 1;
4012
4013 QUIT;
4014
4015 if (interrupt_on_connect)
4016 send_interrupt_sequence ();
4017
4018 /* Ack any packet which the remote side has already sent. */
4019 remote_serial_write ("+", 1);
4020
4021 /* The first packet we send to the target is the optional "supported
4022 packets" request. If the target can answer this, it will tell us
4023 which later probes to skip. */
4024 remote_query_supported ();
4025
4026 /* If the stub wants to get a QAllow, compose one and send it. */
4027 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4028 remote_set_permissions (target);
4029
4030 /* Next, we possibly activate noack mode.
4031
4032 If the QStartNoAckMode packet configuration is set to AUTO,
4033 enable noack mode if the stub reported a wish for it with
4034 qSupported.
4035
4036 If set to TRUE, then enable noack mode even if the stub didn't
4037 report it in qSupported. If the stub doesn't reply OK, the
4038 session ends with an error.
4039
4040 If FALSE, then don't activate noack mode, regardless of what the
4041 stub claimed should be the default with qSupported. */
4042
4043 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4044 if (packet_config_support (noack_config) != PACKET_DISABLE)
4045 {
4046 putpkt ("QStartNoAckMode");
4047 getpkt (&rs->buf, &rs->buf_size, 0);
4048 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4049 rs->noack_mode = 1;
4050 }
4051
4052 if (extended_p)
4053 {
4054 /* Tell the remote that we are using the extended protocol. */
4055 putpkt ("!");
4056 getpkt (&rs->buf, &rs->buf_size, 0);
4057 }
4058
4059 /* Let the target know which signals it is allowed to pass down to
4060 the program. */
4061 update_signals_program_target ();
4062
4063 /* Next, if the target can specify a description, read it. We do
4064 this before anything involving memory or registers. */
4065 target_find_description ();
4066
4067 /* Next, now that we know something about the target, update the
4068 address spaces in the program spaces. */
4069 update_address_spaces ();
4070
4071 /* On OSs where the list of libraries is global to all
4072 processes, we fetch them early. */
4073 if (gdbarch_has_global_solist (target_gdbarch ()))
4074 solib_add (NULL, from_tty, target, auto_solib_add);
4075
4076 if (target_is_non_stop_p ())
4077 {
4078 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4079 error (_("Non-stop mode requested, but remote "
4080 "does not support non-stop"));
4081
4082 putpkt ("QNonStop:1");
4083 getpkt (&rs->buf, &rs->buf_size, 0);
4084
4085 if (strcmp (rs->buf, "OK") != 0)
4086 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4087
4088 /* Find about threads and processes the stub is already
4089 controlling. We default to adding them in the running state.
4090 The '?' query below will then tell us about which threads are
4091 stopped. */
4092 remote_update_thread_list (target);
4093 }
4094 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4095 {
4096 /* Don't assume that the stub can operate in all-stop mode.
4097 Request it explicitly. */
4098 putpkt ("QNonStop:0");
4099 getpkt (&rs->buf, &rs->buf_size, 0);
4100
4101 if (strcmp (rs->buf, "OK") != 0)
4102 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4103 }
4104
4105 /* Upload TSVs regardless of whether the target is running or not. The
4106 remote stub, such as GDBserver, may have some predefined or builtin
4107 TSVs, even if the target is not running. */
4108 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4109 {
4110 struct uploaded_tsv *uploaded_tsvs = NULL;
4111
4112 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4113 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4114 }
4115
4116 /* Check whether the target is running now. */
4117 putpkt ("?");
4118 getpkt (&rs->buf, &rs->buf_size, 0);
4119
4120 if (!target_is_non_stop_p ())
4121 {
4122 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4123 {
4124 if (!extended_p)
4125 error (_("The target is not running (try extended-remote?)"));
4126
4127 /* We're connected, but not running. Drop out before we
4128 call start_remote. */
4129 rs->starting_up = 0;
4130 return;
4131 }
4132 else
4133 {
4134 /* Save the reply for later. */
4135 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4136 strcpy (wait_status, rs->buf);
4137 }
4138
4139 /* Fetch thread list. */
4140 target_update_thread_list ();
4141
4142 /* Let the stub know that we want it to return the thread. */
4143 set_continue_thread (minus_one_ptid);
4144
4145 if (thread_count () == 0)
4146 {
4147 /* Target has no concept of threads at all. GDB treats
4148 non-threaded target as single-threaded; add a main
4149 thread. */
4150 add_current_inferior_and_thread (wait_status);
4151 }
4152 else
4153 {
4154 /* We have thread information; select the thread the target
4155 says should be current. If we're reconnecting to a
4156 multi-threaded program, this will ideally be the thread
4157 that last reported an event before GDB disconnected. */
4158 inferior_ptid = get_current_thread (wait_status);
4159 if (ptid_equal (inferior_ptid, null_ptid))
4160 {
4161 /* Odd... The target was able to list threads, but not
4162 tell us which thread was current (no "thread"
4163 register in T stop reply?). Just pick the first
4164 thread in the thread list then. */
4165
4166 if (remote_debug)
4167 fprintf_unfiltered (gdb_stdlog,
4168 "warning: couldn't determine remote "
4169 "current thread; picking first in list.\n");
4170
4171 inferior_ptid = thread_list->ptid;
4172 }
4173 }
4174
4175 /* init_wait_for_inferior should be called before get_offsets in order
4176 to manage `inserted' flag in bp loc in a correct state.
4177 breakpoint_init_inferior, called from init_wait_for_inferior, set
4178 `inserted' flag to 0, while before breakpoint_re_set, called from
4179 start_remote, set `inserted' flag to 1. In the initialization of
4180 inferior, breakpoint_init_inferior should be called first, and then
4181 breakpoint_re_set can be called. If this order is broken, state of
4182 `inserted' flag is wrong, and cause some problems on breakpoint
4183 manipulation. */
4184 init_wait_for_inferior ();
4185
4186 get_offsets (); /* Get text, data & bss offsets. */
4187
4188 /* If we could not find a description using qXfer, and we know
4189 how to do it some other way, try again. This is not
4190 supported for non-stop; it could be, but it is tricky if
4191 there are no stopped threads when we connect. */
4192 if (remote_read_description_p (target)
4193 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4194 {
4195 target_clear_description ();
4196 target_find_description ();
4197 }
4198
4199 /* Use the previously fetched status. */
4200 gdb_assert (wait_status != NULL);
4201 strcpy (rs->buf, wait_status);
4202 rs->cached_wait_status = 1;
4203
4204 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4205 }
4206 else
4207 {
4208 /* Clear WFI global state. Do this before finding about new
4209 threads and inferiors, and setting the current inferior.
4210 Otherwise we would clear the proceed status of the current
4211 inferior when we want its stop_soon state to be preserved
4212 (see notice_new_inferior). */
4213 init_wait_for_inferior ();
4214
4215 /* In non-stop, we will either get an "OK", meaning that there
4216 are no stopped threads at this time; or, a regular stop
4217 reply. In the latter case, there may be more than one thread
4218 stopped --- we pull them all out using the vStopped
4219 mechanism. */
4220 if (strcmp (rs->buf, "OK") != 0)
4221 {
4222 struct notif_client *notif = &notif_client_stop;
4223
4224 /* remote_notif_get_pending_replies acks this one, and gets
4225 the rest out. */
4226 rs->notif_state->pending_event[notif_client_stop.id]
4227 = remote_notif_parse (notif, rs->buf);
4228 remote_notif_get_pending_events (notif);
4229 }
4230
4231 if (thread_count () == 0)
4232 {
4233 if (!extended_p)
4234 error (_("The target is not running (try extended-remote?)"));
4235
4236 /* We're connected, but not running. Drop out before we
4237 call start_remote. */
4238 rs->starting_up = 0;
4239 return;
4240 }
4241
4242 /* In non-stop mode, any cached wait status will be stored in
4243 the stop reply queue. */
4244 gdb_assert (wait_status == NULL);
4245
4246 /* Report all signals during attach/startup. */
4247 remote_pass_signals (target, 0, NULL);
4248
4249 /* If there are already stopped threads, mark them stopped and
4250 report their stops before giving the prompt to the user. */
4251 process_initial_stop_replies (from_tty);
4252
4253 if (target_can_async_p ())
4254 target_async (1);
4255 }
4256
4257 /* If we connected to a live target, do some additional setup. */
4258 if (target_has_execution)
4259 {
4260 if (symfile_objfile) /* No use without a symbol-file. */
4261 remote_check_symbols ();
4262 }
4263
4264 /* Possibly the target has been engaged in a trace run started
4265 previously; find out where things are at. */
4266 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4267 {
4268 struct uploaded_tp *uploaded_tps = NULL;
4269
4270 if (current_trace_status ()->running)
4271 printf_filtered (_("Trace is already running on the target.\n"));
4272
4273 remote_upload_tracepoints (target, &uploaded_tps);
4274
4275 merge_uploaded_tracepoints (&uploaded_tps);
4276 }
4277
4278 /* The thread and inferior lists are now synchronized with the
4279 target, our symbols have been relocated, and we're merged the
4280 target's tracepoints with ours. We're done with basic start
4281 up. */
4282 rs->starting_up = 0;
4283
4284 /* Maybe breakpoints are global and need to be inserted now. */
4285 if (breakpoints_should_be_inserted_now ())
4286 insert_breakpoints ();
4287 }
4288
4289 /* Open a connection to a remote debugger.
4290 NAME is the filename used for communication. */
4291
4292 static void
4293 remote_open (const char *name, int from_tty)
4294 {
4295 remote_open_1 (name, from_tty, &remote_ops, 0);
4296 }
4297
4298 /* Open a connection to a remote debugger using the extended
4299 remote gdb protocol. NAME is the filename used for communication. */
4300
4301 static void
4302 extended_remote_open (const char *name, int from_tty)
4303 {
4304 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4305 }
4306
4307 /* Reset all packets back to "unknown support". Called when opening a
4308 new connection to a remote target. */
4309
4310 static void
4311 reset_all_packet_configs_support (void)
4312 {
4313 int i;
4314
4315 for (i = 0; i < PACKET_MAX; i++)
4316 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4317 }
4318
4319 /* Initialize all packet configs. */
4320
4321 static void
4322 init_all_packet_configs (void)
4323 {
4324 int i;
4325
4326 for (i = 0; i < PACKET_MAX; i++)
4327 {
4328 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4329 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4330 }
4331 }
4332
4333 /* Symbol look-up. */
4334
4335 static void
4336 remote_check_symbols (void)
4337 {
4338 struct remote_state *rs = get_remote_state ();
4339 char *msg, *reply, *tmp;
4340 int end;
4341 long reply_size;
4342 struct cleanup *old_chain;
4343
4344 /* The remote side has no concept of inferiors that aren't running
4345 yet, it only knows about running processes. If we're connected
4346 but our current inferior is not running, we should not invite the
4347 remote target to request symbol lookups related to its
4348 (unrelated) current process. */
4349 if (!target_has_execution)
4350 return;
4351
4352 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4353 return;
4354
4355 /* Make sure the remote is pointing at the right process. Note
4356 there's no way to select "no process". */
4357 set_general_process ();
4358
4359 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4360 because we need both at the same time. */
4361 msg = (char *) xmalloc (get_remote_packet_size ());
4362 old_chain = make_cleanup (xfree, msg);
4363 reply = (char *) xmalloc (get_remote_packet_size ());
4364 make_cleanup (free_current_contents, &reply);
4365 reply_size = get_remote_packet_size ();
4366
4367 /* Invite target to request symbol lookups. */
4368
4369 putpkt ("qSymbol::");
4370 getpkt (&reply, &reply_size, 0);
4371 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4372
4373 while (startswith (reply, "qSymbol:"))
4374 {
4375 struct bound_minimal_symbol sym;
4376
4377 tmp = &reply[8];
4378 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4379 msg[end] = '\0';
4380 sym = lookup_minimal_symbol (msg, NULL, NULL);
4381 if (sym.minsym == NULL)
4382 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4383 else
4384 {
4385 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4386 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4387
4388 /* If this is a function address, return the start of code
4389 instead of any data function descriptor. */
4390 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4391 sym_addr,
4392 &current_target);
4393
4394 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4395 phex_nz (sym_addr, addr_size), &reply[8]);
4396 }
4397
4398 putpkt (msg);
4399 getpkt (&reply, &reply_size, 0);
4400 }
4401
4402 do_cleanups (old_chain);
4403 }
4404
4405 static struct serial *
4406 remote_serial_open (const char *name)
4407 {
4408 static int udp_warning = 0;
4409
4410 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4411 of in ser-tcp.c, because it is the remote protocol assuming that the
4412 serial connection is reliable and not the serial connection promising
4413 to be. */
4414 if (!udp_warning && startswith (name, "udp:"))
4415 {
4416 warning (_("The remote protocol may be unreliable over UDP.\n"
4417 "Some events may be lost, rendering further debugging "
4418 "impossible."));
4419 udp_warning = 1;
4420 }
4421
4422 return serial_open (name);
4423 }
4424
4425 /* Inform the target of our permission settings. The permission flags
4426 work without this, but if the target knows the settings, it can do
4427 a couple things. First, it can add its own check, to catch cases
4428 that somehow manage to get by the permissions checks in target
4429 methods. Second, if the target is wired to disallow particular
4430 settings (for instance, a system in the field that is not set up to
4431 be able to stop at a breakpoint), it can object to any unavailable
4432 permissions. */
4433
4434 void
4435 remote_set_permissions (struct target_ops *self)
4436 {
4437 struct remote_state *rs = get_remote_state ();
4438
4439 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4440 "WriteReg:%x;WriteMem:%x;"
4441 "InsertBreak:%x;InsertTrace:%x;"
4442 "InsertFastTrace:%x;Stop:%x",
4443 may_write_registers, may_write_memory,
4444 may_insert_breakpoints, may_insert_tracepoints,
4445 may_insert_fast_tracepoints, may_stop);
4446 putpkt (rs->buf);
4447 getpkt (&rs->buf, &rs->buf_size, 0);
4448
4449 /* If the target didn't like the packet, warn the user. Do not try
4450 to undo the user's settings, that would just be maddening. */
4451 if (strcmp (rs->buf, "OK") != 0)
4452 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4453 }
4454
4455 /* This type describes each known response to the qSupported
4456 packet. */
4457 struct protocol_feature
4458 {
4459 /* The name of this protocol feature. */
4460 const char *name;
4461
4462 /* The default for this protocol feature. */
4463 enum packet_support default_support;
4464
4465 /* The function to call when this feature is reported, or after
4466 qSupported processing if the feature is not supported.
4467 The first argument points to this structure. The second
4468 argument indicates whether the packet requested support be
4469 enabled, disabled, or probed (or the default, if this function
4470 is being called at the end of processing and this feature was
4471 not reported). The third argument may be NULL; if not NULL, it
4472 is a NUL-terminated string taken from the packet following
4473 this feature's name and an equals sign. */
4474 void (*func) (const struct protocol_feature *, enum packet_support,
4475 const char *);
4476
4477 /* The corresponding packet for this feature. Only used if
4478 FUNC is remote_supported_packet. */
4479 int packet;
4480 };
4481
4482 static void
4483 remote_supported_packet (const struct protocol_feature *feature,
4484 enum packet_support support,
4485 const char *argument)
4486 {
4487 if (argument)
4488 {
4489 warning (_("Remote qSupported response supplied an unexpected value for"
4490 " \"%s\"."), feature->name);
4491 return;
4492 }
4493
4494 remote_protocol_packets[feature->packet].support = support;
4495 }
4496
4497 static void
4498 remote_packet_size (const struct protocol_feature *feature,
4499 enum packet_support support, const char *value)
4500 {
4501 struct remote_state *rs = get_remote_state ();
4502
4503 int packet_size;
4504 char *value_end;
4505
4506 if (support != PACKET_ENABLE)
4507 return;
4508
4509 if (value == NULL || *value == '\0')
4510 {
4511 warning (_("Remote target reported \"%s\" without a size."),
4512 feature->name);
4513 return;
4514 }
4515
4516 errno = 0;
4517 packet_size = strtol (value, &value_end, 16);
4518 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4519 {
4520 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4521 feature->name, value);
4522 return;
4523 }
4524
4525 /* Record the new maximum packet size. */
4526 rs->explicit_packet_size = packet_size;
4527 }
4528
4529 static const struct protocol_feature remote_protocol_features[] = {
4530 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4531 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4532 PACKET_qXfer_auxv },
4533 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4534 PACKET_qXfer_exec_file },
4535 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4536 PACKET_qXfer_features },
4537 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4538 PACKET_qXfer_libraries },
4539 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4540 PACKET_qXfer_libraries_svr4 },
4541 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4542 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4543 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4544 PACKET_qXfer_memory_map },
4545 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4546 PACKET_qXfer_spu_read },
4547 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4548 PACKET_qXfer_spu_write },
4549 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4550 PACKET_qXfer_osdata },
4551 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4552 PACKET_qXfer_threads },
4553 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4554 PACKET_qXfer_traceframe_info },
4555 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4556 PACKET_QPassSignals },
4557 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4558 PACKET_QCatchSyscalls },
4559 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4560 PACKET_QProgramSignals },
4561 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4562 PACKET_QStartNoAckMode },
4563 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4564 PACKET_multiprocess_feature },
4565 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4566 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4567 PACKET_qXfer_siginfo_read },
4568 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4569 PACKET_qXfer_siginfo_write },
4570 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4571 PACKET_ConditionalTracepoints },
4572 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4573 PACKET_ConditionalBreakpoints },
4574 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4575 PACKET_BreakpointCommands },
4576 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4577 PACKET_FastTracepoints },
4578 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4579 PACKET_StaticTracepoints },
4580 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4581 PACKET_InstallInTrace},
4582 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4583 PACKET_DisconnectedTracing_feature },
4584 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4585 PACKET_bc },
4586 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4587 PACKET_bs },
4588 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4589 PACKET_TracepointSource },
4590 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4591 PACKET_QAllow },
4592 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4593 PACKET_EnableDisableTracepoints_feature },
4594 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4595 PACKET_qXfer_fdpic },
4596 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4597 PACKET_qXfer_uib },
4598 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4599 PACKET_QDisableRandomization },
4600 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4601 { "QTBuffer:size", PACKET_DISABLE,
4602 remote_supported_packet, PACKET_QTBuffer_size},
4603 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4604 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4605 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4606 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4607 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4608 PACKET_qXfer_btrace },
4609 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4610 PACKET_qXfer_btrace_conf },
4611 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4612 PACKET_Qbtrace_conf_bts_size },
4613 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4614 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4615 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4616 PACKET_fork_event_feature },
4617 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4618 PACKET_vfork_event_feature },
4619 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4620 PACKET_exec_event_feature },
4621 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4622 PACKET_Qbtrace_conf_pt_size },
4623 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4624 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4625 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4626 };
4627
4628 static char *remote_support_xml;
4629
4630 /* Register string appended to "xmlRegisters=" in qSupported query. */
4631
4632 void
4633 register_remote_support_xml (const char *xml)
4634 {
4635 #if defined(HAVE_LIBEXPAT)
4636 if (remote_support_xml == NULL)
4637 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4638 else
4639 {
4640 char *copy = xstrdup (remote_support_xml + 13);
4641 char *p = strtok (copy, ",");
4642
4643 do
4644 {
4645 if (strcmp (p, xml) == 0)
4646 {
4647 /* already there */
4648 xfree (copy);
4649 return;
4650 }
4651 }
4652 while ((p = strtok (NULL, ",")) != NULL);
4653 xfree (copy);
4654
4655 remote_support_xml = reconcat (remote_support_xml,
4656 remote_support_xml, ",", xml,
4657 (char *) NULL);
4658 }
4659 #endif
4660 }
4661
4662 static char *
4663 remote_query_supported_append (char *msg, const char *append)
4664 {
4665 if (msg)
4666 return reconcat (msg, msg, ";", append, (char *) NULL);
4667 else
4668 return xstrdup (append);
4669 }
4670
4671 static void
4672 remote_query_supported (void)
4673 {
4674 struct remote_state *rs = get_remote_state ();
4675 char *next;
4676 int i;
4677 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4678
4679 /* The packet support flags are handled differently for this packet
4680 than for most others. We treat an error, a disabled packet, and
4681 an empty response identically: any features which must be reported
4682 to be used will be automatically disabled. An empty buffer
4683 accomplishes this, since that is also the representation for a list
4684 containing no features. */
4685
4686 rs->buf[0] = 0;
4687 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4688 {
4689 char *q = NULL;
4690 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4691
4692 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4693 q = remote_query_supported_append (q, "multiprocess+");
4694
4695 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4696 q = remote_query_supported_append (q, "swbreak+");
4697 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4698 q = remote_query_supported_append (q, "hwbreak+");
4699
4700 q = remote_query_supported_append (q, "qRelocInsn+");
4701
4702 if (packet_set_cmd_state (PACKET_fork_event_feature)
4703 != AUTO_BOOLEAN_FALSE)
4704 q = remote_query_supported_append (q, "fork-events+");
4705 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4706 != AUTO_BOOLEAN_FALSE)
4707 q = remote_query_supported_append (q, "vfork-events+");
4708 if (packet_set_cmd_state (PACKET_exec_event_feature)
4709 != AUTO_BOOLEAN_FALSE)
4710 q = remote_query_supported_append (q, "exec-events+");
4711
4712 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4713 q = remote_query_supported_append (q, "vContSupported+");
4714
4715 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4716 q = remote_query_supported_append (q, "QThreadEvents+");
4717
4718 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4719 q = remote_query_supported_append (q, "no-resumed+");
4720
4721 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4722 the qSupported:xmlRegisters=i386 handling. */
4723 if (remote_support_xml != NULL)
4724 q = remote_query_supported_append (q, remote_support_xml);
4725
4726 q = reconcat (q, "qSupported:", q, (char *) NULL);
4727 putpkt (q);
4728
4729 do_cleanups (old_chain);
4730
4731 getpkt (&rs->buf, &rs->buf_size, 0);
4732
4733 /* If an error occured, warn, but do not return - just reset the
4734 buffer to empty and go on to disable features. */
4735 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4736 == PACKET_ERROR)
4737 {
4738 warning (_("Remote failure reply: %s"), rs->buf);
4739 rs->buf[0] = 0;
4740 }
4741 }
4742
4743 memset (seen, 0, sizeof (seen));
4744
4745 next = rs->buf;
4746 while (*next)
4747 {
4748 enum packet_support is_supported;
4749 char *p, *end, *name_end, *value;
4750
4751 /* First separate out this item from the rest of the packet. If
4752 there's another item after this, we overwrite the separator
4753 (terminated strings are much easier to work with). */
4754 p = next;
4755 end = strchr (p, ';');
4756 if (end == NULL)
4757 {
4758 end = p + strlen (p);
4759 next = end;
4760 }
4761 else
4762 {
4763 *end = '\0';
4764 next = end + 1;
4765
4766 if (end == p)
4767 {
4768 warning (_("empty item in \"qSupported\" response"));
4769 continue;
4770 }
4771 }
4772
4773 name_end = strchr (p, '=');
4774 if (name_end)
4775 {
4776 /* This is a name=value entry. */
4777 is_supported = PACKET_ENABLE;
4778 value = name_end + 1;
4779 *name_end = '\0';
4780 }
4781 else
4782 {
4783 value = NULL;
4784 switch (end[-1])
4785 {
4786 case '+':
4787 is_supported = PACKET_ENABLE;
4788 break;
4789
4790 case '-':
4791 is_supported = PACKET_DISABLE;
4792 break;
4793
4794 case '?':
4795 is_supported = PACKET_SUPPORT_UNKNOWN;
4796 break;
4797
4798 default:
4799 warning (_("unrecognized item \"%s\" "
4800 "in \"qSupported\" response"), p);
4801 continue;
4802 }
4803 end[-1] = '\0';
4804 }
4805
4806 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4807 if (strcmp (remote_protocol_features[i].name, p) == 0)
4808 {
4809 const struct protocol_feature *feature;
4810
4811 seen[i] = 1;
4812 feature = &remote_protocol_features[i];
4813 feature->func (feature, is_supported, value);
4814 break;
4815 }
4816 }
4817
4818 /* If we increased the packet size, make sure to increase the global
4819 buffer size also. We delay this until after parsing the entire
4820 qSupported packet, because this is the same buffer we were
4821 parsing. */
4822 if (rs->buf_size < rs->explicit_packet_size)
4823 {
4824 rs->buf_size = rs->explicit_packet_size;
4825 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4826 }
4827
4828 /* Handle the defaults for unmentioned features. */
4829 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4830 if (!seen[i])
4831 {
4832 const struct protocol_feature *feature;
4833
4834 feature = &remote_protocol_features[i];
4835 feature->func (feature, feature->default_support, NULL);
4836 }
4837 }
4838
4839 /* Serial QUIT handler for the remote serial descriptor.
4840
4841 Defers handling a Ctrl-C until we're done with the current
4842 command/response packet sequence, unless:
4843
4844 - We're setting up the connection. Don't send a remote interrupt
4845 request, as we're not fully synced yet. Quit immediately
4846 instead.
4847
4848 - The target has been resumed in the foreground
4849 (target_terminal_is_ours is false) with a synchronous resume
4850 packet, and we're blocked waiting for the stop reply, thus a
4851 Ctrl-C should be immediately sent to the target.
4852
4853 - We get a second Ctrl-C while still within the same serial read or
4854 write. In that case the serial is seemingly wedged --- offer to
4855 quit/disconnect.
4856
4857 - We see a second Ctrl-C without target response, after having
4858 previously interrupted the target. In that case the target/stub
4859 is probably wedged --- offer to quit/disconnect.
4860 */
4861
4862 static void
4863 remote_serial_quit_handler (void)
4864 {
4865 struct remote_state *rs = get_remote_state ();
4866
4867 if (check_quit_flag ())
4868 {
4869 /* If we're starting up, we're not fully synced yet. Quit
4870 immediately. */
4871 if (rs->starting_up)
4872 quit ();
4873 else if (rs->got_ctrlc_during_io)
4874 {
4875 if (query (_("The target is not responding to GDB commands.\n"
4876 "Stop debugging it? ")))
4877 remote_unpush_and_throw ();
4878 }
4879 /* If ^C has already been sent once, offer to disconnect. */
4880 else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4881 interrupt_query ();
4882 /* All-stop protocol, and blocked waiting for stop reply. Send
4883 an interrupt request. */
4884 else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4885 target_interrupt (inferior_ptid);
4886 else
4887 rs->got_ctrlc_during_io = 1;
4888 }
4889 }
4890
4891 /* Remove any of the remote.c targets from target stack. Upper targets depend
4892 on it so remove them first. */
4893
4894 static void
4895 remote_unpush_target (void)
4896 {
4897 pop_all_targets_at_and_above (process_stratum);
4898 }
4899
4900 static void
4901 remote_unpush_and_throw (void)
4902 {
4903 remote_unpush_target ();
4904 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4905 }
4906
4907 static void
4908 remote_open_1 (const char *name, int from_tty,
4909 struct target_ops *target, int extended_p)
4910 {
4911 struct remote_state *rs = get_remote_state ();
4912
4913 if (name == 0)
4914 error (_("To open a remote debug connection, you need to specify what\n"
4915 "serial device is attached to the remote system\n"
4916 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4917
4918 /* See FIXME above. */
4919 if (!target_async_permitted)
4920 wait_forever_enabled_p = 1;
4921
4922 /* If we're connected to a running target, target_preopen will kill it.
4923 Ask this question first, before target_preopen has a chance to kill
4924 anything. */
4925 if (rs->remote_desc != NULL && !have_inferiors ())
4926 {
4927 if (from_tty
4928 && !query (_("Already connected to a remote target. Disconnect? ")))
4929 error (_("Still connected."));
4930 }
4931
4932 /* Here the possibly existing remote target gets unpushed. */
4933 target_preopen (from_tty);
4934
4935 /* Make sure we send the passed signals list the next time we resume. */
4936 xfree (rs->last_pass_packet);
4937 rs->last_pass_packet = NULL;
4938
4939 /* Make sure we send the program signals list the next time we
4940 resume. */
4941 xfree (rs->last_program_signals_packet);
4942 rs->last_program_signals_packet = NULL;
4943
4944 remote_fileio_reset ();
4945 reopen_exec_file ();
4946 reread_symbols ();
4947
4948 rs->remote_desc = remote_serial_open (name);
4949 if (!rs->remote_desc)
4950 perror_with_name (name);
4951
4952 if (baud_rate != -1)
4953 {
4954 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4955 {
4956 /* The requested speed could not be set. Error out to
4957 top level after closing remote_desc. Take care to
4958 set remote_desc to NULL to avoid closing remote_desc
4959 more than once. */
4960 serial_close (rs->remote_desc);
4961 rs->remote_desc = NULL;
4962 perror_with_name (name);
4963 }
4964 }
4965
4966 serial_setparity (rs->remote_desc, serial_parity);
4967 serial_raw (rs->remote_desc);
4968
4969 /* If there is something sitting in the buffer we might take it as a
4970 response to a command, which would be bad. */
4971 serial_flush_input (rs->remote_desc);
4972
4973 if (from_tty)
4974 {
4975 puts_filtered ("Remote debugging using ");
4976 puts_filtered (name);
4977 puts_filtered ("\n");
4978 }
4979 push_target (target); /* Switch to using remote target now. */
4980
4981 /* Register extra event sources in the event loop. */
4982 remote_async_inferior_event_token
4983 = create_async_event_handler (remote_async_inferior_event_handler,
4984 NULL);
4985 rs->notif_state = remote_notif_state_allocate ();
4986
4987 /* Reset the target state; these things will be queried either by
4988 remote_query_supported or as they are needed. */
4989 reset_all_packet_configs_support ();
4990 rs->cached_wait_status = 0;
4991 rs->explicit_packet_size = 0;
4992 rs->noack_mode = 0;
4993 rs->extended = extended_p;
4994 rs->waiting_for_stop_reply = 0;
4995 rs->ctrlc_pending_p = 0;
4996 rs->got_ctrlc_during_io = 0;
4997
4998 rs->general_thread = not_sent_ptid;
4999 rs->continue_thread = not_sent_ptid;
5000 rs->remote_traceframe_number = -1;
5001
5002 /* Probe for ability to use "ThreadInfo" query, as required. */
5003 rs->use_threadinfo_query = 1;
5004 rs->use_threadextra_query = 1;
5005
5006 readahead_cache_invalidate ();
5007
5008 /* Start out by owning the terminal. */
5009 remote_async_terminal_ours_p = 1;
5010
5011 if (target_async_permitted)
5012 {
5013 /* FIXME: cagney/1999-09-23: During the initial connection it is
5014 assumed that the target is already ready and able to respond to
5015 requests. Unfortunately remote_start_remote() eventually calls
5016 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5017 around this. Eventually a mechanism that allows
5018 wait_for_inferior() to expect/get timeouts will be
5019 implemented. */
5020 wait_forever_enabled_p = 0;
5021 }
5022
5023 /* First delete any symbols previously loaded from shared libraries. */
5024 no_shared_libraries (NULL, 0);
5025
5026 /* Start afresh. */
5027 init_thread_list ();
5028
5029 /* Start the remote connection. If error() or QUIT, discard this
5030 target (we'd otherwise be in an inconsistent state) and then
5031 propogate the error on up the exception chain. This ensures that
5032 the caller doesn't stumble along blindly assuming that the
5033 function succeeded. The CLI doesn't have this problem but other
5034 UI's, such as MI do.
5035
5036 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5037 this function should return an error indication letting the
5038 caller restore the previous state. Unfortunately the command
5039 ``target remote'' is directly wired to this function making that
5040 impossible. On a positive note, the CLI side of this problem has
5041 been fixed - the function set_cmd_context() makes it possible for
5042 all the ``target ....'' commands to share a common callback
5043 function. See cli-dump.c. */
5044 {
5045
5046 TRY
5047 {
5048 remote_start_remote (from_tty, target, extended_p);
5049 }
5050 CATCH (ex, RETURN_MASK_ALL)
5051 {
5052 /* Pop the partially set up target - unless something else did
5053 already before throwing the exception. */
5054 if (rs->remote_desc != NULL)
5055 remote_unpush_target ();
5056 if (target_async_permitted)
5057 wait_forever_enabled_p = 1;
5058 throw_exception (ex);
5059 }
5060 END_CATCH
5061 }
5062
5063 remote_btrace_reset ();
5064
5065 if (target_async_permitted)
5066 wait_forever_enabled_p = 1;
5067 }
5068
5069 /* Detach the specified process. */
5070
5071 static void
5072 remote_detach_pid (int pid)
5073 {
5074 struct remote_state *rs = get_remote_state ();
5075
5076 if (remote_multi_process_p (rs))
5077 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5078 else
5079 strcpy (rs->buf, "D");
5080
5081 putpkt (rs->buf);
5082 getpkt (&rs->buf, &rs->buf_size, 0);
5083
5084 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5085 ;
5086 else if (rs->buf[0] == '\0')
5087 error (_("Remote doesn't know how to detach"));
5088 else
5089 error (_("Can't detach process."));
5090 }
5091
5092 /* This detaches a program to which we previously attached, using
5093 inferior_ptid to identify the process. After this is done, GDB
5094 can be used to debug some other program. We better not have left
5095 any breakpoints in the target program or it'll die when it hits
5096 one. */
5097
5098 static void
5099 remote_detach_1 (const char *args, int from_tty)
5100 {
5101 int pid = ptid_get_pid (inferior_ptid);
5102 struct remote_state *rs = get_remote_state ();
5103 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5104 int is_fork_parent;
5105
5106 if (args)
5107 error (_("Argument given to \"detach\" when remotely debugging."));
5108
5109 if (!target_has_execution)
5110 error (_("No process to detach from."));
5111
5112 if (from_tty)
5113 {
5114 char *exec_file = get_exec_file (0);
5115 if (exec_file == NULL)
5116 exec_file = "";
5117 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5118 target_pid_to_str (pid_to_ptid (pid)));
5119 gdb_flush (gdb_stdout);
5120 }
5121
5122 /* Tell the remote target to detach. */
5123 remote_detach_pid (pid);
5124
5125 /* Exit only if this is the only active inferior. */
5126 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5127 puts_filtered (_("Ending remote debugging.\n"));
5128
5129 /* Check to see if we are detaching a fork parent. Note that if we
5130 are detaching a fork child, tp == NULL. */
5131 is_fork_parent = (tp != NULL
5132 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5133
5134 /* If doing detach-on-fork, we don't mourn, because that will delete
5135 breakpoints that should be available for the followed inferior. */
5136 if (!is_fork_parent)
5137 target_mourn_inferior ();
5138 else
5139 {
5140 inferior_ptid = null_ptid;
5141 detach_inferior (pid);
5142 }
5143 }
5144
5145 static void
5146 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5147 {
5148 remote_detach_1 (args, from_tty);
5149 }
5150
5151 static void
5152 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5153 {
5154 remote_detach_1 (args, from_tty);
5155 }
5156
5157 /* Target follow-fork function for remote targets. On entry, and
5158 at return, the current inferior is the fork parent.
5159
5160 Note that although this is currently only used for extended-remote,
5161 it is named remote_follow_fork in anticipation of using it for the
5162 remote target as well. */
5163
5164 static int
5165 remote_follow_fork (struct target_ops *ops, int follow_child,
5166 int detach_fork)
5167 {
5168 struct remote_state *rs = get_remote_state ();
5169 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5170
5171 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5172 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5173 {
5174 /* When following the parent and detaching the child, we detach
5175 the child here. For the case of following the child and
5176 detaching the parent, the detach is done in the target-
5177 independent follow fork code in infrun.c. We can't use
5178 target_detach when detaching an unfollowed child because
5179 the client side doesn't know anything about the child. */
5180 if (detach_fork && !follow_child)
5181 {
5182 /* Detach the fork child. */
5183 ptid_t child_ptid;
5184 pid_t child_pid;
5185
5186 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5187 child_pid = ptid_get_pid (child_ptid);
5188
5189 remote_detach_pid (child_pid);
5190 detach_inferior (child_pid);
5191 }
5192 }
5193 return 0;
5194 }
5195
5196 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5197 in the program space of the new inferior. On entry and at return the
5198 current inferior is the exec'ing inferior. INF is the new exec'd
5199 inferior, which may be the same as the exec'ing inferior unless
5200 follow-exec-mode is "new". */
5201
5202 static void
5203 remote_follow_exec (struct target_ops *ops,
5204 struct inferior *inf, char *execd_pathname)
5205 {
5206 /* We know that this is a target file name, so if it has the "target:"
5207 prefix we strip it off before saving it in the program space. */
5208 if (is_target_filename (execd_pathname))
5209 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5210
5211 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5212 }
5213
5214 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5215
5216 static void
5217 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5218 {
5219 if (args)
5220 error (_("Argument given to \"disconnect\" when remotely debugging."));
5221
5222 /* Make sure we unpush even the extended remote targets. Calling
5223 target_mourn_inferior won't unpush, and remote_mourn won't
5224 unpush if there is more than one inferior left. */
5225 unpush_target (target);
5226 generic_mourn_inferior ();
5227
5228 if (from_tty)
5229 puts_filtered ("Ending remote debugging.\n");
5230 }
5231
5232 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5233 be chatty about it. */
5234
5235 static void
5236 extended_remote_attach (struct target_ops *target, const char *args,
5237 int from_tty)
5238 {
5239 struct remote_state *rs = get_remote_state ();
5240 int pid;
5241 char *wait_status = NULL;
5242
5243 pid = parse_pid_to_attach (args);
5244
5245 /* Remote PID can be freely equal to getpid, do not check it here the same
5246 way as in other targets. */
5247
5248 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5249 error (_("This target does not support attaching to a process"));
5250
5251 if (from_tty)
5252 {
5253 char *exec_file = get_exec_file (0);
5254
5255 if (exec_file)
5256 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5257 target_pid_to_str (pid_to_ptid (pid)));
5258 else
5259 printf_unfiltered (_("Attaching to %s\n"),
5260 target_pid_to_str (pid_to_ptid (pid)));
5261
5262 gdb_flush (gdb_stdout);
5263 }
5264
5265 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5266 putpkt (rs->buf);
5267 getpkt (&rs->buf, &rs->buf_size, 0);
5268
5269 switch (packet_ok (rs->buf,
5270 &remote_protocol_packets[PACKET_vAttach]))
5271 {
5272 case PACKET_OK:
5273 if (!target_is_non_stop_p ())
5274 {
5275 /* Save the reply for later. */
5276 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5277 strcpy (wait_status, rs->buf);
5278 }
5279 else if (strcmp (rs->buf, "OK") != 0)
5280 error (_("Attaching to %s failed with: %s"),
5281 target_pid_to_str (pid_to_ptid (pid)),
5282 rs->buf);
5283 break;
5284 case PACKET_UNKNOWN:
5285 error (_("This target does not support attaching to a process"));
5286 default:
5287 error (_("Attaching to %s failed"),
5288 target_pid_to_str (pid_to_ptid (pid)));
5289 }
5290
5291 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5292
5293 inferior_ptid = pid_to_ptid (pid);
5294
5295 if (target_is_non_stop_p ())
5296 {
5297 struct thread_info *thread;
5298
5299 /* Get list of threads. */
5300 remote_update_thread_list (target);
5301
5302 thread = first_thread_of_process (pid);
5303 if (thread)
5304 inferior_ptid = thread->ptid;
5305 else
5306 inferior_ptid = pid_to_ptid (pid);
5307
5308 /* Invalidate our notion of the remote current thread. */
5309 record_currthread (rs, minus_one_ptid);
5310 }
5311 else
5312 {
5313 /* Now, if we have thread information, update inferior_ptid. */
5314 inferior_ptid = remote_current_thread (inferior_ptid);
5315
5316 /* Add the main thread to the thread list. */
5317 add_thread_silent (inferior_ptid);
5318 }
5319
5320 /* Next, if the target can specify a description, read it. We do
5321 this before anything involving memory or registers. */
5322 target_find_description ();
5323
5324 if (!target_is_non_stop_p ())
5325 {
5326 /* Use the previously fetched status. */
5327 gdb_assert (wait_status != NULL);
5328
5329 if (target_can_async_p ())
5330 {
5331 struct notif_event *reply
5332 = remote_notif_parse (&notif_client_stop, wait_status);
5333
5334 push_stop_reply ((struct stop_reply *) reply);
5335
5336 target_async (1);
5337 }
5338 else
5339 {
5340 gdb_assert (wait_status != NULL);
5341 strcpy (rs->buf, wait_status);
5342 rs->cached_wait_status = 1;
5343 }
5344 }
5345 else
5346 gdb_assert (wait_status == NULL);
5347 }
5348
5349 /* Implementation of the to_post_attach method. */
5350
5351 static void
5352 extended_remote_post_attach (struct target_ops *ops, int pid)
5353 {
5354 /* Get text, data & bss offsets. */
5355 get_offsets ();
5356
5357 /* In certain cases GDB might not have had the chance to start
5358 symbol lookup up until now. This could happen if the debugged
5359 binary is not using shared libraries, the vsyscall page is not
5360 present (on Linux) and the binary itself hadn't changed since the
5361 debugging process was started. */
5362 if (symfile_objfile != NULL)
5363 remote_check_symbols();
5364 }
5365
5366 \f
5367 /* Check for the availability of vCont. This function should also check
5368 the response. */
5369
5370 static void
5371 remote_vcont_probe (struct remote_state *rs)
5372 {
5373 char *buf;
5374
5375 strcpy (rs->buf, "vCont?");
5376 putpkt (rs->buf);
5377 getpkt (&rs->buf, &rs->buf_size, 0);
5378 buf = rs->buf;
5379
5380 /* Make sure that the features we assume are supported. */
5381 if (startswith (buf, "vCont"))
5382 {
5383 char *p = &buf[5];
5384 int support_c, support_C;
5385
5386 rs->supports_vCont.s = 0;
5387 rs->supports_vCont.S = 0;
5388 support_c = 0;
5389 support_C = 0;
5390 rs->supports_vCont.t = 0;
5391 rs->supports_vCont.r = 0;
5392 while (p && *p == ';')
5393 {
5394 p++;
5395 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5396 rs->supports_vCont.s = 1;
5397 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5398 rs->supports_vCont.S = 1;
5399 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5400 support_c = 1;
5401 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5402 support_C = 1;
5403 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5404 rs->supports_vCont.t = 1;
5405 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5406 rs->supports_vCont.r = 1;
5407
5408 p = strchr (p, ';');
5409 }
5410
5411 /* If c, and C are not all supported, we can't use vCont. Clearing
5412 BUF will make packet_ok disable the packet. */
5413 if (!support_c || !support_C)
5414 buf[0] = 0;
5415 }
5416
5417 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5418 }
5419
5420 /* Helper function for building "vCont" resumptions. Write a
5421 resumption to P. ENDP points to one-passed-the-end of the buffer
5422 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5423 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5424 resumed thread should be single-stepped and/or signalled. If PTID
5425 equals minus_one_ptid, then all threads are resumed; if PTID
5426 represents a process, then all threads of the process are resumed;
5427 the thread to be stepped and/or signalled is given in the global
5428 INFERIOR_PTID. */
5429
5430 static char *
5431 append_resumption (char *p, char *endp,
5432 ptid_t ptid, int step, enum gdb_signal siggnal)
5433 {
5434 struct remote_state *rs = get_remote_state ();
5435
5436 if (step && siggnal != GDB_SIGNAL_0)
5437 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5438 else if (step
5439 /* GDB is willing to range step. */
5440 && use_range_stepping
5441 /* Target supports range stepping. */
5442 && rs->supports_vCont.r
5443 /* We don't currently support range stepping multiple
5444 threads with a wildcard (though the protocol allows it,
5445 so stubs shouldn't make an active effort to forbid
5446 it). */
5447 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5448 {
5449 struct thread_info *tp;
5450
5451 if (ptid_equal (ptid, minus_one_ptid))
5452 {
5453 /* If we don't know about the target thread's tid, then
5454 we're resuming magic_null_ptid (see caller). */
5455 tp = find_thread_ptid (magic_null_ptid);
5456 }
5457 else
5458 tp = find_thread_ptid (ptid);
5459 gdb_assert (tp != NULL);
5460
5461 if (tp->control.may_range_step)
5462 {
5463 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5464
5465 p += xsnprintf (p, endp - p, ";r%s,%s",
5466 phex_nz (tp->control.step_range_start,
5467 addr_size),
5468 phex_nz (tp->control.step_range_end,
5469 addr_size));
5470 }
5471 else
5472 p += xsnprintf (p, endp - p, ";s");
5473 }
5474 else if (step)
5475 p += xsnprintf (p, endp - p, ";s");
5476 else if (siggnal != GDB_SIGNAL_0)
5477 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5478 else
5479 p += xsnprintf (p, endp - p, ";c");
5480
5481 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5482 {
5483 ptid_t nptid;
5484
5485 /* All (-1) threads of process. */
5486 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5487
5488 p += xsnprintf (p, endp - p, ":");
5489 p = write_ptid (p, endp, nptid);
5490 }
5491 else if (!ptid_equal (ptid, minus_one_ptid))
5492 {
5493 p += xsnprintf (p, endp - p, ":");
5494 p = write_ptid (p, endp, ptid);
5495 }
5496
5497 return p;
5498 }
5499
5500 /* Clear the thread's private info on resume. */
5501
5502 static void
5503 resume_clear_thread_private_info (struct thread_info *thread)
5504 {
5505 if (thread->priv != NULL)
5506 {
5507 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5508 thread->priv->watch_data_address = 0;
5509 }
5510 }
5511
5512 /* Append a vCont continue-with-signal action for threads that have a
5513 non-zero stop signal. */
5514
5515 static char *
5516 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5517 {
5518 struct thread_info *thread;
5519
5520 ALL_NON_EXITED_THREADS (thread)
5521 if (ptid_match (thread->ptid, ptid)
5522 && !ptid_equal (inferior_ptid, thread->ptid)
5523 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5524 {
5525 p = append_resumption (p, endp, thread->ptid,
5526 0, thread->suspend.stop_signal);
5527 thread->suspend.stop_signal = GDB_SIGNAL_0;
5528 resume_clear_thread_private_info (thread);
5529 }
5530
5531 return p;
5532 }
5533
5534 /* Resume the remote inferior by using a "vCont" packet. The thread
5535 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5536 resumed thread should be single-stepped and/or signalled. If PTID
5537 equals minus_one_ptid, then all threads are resumed; the thread to
5538 be stepped and/or signalled is given in the global INFERIOR_PTID.
5539 This function returns non-zero iff it resumes the inferior.
5540
5541 This function issues a strict subset of all possible vCont commands at the
5542 moment. */
5543
5544 static int
5545 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5546 {
5547 struct remote_state *rs = get_remote_state ();
5548 char *p;
5549 char *endp;
5550
5551 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5552 remote_vcont_probe (rs);
5553
5554 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5555 return 0;
5556
5557 p = rs->buf;
5558 endp = rs->buf + get_remote_packet_size ();
5559
5560 /* If we could generate a wider range of packets, we'd have to worry
5561 about overflowing BUF. Should there be a generic
5562 "multi-part-packet" packet? */
5563
5564 p += xsnprintf (p, endp - p, "vCont");
5565
5566 if (ptid_equal (ptid, magic_null_ptid))
5567 {
5568 /* MAGIC_NULL_PTID means that we don't have any active threads,
5569 so we don't have any TID numbers the inferior will
5570 understand. Make sure to only send forms that do not specify
5571 a TID. */
5572 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5573 }
5574 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5575 {
5576 /* Resume all threads (of all processes, or of a single
5577 process), with preference for INFERIOR_PTID. This assumes
5578 inferior_ptid belongs to the set of all threads we are about
5579 to resume. */
5580 if (step || siggnal != GDB_SIGNAL_0)
5581 {
5582 /* Step inferior_ptid, with or without signal. */
5583 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5584 }
5585
5586 /* Also pass down any pending signaled resumption for other
5587 threads not the current. */
5588 p = append_pending_thread_resumptions (p, endp, ptid);
5589
5590 /* And continue others without a signal. */
5591 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5592 }
5593 else
5594 {
5595 /* Scheduler locking; resume only PTID. */
5596 append_resumption (p, endp, ptid, step, siggnal);
5597 }
5598
5599 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5600 putpkt (rs->buf);
5601
5602 if (target_is_non_stop_p ())
5603 {
5604 /* In non-stop, the stub replies to vCont with "OK". The stop
5605 reply will be reported asynchronously by means of a `%Stop'
5606 notification. */
5607 getpkt (&rs->buf, &rs->buf_size, 0);
5608 if (strcmp (rs->buf, "OK") != 0)
5609 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5610 }
5611
5612 return 1;
5613 }
5614
5615 /* Tell the remote machine to resume. */
5616
5617 static void
5618 remote_resume (struct target_ops *ops,
5619 ptid_t ptid, int step, enum gdb_signal siggnal)
5620 {
5621 struct remote_state *rs = get_remote_state ();
5622 char *buf;
5623 struct thread_info *thread;
5624
5625 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5626 (explained in remote-notif.c:handle_notification) so
5627 remote_notif_process is not called. We need find a place where
5628 it is safe to start a 'vNotif' sequence. It is good to do it
5629 before resuming inferior, because inferior was stopped and no RSP
5630 traffic at that moment. */
5631 if (!target_is_non_stop_p ())
5632 remote_notif_process (rs->notif_state, &notif_client_stop);
5633
5634 rs->last_sent_signal = siggnal;
5635 rs->last_sent_step = step;
5636
5637 /* The vCont packet doesn't need to specify threads via Hc. */
5638 /* No reverse support (yet) for vCont. */
5639 if (execution_direction != EXEC_REVERSE)
5640 if (remote_vcont_resume (ptid, step, siggnal))
5641 goto done;
5642
5643 /* All other supported resume packets do use Hc, so set the continue
5644 thread. */
5645 if (ptid_equal (ptid, minus_one_ptid))
5646 set_continue_thread (any_thread_ptid);
5647 else
5648 set_continue_thread (ptid);
5649
5650 ALL_NON_EXITED_THREADS (thread)
5651 resume_clear_thread_private_info (thread);
5652
5653 buf = rs->buf;
5654 if (execution_direction == EXEC_REVERSE)
5655 {
5656 /* We don't pass signals to the target in reverse exec mode. */
5657 if (info_verbose && siggnal != GDB_SIGNAL_0)
5658 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5659 siggnal);
5660
5661 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5662 error (_("Remote reverse-step not supported."));
5663 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5664 error (_("Remote reverse-continue not supported."));
5665
5666 strcpy (buf, step ? "bs" : "bc");
5667 }
5668 else if (siggnal != GDB_SIGNAL_0)
5669 {
5670 buf[0] = step ? 'S' : 'C';
5671 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5672 buf[2] = tohex (((int) siggnal) & 0xf);
5673 buf[3] = '\0';
5674 }
5675 else
5676 strcpy (buf, step ? "s" : "c");
5677
5678 putpkt (buf);
5679
5680 done:
5681 /* We are about to start executing the inferior, let's register it
5682 with the event loop. NOTE: this is the one place where all the
5683 execution commands end up. We could alternatively do this in each
5684 of the execution commands in infcmd.c. */
5685 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5686 into infcmd.c in order to allow inferior function calls to work
5687 NOT asynchronously. */
5688 if (target_can_async_p ())
5689 target_async (1);
5690
5691 /* We've just told the target to resume. The remote server will
5692 wait for the inferior to stop, and then send a stop reply. In
5693 the mean time, we can't start another command/query ourselves
5694 because the stub wouldn't be ready to process it. This applies
5695 only to the base all-stop protocol, however. In non-stop (which
5696 only supports vCont), the stub replies with an "OK", and is
5697 immediate able to process further serial input. */
5698 if (!target_is_non_stop_p ())
5699 rs->waiting_for_stop_reply = 1;
5700 }
5701 \f
5702
5703 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5704 thread, all threads of a remote process, or all threads of all
5705 processes. */
5706
5707 static void
5708 remote_stop_ns (ptid_t ptid)
5709 {
5710 struct remote_state *rs = get_remote_state ();
5711 char *p = rs->buf;
5712 char *endp = rs->buf + get_remote_packet_size ();
5713
5714 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5715 remote_vcont_probe (rs);
5716
5717 if (!rs->supports_vCont.t)
5718 error (_("Remote server does not support stopping threads"));
5719
5720 if (ptid_equal (ptid, minus_one_ptid)
5721 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5722 p += xsnprintf (p, endp - p, "vCont;t");
5723 else
5724 {
5725 ptid_t nptid;
5726
5727 p += xsnprintf (p, endp - p, "vCont;t:");
5728
5729 if (ptid_is_pid (ptid))
5730 /* All (-1) threads of process. */
5731 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5732 else
5733 {
5734 /* Small optimization: if we already have a stop reply for
5735 this thread, no use in telling the stub we want this
5736 stopped. */
5737 if (peek_stop_reply (ptid))
5738 return;
5739
5740 nptid = ptid;
5741 }
5742
5743 write_ptid (p, endp, nptid);
5744 }
5745
5746 /* In non-stop, we get an immediate OK reply. The stop reply will
5747 come in asynchronously by notification. */
5748 putpkt (rs->buf);
5749 getpkt (&rs->buf, &rs->buf_size, 0);
5750 if (strcmp (rs->buf, "OK") != 0)
5751 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5752 }
5753
5754 /* All-stop version of target_interrupt. Sends a break or a ^C to
5755 interrupt the remote target. It is undefined which thread of which
5756 process reports the interrupt. */
5757
5758 static void
5759 remote_interrupt_as (void)
5760 {
5761 struct remote_state *rs = get_remote_state ();
5762
5763 rs->ctrlc_pending_p = 1;
5764
5765 /* If the inferior is stopped already, but the core didn't know
5766 about it yet, just ignore the request. The cached wait status
5767 will be collected in remote_wait. */
5768 if (rs->cached_wait_status)
5769 return;
5770
5771 /* Send interrupt_sequence to remote target. */
5772 send_interrupt_sequence ();
5773 }
5774
5775 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5776 the remote target. It is undefined which thread of which process
5777 reports the interrupt. Throws an error if the packet is not
5778 supported by the server. */
5779
5780 static void
5781 remote_interrupt_ns (void)
5782 {
5783 struct remote_state *rs = get_remote_state ();
5784 char *p = rs->buf;
5785 char *endp = rs->buf + get_remote_packet_size ();
5786
5787 xsnprintf (p, endp - p, "vCtrlC");
5788
5789 /* In non-stop, we get an immediate OK reply. The stop reply will
5790 come in asynchronously by notification. */
5791 putpkt (rs->buf);
5792 getpkt (&rs->buf, &rs->buf_size, 0);
5793
5794 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5795 {
5796 case PACKET_OK:
5797 break;
5798 case PACKET_UNKNOWN:
5799 error (_("No support for interrupting the remote target."));
5800 case PACKET_ERROR:
5801 error (_("Interrupting target failed: %s"), rs->buf);
5802 }
5803 }
5804
5805 /* Implement the to_stop function for the remote targets. */
5806
5807 static void
5808 remote_stop (struct target_ops *self, ptid_t ptid)
5809 {
5810 if (remote_debug)
5811 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5812
5813 if (target_is_non_stop_p ())
5814 remote_stop_ns (ptid);
5815 else
5816 {
5817 /* We don't currently have a way to transparently pause the
5818 remote target in all-stop mode. Interrupt it instead. */
5819 remote_interrupt_as ();
5820 }
5821 }
5822
5823 /* Implement the to_interrupt function for the remote targets. */
5824
5825 static void
5826 remote_interrupt (struct target_ops *self, ptid_t ptid)
5827 {
5828 struct remote_state *rs = get_remote_state ();
5829
5830 if (remote_debug)
5831 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5832
5833 if (target_is_non_stop_p ())
5834 remote_interrupt_ns ();
5835 else
5836 remote_interrupt_as ();
5837 }
5838
5839 /* Implement the to_pass_ctrlc function for the remote targets. */
5840
5841 static void
5842 remote_pass_ctrlc (struct target_ops *self)
5843 {
5844 struct remote_state *rs = get_remote_state ();
5845
5846 if (remote_debug)
5847 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
5848
5849 /* If we're starting up, we're not fully synced yet. Quit
5850 immediately. */
5851 if (rs->starting_up)
5852 quit ();
5853 /* If ^C has already been sent once, offer to disconnect. */
5854 else if (rs->ctrlc_pending_p)
5855 interrupt_query ();
5856 else
5857 target_interrupt (inferior_ptid);
5858 }
5859
5860 /* Ask the user what to do when an interrupt is received. */
5861
5862 static void
5863 interrupt_query (void)
5864 {
5865 struct remote_state *rs = get_remote_state ();
5866
5867 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5868 {
5869 if (query (_("The target is not responding to interrupt requests.\n"
5870 "Stop debugging it? ")))
5871 {
5872 remote_unpush_target ();
5873 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5874 }
5875 }
5876 else
5877 {
5878 if (query (_("Interrupted while waiting for the program.\n"
5879 "Give up waiting? ")))
5880 quit ();
5881 }
5882 }
5883
5884 /* Enable/disable target terminal ownership. Most targets can use
5885 terminal groups to control terminal ownership. Remote targets are
5886 different in that explicit transfer of ownership to/from GDB/target
5887 is required. */
5888
5889 static void
5890 remote_terminal_inferior (struct target_ops *self)
5891 {
5892 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5893 idempotent. The event-loop GDB talking to an asynchronous target
5894 with a synchronous command calls this function from both
5895 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5896 transfer the terminal to the target when it shouldn't this guard
5897 can go away. */
5898 if (!remote_async_terminal_ours_p)
5899 return;
5900 delete_file_handler (input_fd);
5901 remote_async_terminal_ours_p = 0;
5902 /* NOTE: At this point we could also register our selves as the
5903 recipient of all input. Any characters typed could then be
5904 passed on down to the target. */
5905 }
5906
5907 static void
5908 remote_terminal_ours (struct target_ops *self)
5909 {
5910 /* See FIXME in remote_terminal_inferior. */
5911 if (remote_async_terminal_ours_p)
5912 return;
5913 add_file_handler (input_fd, stdin_event_handler, 0);
5914 remote_async_terminal_ours_p = 1;
5915 }
5916
5917 static void
5918 remote_console_output (char *msg)
5919 {
5920 char *p;
5921
5922 for (p = msg; p[0] && p[1]; p += 2)
5923 {
5924 char tb[2];
5925 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5926
5927 tb[0] = c;
5928 tb[1] = 0;
5929 fputs_unfiltered (tb, gdb_stdtarg);
5930 }
5931 gdb_flush (gdb_stdtarg);
5932 }
5933
5934 typedef struct cached_reg
5935 {
5936 int num;
5937 gdb_byte data[MAX_REGISTER_SIZE];
5938 } cached_reg_t;
5939
5940 DEF_VEC_O(cached_reg_t);
5941
5942 typedef struct stop_reply
5943 {
5944 struct notif_event base;
5945
5946 /* The identifier of the thread about this event */
5947 ptid_t ptid;
5948
5949 /* The remote state this event is associated with. When the remote
5950 connection, represented by a remote_state object, is closed,
5951 all the associated stop_reply events should be released. */
5952 struct remote_state *rs;
5953
5954 struct target_waitstatus ws;
5955
5956 /* Expedited registers. This makes remote debugging a bit more
5957 efficient for those targets that provide critical registers as
5958 part of their normal status mechanism (as another roundtrip to
5959 fetch them is avoided). */
5960 VEC(cached_reg_t) *regcache;
5961
5962 enum target_stop_reason stop_reason;
5963
5964 CORE_ADDR watch_data_address;
5965
5966 int core;
5967 } *stop_reply_p;
5968
5969 DECLARE_QUEUE_P (stop_reply_p);
5970 DEFINE_QUEUE_P (stop_reply_p);
5971 /* The list of already fetched and acknowledged stop events. This
5972 queue is used for notification Stop, and other notifications
5973 don't need queue for their events, because the notification events
5974 of Stop can't be consumed immediately, so that events should be
5975 queued first, and be consumed by remote_wait_{ns,as} one per
5976 time. Other notifications can consume their events immediately,
5977 so queue is not needed for them. */
5978 static QUEUE (stop_reply_p) *stop_reply_queue;
5979
5980 static void
5981 stop_reply_xfree (struct stop_reply *r)
5982 {
5983 notif_event_xfree ((struct notif_event *) r);
5984 }
5985
5986 /* Return the length of the stop reply queue. */
5987
5988 static int
5989 stop_reply_queue_length (void)
5990 {
5991 return QUEUE_length (stop_reply_p, stop_reply_queue);
5992 }
5993
5994 static void
5995 remote_notif_stop_parse (struct notif_client *self, char *buf,
5996 struct notif_event *event)
5997 {
5998 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5999 }
6000
6001 static void
6002 remote_notif_stop_ack (struct notif_client *self, char *buf,
6003 struct notif_event *event)
6004 {
6005 struct stop_reply *stop_reply = (struct stop_reply *) event;
6006
6007 /* acknowledge */
6008 putpkt ((char *) self->ack_command);
6009
6010 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6011 /* We got an unknown stop reply. */
6012 error (_("Unknown stop reply"));
6013
6014 push_stop_reply (stop_reply);
6015 }
6016
6017 static int
6018 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6019 {
6020 /* We can't get pending events in remote_notif_process for
6021 notification stop, and we have to do this in remote_wait_ns
6022 instead. If we fetch all queued events from stub, remote stub
6023 may exit and we have no chance to process them back in
6024 remote_wait_ns. */
6025 mark_async_event_handler (remote_async_inferior_event_token);
6026 return 0;
6027 }
6028
6029 static void
6030 stop_reply_dtr (struct notif_event *event)
6031 {
6032 struct stop_reply *r = (struct stop_reply *) event;
6033
6034 VEC_free (cached_reg_t, r->regcache);
6035 }
6036
6037 static struct notif_event *
6038 remote_notif_stop_alloc_reply (void)
6039 {
6040 /* We cast to a pointer to the "base class". */
6041 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6042
6043 r->dtr = stop_reply_dtr;
6044
6045 return r;
6046 }
6047
6048 /* A client of notification Stop. */
6049
6050 struct notif_client notif_client_stop =
6051 {
6052 "Stop",
6053 "vStopped",
6054 remote_notif_stop_parse,
6055 remote_notif_stop_ack,
6056 remote_notif_stop_can_get_pending_events,
6057 remote_notif_stop_alloc_reply,
6058 REMOTE_NOTIF_STOP,
6059 };
6060
6061 /* A parameter to pass data in and out. */
6062
6063 struct queue_iter_param
6064 {
6065 void *input;
6066 struct stop_reply *output;
6067 };
6068
6069 /* Determine if THREAD is a pending fork parent thread. ARG contains
6070 the pid of the process that owns the threads we want to check, or
6071 -1 if we want to check all threads. */
6072
6073 static int
6074 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6075 ptid_t thread_ptid)
6076 {
6077 if (ws->kind == TARGET_WAITKIND_FORKED
6078 || ws->kind == TARGET_WAITKIND_VFORKED)
6079 {
6080 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6081 return 1;
6082 }
6083
6084 return 0;
6085 }
6086
6087 /* Check whether EVENT is a fork event, and if it is, remove the
6088 fork child from the context list passed in DATA. */
6089
6090 static int
6091 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6092 QUEUE_ITER (stop_reply_p) *iter,
6093 stop_reply_p event,
6094 void *data)
6095 {
6096 struct queue_iter_param *param = (struct queue_iter_param *) data;
6097 struct threads_listing_context *context
6098 = (struct threads_listing_context *) param->input;
6099
6100 if (event->ws.kind == TARGET_WAITKIND_FORKED
6101 || event->ws.kind == TARGET_WAITKIND_VFORKED
6102 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6103 threads_listing_context_remove (&event->ws, context);
6104
6105 return 1;
6106 }
6107
6108 /* If CONTEXT contains any fork child threads that have not been
6109 reported yet, remove them from the CONTEXT list. If such a
6110 thread exists it is because we are stopped at a fork catchpoint
6111 and have not yet called follow_fork, which will set up the
6112 host-side data structures for the new process. */
6113
6114 static void
6115 remove_new_fork_children (struct threads_listing_context *context)
6116 {
6117 struct thread_info * thread;
6118 int pid = -1;
6119 struct notif_client *notif = &notif_client_stop;
6120 struct queue_iter_param param;
6121
6122 /* For any threads stopped at a fork event, remove the corresponding
6123 fork child threads from the CONTEXT list. */
6124 ALL_NON_EXITED_THREADS (thread)
6125 {
6126 struct target_waitstatus *ws;
6127
6128 if (thread->suspend.waitstatus_pending_p)
6129 ws = &thread->suspend.waitstatus;
6130 else
6131 ws = &thread->pending_follow;
6132
6133 if (is_pending_fork_parent (ws, pid, thread->ptid))
6134 {
6135 threads_listing_context_remove (ws, context);
6136 }
6137 }
6138
6139 /* Check for any pending fork events (not reported or processed yet)
6140 in process PID and remove those fork child threads from the
6141 CONTEXT list as well. */
6142 remote_notif_get_pending_events (notif);
6143 param.input = context;
6144 param.output = NULL;
6145 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6146 remove_child_of_pending_fork, &param);
6147 }
6148
6149 /* Remove stop replies in the queue if its pid is equal to the given
6150 inferior's pid. */
6151
6152 static int
6153 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6154 QUEUE_ITER (stop_reply_p) *iter,
6155 stop_reply_p event,
6156 void *data)
6157 {
6158 struct queue_iter_param *param = (struct queue_iter_param *) data;
6159 struct inferior *inf = (struct inferior *) param->input;
6160
6161 if (ptid_get_pid (event->ptid) == inf->pid)
6162 {
6163 stop_reply_xfree (event);
6164 QUEUE_remove_elem (stop_reply_p, q, iter);
6165 }
6166
6167 return 1;
6168 }
6169
6170 /* Discard all pending stop replies of inferior INF. */
6171
6172 static void
6173 discard_pending_stop_replies (struct inferior *inf)
6174 {
6175 struct queue_iter_param param;
6176 struct stop_reply *reply;
6177 struct remote_state *rs = get_remote_state ();
6178 struct remote_notif_state *rns = rs->notif_state;
6179
6180 /* This function can be notified when an inferior exists. When the
6181 target is not remote, the notification state is NULL. */
6182 if (rs->remote_desc == NULL)
6183 return;
6184
6185 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6186
6187 /* Discard the in-flight notification. */
6188 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6189 {
6190 stop_reply_xfree (reply);
6191 rns->pending_event[notif_client_stop.id] = NULL;
6192 }
6193
6194 param.input = inf;
6195 param.output = NULL;
6196 /* Discard the stop replies we have already pulled with
6197 vStopped. */
6198 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6199 remove_stop_reply_for_inferior, &param);
6200 }
6201
6202 /* If its remote state is equal to the given remote state,
6203 remove EVENT from the stop reply queue. */
6204
6205 static int
6206 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6207 QUEUE_ITER (stop_reply_p) *iter,
6208 stop_reply_p event,
6209 void *data)
6210 {
6211 struct queue_iter_param *param = (struct queue_iter_param *) data;
6212 struct remote_state *rs = (struct remote_state *) param->input;
6213
6214 if (event->rs == rs)
6215 {
6216 stop_reply_xfree (event);
6217 QUEUE_remove_elem (stop_reply_p, q, iter);
6218 }
6219
6220 return 1;
6221 }
6222
6223 /* Discard the stop replies for RS in stop_reply_queue. */
6224
6225 static void
6226 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6227 {
6228 struct queue_iter_param param;
6229
6230 param.input = rs;
6231 param.output = NULL;
6232 /* Discard the stop replies we have already pulled with
6233 vStopped. */
6234 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6235 remove_stop_reply_of_remote_state, &param);
6236 }
6237
6238 /* A parameter to pass data in and out. */
6239
6240 static int
6241 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6242 QUEUE_ITER (stop_reply_p) *iter,
6243 stop_reply_p event,
6244 void *data)
6245 {
6246 struct queue_iter_param *param = (struct queue_iter_param *) data;
6247 ptid_t *ptid = (ptid_t *) param->input;
6248
6249 if (ptid_match (event->ptid, *ptid))
6250 {
6251 param->output = event;
6252 QUEUE_remove_elem (stop_reply_p, q, iter);
6253 return 0;
6254 }
6255
6256 return 1;
6257 }
6258
6259 /* Remove the first reply in 'stop_reply_queue' which matches
6260 PTID. */
6261
6262 static struct stop_reply *
6263 remote_notif_remove_queued_reply (ptid_t ptid)
6264 {
6265 struct queue_iter_param param;
6266
6267 param.input = &ptid;
6268 param.output = NULL;
6269
6270 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6271 remote_notif_remove_once_on_match, &param);
6272 if (notif_debug)
6273 fprintf_unfiltered (gdb_stdlog,
6274 "notif: discard queued event: 'Stop' in %s\n",
6275 target_pid_to_str (ptid));
6276
6277 return param.output;
6278 }
6279
6280 /* Look for a queued stop reply belonging to PTID. If one is found,
6281 remove it from the queue, and return it. Returns NULL if none is
6282 found. If there are still queued events left to process, tell the
6283 event loop to get back to target_wait soon. */
6284
6285 static struct stop_reply *
6286 queued_stop_reply (ptid_t ptid)
6287 {
6288 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6289
6290 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6291 /* There's still at least an event left. */
6292 mark_async_event_handler (remote_async_inferior_event_token);
6293
6294 return r;
6295 }
6296
6297 /* Push a fully parsed stop reply in the stop reply queue. Since we
6298 know that we now have at least one queued event left to pass to the
6299 core side, tell the event loop to get back to target_wait soon. */
6300
6301 static void
6302 push_stop_reply (struct stop_reply *new_event)
6303 {
6304 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6305
6306 if (notif_debug)
6307 fprintf_unfiltered (gdb_stdlog,
6308 "notif: push 'Stop' %s to queue %d\n",
6309 target_pid_to_str (new_event->ptid),
6310 QUEUE_length (stop_reply_p,
6311 stop_reply_queue));
6312
6313 mark_async_event_handler (remote_async_inferior_event_token);
6314 }
6315
6316 static int
6317 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6318 QUEUE_ITER (stop_reply_p) *iter,
6319 struct stop_reply *event,
6320 void *data)
6321 {
6322 ptid_t *ptid = (ptid_t *) data;
6323
6324 return !(ptid_equal (*ptid, event->ptid)
6325 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6326 }
6327
6328 /* Returns true if we have a stop reply for PTID. */
6329
6330 static int
6331 peek_stop_reply (ptid_t ptid)
6332 {
6333 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6334 stop_reply_match_ptid_and_ws, &ptid);
6335 }
6336
6337 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6338 starting with P and ending with PEND matches PREFIX. */
6339
6340 static int
6341 strprefix (const char *p, const char *pend, const char *prefix)
6342 {
6343 for ( ; p < pend; p++, prefix++)
6344 if (*p != *prefix)
6345 return 0;
6346 return *prefix == '\0';
6347 }
6348
6349 /* Parse the stop reply in BUF. Either the function succeeds, and the
6350 result is stored in EVENT, or throws an error. */
6351
6352 static void
6353 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6354 {
6355 struct remote_arch_state *rsa = get_remote_arch_state ();
6356 ULONGEST addr;
6357 char *p;
6358 int skipregs = 0;
6359
6360 event->ptid = null_ptid;
6361 event->rs = get_remote_state ();
6362 event->ws.kind = TARGET_WAITKIND_IGNORE;
6363 event->ws.value.integer = 0;
6364 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6365 event->regcache = NULL;
6366 event->core = -1;
6367
6368 switch (buf[0])
6369 {
6370 case 'T': /* Status with PC, SP, FP, ... */
6371 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6372 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6373 ss = signal number
6374 n... = register number
6375 r... = register contents
6376 */
6377
6378 p = &buf[3]; /* after Txx */
6379 while (*p)
6380 {
6381 char *p1;
6382 int fieldsize;
6383
6384 p1 = strchr (p, ':');
6385 if (p1 == NULL)
6386 error (_("Malformed packet(a) (missing colon): %s\n\
6387 Packet: '%s'\n"),
6388 p, buf);
6389 if (p == p1)
6390 error (_("Malformed packet(a) (missing register number): %s\n\
6391 Packet: '%s'\n"),
6392 p, buf);
6393
6394 /* Some "registers" are actually extended stop information.
6395 Note if you're adding a new entry here: GDB 7.9 and
6396 earlier assume that all register "numbers" that start
6397 with an hex digit are real register numbers. Make sure
6398 the server only sends such a packet if it knows the
6399 client understands it. */
6400
6401 if (strprefix (p, p1, "thread"))
6402 event->ptid = read_ptid (++p1, &p);
6403 else if (strprefix (p, p1, "syscall_entry"))
6404 {
6405 ULONGEST sysno;
6406
6407 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6408 p = unpack_varlen_hex (++p1, &sysno);
6409 event->ws.value.syscall_number = (int) sysno;
6410 }
6411 else if (strprefix (p, p1, "syscall_return"))
6412 {
6413 ULONGEST sysno;
6414
6415 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6416 p = unpack_varlen_hex (++p1, &sysno);
6417 event->ws.value.syscall_number = (int) sysno;
6418 }
6419 else if (strprefix (p, p1, "watch")
6420 || strprefix (p, p1, "rwatch")
6421 || strprefix (p, p1, "awatch"))
6422 {
6423 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6424 p = unpack_varlen_hex (++p1, &addr);
6425 event->watch_data_address = (CORE_ADDR) addr;
6426 }
6427 else if (strprefix (p, p1, "swbreak"))
6428 {
6429 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6430
6431 /* Make sure the stub doesn't forget to indicate support
6432 with qSupported. */
6433 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6434 error (_("Unexpected swbreak stop reason"));
6435
6436 /* The value part is documented as "must be empty",
6437 though we ignore it, in case we ever decide to make
6438 use of it in a backward compatible way. */
6439 p = strchrnul (p1 + 1, ';');
6440 }
6441 else if (strprefix (p, p1, "hwbreak"))
6442 {
6443 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6444
6445 /* Make sure the stub doesn't forget to indicate support
6446 with qSupported. */
6447 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6448 error (_("Unexpected hwbreak stop reason"));
6449
6450 /* See above. */
6451 p = strchrnul (p1 + 1, ';');
6452 }
6453 else if (strprefix (p, p1, "library"))
6454 {
6455 event->ws.kind = TARGET_WAITKIND_LOADED;
6456 p = strchrnul (p1 + 1, ';');
6457 }
6458 else if (strprefix (p, p1, "replaylog"))
6459 {
6460 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6461 /* p1 will indicate "begin" or "end", but it makes
6462 no difference for now, so ignore it. */
6463 p = strchrnul (p1 + 1, ';');
6464 }
6465 else if (strprefix (p, p1, "core"))
6466 {
6467 ULONGEST c;
6468
6469 p = unpack_varlen_hex (++p1, &c);
6470 event->core = c;
6471 }
6472 else if (strprefix (p, p1, "fork"))
6473 {
6474 event->ws.value.related_pid = read_ptid (++p1, &p);
6475 event->ws.kind = TARGET_WAITKIND_FORKED;
6476 }
6477 else if (strprefix (p, p1, "vfork"))
6478 {
6479 event->ws.value.related_pid = read_ptid (++p1, &p);
6480 event->ws.kind = TARGET_WAITKIND_VFORKED;
6481 }
6482 else if (strprefix (p, p1, "vforkdone"))
6483 {
6484 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6485 p = strchrnul (p1 + 1, ';');
6486 }
6487 else if (strprefix (p, p1, "exec"))
6488 {
6489 ULONGEST ignored;
6490 char pathname[PATH_MAX];
6491 int pathlen;
6492
6493 /* Determine the length of the execd pathname. */
6494 p = unpack_varlen_hex (++p1, &ignored);
6495 pathlen = (p - p1) / 2;
6496
6497 /* Save the pathname for event reporting and for
6498 the next run command. */
6499 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6500 pathname[pathlen] = '\0';
6501
6502 /* This is freed during event handling. */
6503 event->ws.value.execd_pathname = xstrdup (pathname);
6504 event->ws.kind = TARGET_WAITKIND_EXECD;
6505
6506 /* Skip the registers included in this packet, since
6507 they may be for an architecture different from the
6508 one used by the original program. */
6509 skipregs = 1;
6510 }
6511 else if (strprefix (p, p1, "create"))
6512 {
6513 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6514 p = strchrnul (p1 + 1, ';');
6515 }
6516 else
6517 {
6518 ULONGEST pnum;
6519 char *p_temp;
6520
6521 if (skipregs)
6522 {
6523 p = strchrnul (p1 + 1, ';');
6524 p++;
6525 continue;
6526 }
6527
6528 /* Maybe a real ``P'' register number. */
6529 p_temp = unpack_varlen_hex (p, &pnum);
6530 /* If the first invalid character is the colon, we got a
6531 register number. Otherwise, it's an unknown stop
6532 reason. */
6533 if (p_temp == p1)
6534 {
6535 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6536 cached_reg_t cached_reg;
6537
6538 if (reg == NULL)
6539 error (_("Remote sent bad register number %s: %s\n\
6540 Packet: '%s'\n"),
6541 hex_string (pnum), p, buf);
6542
6543 cached_reg.num = reg->regnum;
6544
6545 p = p1 + 1;
6546 fieldsize = hex2bin (p, cached_reg.data,
6547 register_size (target_gdbarch (),
6548 reg->regnum));
6549 p += 2 * fieldsize;
6550 if (fieldsize < register_size (target_gdbarch (),
6551 reg->regnum))
6552 warning (_("Remote reply is too short: %s"), buf);
6553
6554 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6555 }
6556 else
6557 {
6558 /* Not a number. Silently skip unknown optional
6559 info. */
6560 p = strchrnul (p1 + 1, ';');
6561 }
6562 }
6563
6564 if (*p != ';')
6565 error (_("Remote register badly formatted: %s\nhere: %s"),
6566 buf, p);
6567 ++p;
6568 }
6569
6570 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6571 break;
6572
6573 /* fall through */
6574 case 'S': /* Old style status, just signal only. */
6575 {
6576 int sig;
6577
6578 event->ws.kind = TARGET_WAITKIND_STOPPED;
6579 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6580 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6581 event->ws.value.sig = (enum gdb_signal) sig;
6582 else
6583 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6584 }
6585 break;
6586 case 'w': /* Thread exited. */
6587 {
6588 char *p;
6589 ULONGEST value;
6590
6591 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6592 p = unpack_varlen_hex (&buf[1], &value);
6593 event->ws.value.integer = value;
6594 if (*p != ';')
6595 error (_("stop reply packet badly formatted: %s"), buf);
6596 event->ptid = read_ptid (++p, NULL);
6597 break;
6598 }
6599 case 'W': /* Target exited. */
6600 case 'X':
6601 {
6602 char *p;
6603 int pid;
6604 ULONGEST value;
6605
6606 /* GDB used to accept only 2 hex chars here. Stubs should
6607 only send more if they detect GDB supports multi-process
6608 support. */
6609 p = unpack_varlen_hex (&buf[1], &value);
6610
6611 if (buf[0] == 'W')
6612 {
6613 /* The remote process exited. */
6614 event->ws.kind = TARGET_WAITKIND_EXITED;
6615 event->ws.value.integer = value;
6616 }
6617 else
6618 {
6619 /* The remote process exited with a signal. */
6620 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6621 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6622 event->ws.value.sig = (enum gdb_signal) value;
6623 else
6624 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6625 }
6626
6627 /* If no process is specified, assume inferior_ptid. */
6628 pid = ptid_get_pid (inferior_ptid);
6629 if (*p == '\0')
6630 ;
6631 else if (*p == ';')
6632 {
6633 p++;
6634
6635 if (*p == '\0')
6636 ;
6637 else if (startswith (p, "process:"))
6638 {
6639 ULONGEST upid;
6640
6641 p += sizeof ("process:") - 1;
6642 unpack_varlen_hex (p, &upid);
6643 pid = upid;
6644 }
6645 else
6646 error (_("unknown stop reply packet: %s"), buf);
6647 }
6648 else
6649 error (_("unknown stop reply packet: %s"), buf);
6650 event->ptid = pid_to_ptid (pid);
6651 }
6652 break;
6653 case 'N':
6654 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6655 event->ptid = minus_one_ptid;
6656 break;
6657 }
6658
6659 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6660 error (_("No process or thread specified in stop reply: %s"), buf);
6661 }
6662
6663 /* When the stub wants to tell GDB about a new notification reply, it
6664 sends a notification (%Stop, for example). Those can come it at
6665 any time, hence, we have to make sure that any pending
6666 putpkt/getpkt sequence we're making is finished, before querying
6667 the stub for more events with the corresponding ack command
6668 (vStopped, for example). E.g., if we started a vStopped sequence
6669 immediately upon receiving the notification, something like this
6670 could happen:
6671
6672 1.1) --> Hg 1
6673 1.2) <-- OK
6674 1.3) --> g
6675 1.4) <-- %Stop
6676 1.5) --> vStopped
6677 1.6) <-- (registers reply to step #1.3)
6678
6679 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6680 query.
6681
6682 To solve this, whenever we parse a %Stop notification successfully,
6683 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6684 doing whatever we were doing:
6685
6686 2.1) --> Hg 1
6687 2.2) <-- OK
6688 2.3) --> g
6689 2.4) <-- %Stop
6690 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6691 2.5) <-- (registers reply to step #2.3)
6692
6693 Eventualy after step #2.5, we return to the event loop, which
6694 notices there's an event on the
6695 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6696 associated callback --- the function below. At this point, we're
6697 always safe to start a vStopped sequence. :
6698
6699 2.6) --> vStopped
6700 2.7) <-- T05 thread:2
6701 2.8) --> vStopped
6702 2.9) --> OK
6703 */
6704
6705 void
6706 remote_notif_get_pending_events (struct notif_client *nc)
6707 {
6708 struct remote_state *rs = get_remote_state ();
6709
6710 if (rs->notif_state->pending_event[nc->id] != NULL)
6711 {
6712 if (notif_debug)
6713 fprintf_unfiltered (gdb_stdlog,
6714 "notif: process: '%s' ack pending event\n",
6715 nc->name);
6716
6717 /* acknowledge */
6718 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6719 rs->notif_state->pending_event[nc->id] = NULL;
6720
6721 while (1)
6722 {
6723 getpkt (&rs->buf, &rs->buf_size, 0);
6724 if (strcmp (rs->buf, "OK") == 0)
6725 break;
6726 else
6727 remote_notif_ack (nc, rs->buf);
6728 }
6729 }
6730 else
6731 {
6732 if (notif_debug)
6733 fprintf_unfiltered (gdb_stdlog,
6734 "notif: process: '%s' no pending reply\n",
6735 nc->name);
6736 }
6737 }
6738
6739 /* Called when it is decided that STOP_REPLY holds the info of the
6740 event that is to be returned to the core. This function always
6741 destroys STOP_REPLY. */
6742
6743 static ptid_t
6744 process_stop_reply (struct stop_reply *stop_reply,
6745 struct target_waitstatus *status)
6746 {
6747 ptid_t ptid;
6748
6749 *status = stop_reply->ws;
6750 ptid = stop_reply->ptid;
6751
6752 /* If no thread/process was reported by the stub, assume the current
6753 inferior. */
6754 if (ptid_equal (ptid, null_ptid))
6755 ptid = inferior_ptid;
6756
6757 if (status->kind != TARGET_WAITKIND_EXITED
6758 && status->kind != TARGET_WAITKIND_SIGNALLED
6759 && status->kind != TARGET_WAITKIND_NO_RESUMED)
6760 {
6761 struct private_thread_info *remote_thr;
6762
6763 /* Expedited registers. */
6764 if (stop_reply->regcache)
6765 {
6766 struct regcache *regcache
6767 = get_thread_arch_regcache (ptid, target_gdbarch ());
6768 cached_reg_t *reg;
6769 int ix;
6770
6771 for (ix = 0;
6772 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6773 ix++)
6774 regcache_raw_supply (regcache, reg->num, reg->data);
6775 VEC_free (cached_reg_t, stop_reply->regcache);
6776 }
6777
6778 remote_notice_new_inferior (ptid, 0);
6779 remote_thr = demand_private_info (ptid);
6780 remote_thr->core = stop_reply->core;
6781 remote_thr->stop_reason = stop_reply->stop_reason;
6782 remote_thr->watch_data_address = stop_reply->watch_data_address;
6783 }
6784
6785 stop_reply_xfree (stop_reply);
6786 return ptid;
6787 }
6788
6789 /* The non-stop mode version of target_wait. */
6790
6791 static ptid_t
6792 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6793 {
6794 struct remote_state *rs = get_remote_state ();
6795 struct stop_reply *stop_reply;
6796 int ret;
6797 int is_notif = 0;
6798
6799 /* If in non-stop mode, get out of getpkt even if a
6800 notification is received. */
6801
6802 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6803 0 /* forever */, &is_notif);
6804 while (1)
6805 {
6806 if (ret != -1 && !is_notif)
6807 switch (rs->buf[0])
6808 {
6809 case 'E': /* Error of some sort. */
6810 /* We're out of sync with the target now. Did it continue
6811 or not? We can't tell which thread it was in non-stop,
6812 so just ignore this. */
6813 warning (_("Remote failure reply: %s"), rs->buf);
6814 break;
6815 case 'O': /* Console output. */
6816 remote_console_output (rs->buf + 1);
6817 break;
6818 default:
6819 warning (_("Invalid remote reply: %s"), rs->buf);
6820 break;
6821 }
6822
6823 /* Acknowledge a pending stop reply that may have arrived in the
6824 mean time. */
6825 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6826 remote_notif_get_pending_events (&notif_client_stop);
6827
6828 /* If indeed we noticed a stop reply, we're done. */
6829 stop_reply = queued_stop_reply (ptid);
6830 if (stop_reply != NULL)
6831 return process_stop_reply (stop_reply, status);
6832
6833 /* Still no event. If we're just polling for an event, then
6834 return to the event loop. */
6835 if (options & TARGET_WNOHANG)
6836 {
6837 status->kind = TARGET_WAITKIND_IGNORE;
6838 return minus_one_ptid;
6839 }
6840
6841 /* Otherwise do a blocking wait. */
6842 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6843 1 /* forever */, &is_notif);
6844 }
6845 }
6846
6847 /* Wait until the remote machine stops, then return, storing status in
6848 STATUS just as `wait' would. */
6849
6850 static ptid_t
6851 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6852 {
6853 struct remote_state *rs = get_remote_state ();
6854 ptid_t event_ptid = null_ptid;
6855 char *buf;
6856 struct stop_reply *stop_reply;
6857
6858 again:
6859
6860 status->kind = TARGET_WAITKIND_IGNORE;
6861 status->value.integer = 0;
6862
6863 stop_reply = queued_stop_reply (ptid);
6864 if (stop_reply != NULL)
6865 return process_stop_reply (stop_reply, status);
6866
6867 if (rs->cached_wait_status)
6868 /* Use the cached wait status, but only once. */
6869 rs->cached_wait_status = 0;
6870 else
6871 {
6872 int ret;
6873 int is_notif;
6874 int forever = ((options & TARGET_WNOHANG) == 0
6875 && wait_forever_enabled_p);
6876
6877 if (!rs->waiting_for_stop_reply)
6878 {
6879 status->kind = TARGET_WAITKIND_NO_RESUMED;
6880 return minus_one_ptid;
6881 }
6882
6883 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6884 _never_ wait for ever -> test on target_is_async_p().
6885 However, before we do that we need to ensure that the caller
6886 knows how to take the target into/out of async mode. */
6887 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6888 forever, &is_notif);
6889
6890 /* GDB gets a notification. Return to core as this event is
6891 not interesting. */
6892 if (ret != -1 && is_notif)
6893 return minus_one_ptid;
6894
6895 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6896 return minus_one_ptid;
6897 }
6898
6899 buf = rs->buf;
6900
6901 /* Assume that the target has acknowledged Ctrl-C unless we receive
6902 an 'F' or 'O' packet. */
6903 if (buf[0] != 'F' && buf[0] != 'O')
6904 rs->ctrlc_pending_p = 0;
6905
6906 switch (buf[0])
6907 {
6908 case 'E': /* Error of some sort. */
6909 /* We're out of sync with the target now. Did it continue or
6910 not? Not is more likely, so report a stop. */
6911 rs->waiting_for_stop_reply = 0;
6912
6913 warning (_("Remote failure reply: %s"), buf);
6914 status->kind = TARGET_WAITKIND_STOPPED;
6915 status->value.sig = GDB_SIGNAL_0;
6916 break;
6917 case 'F': /* File-I/O request. */
6918 /* GDB may access the inferior memory while handling the File-I/O
6919 request, but we don't want GDB accessing memory while waiting
6920 for a stop reply. See the comments in putpkt_binary. Set
6921 waiting_for_stop_reply to 0 temporarily. */
6922 rs->waiting_for_stop_reply = 0;
6923 remote_fileio_request (buf, rs->ctrlc_pending_p);
6924 rs->ctrlc_pending_p = 0;
6925 /* GDB handled the File-I/O request, and the target is running
6926 again. Keep waiting for events. */
6927 rs->waiting_for_stop_reply = 1;
6928 break;
6929 case 'N': case 'T': case 'S': case 'X': case 'W':
6930 {
6931 struct stop_reply *stop_reply;
6932
6933 /* There is a stop reply to handle. */
6934 rs->waiting_for_stop_reply = 0;
6935
6936 stop_reply
6937 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6938 rs->buf);
6939
6940 event_ptid = process_stop_reply (stop_reply, status);
6941 break;
6942 }
6943 case 'O': /* Console output. */
6944 remote_console_output (buf + 1);
6945 break;
6946 case '\0':
6947 if (rs->last_sent_signal != GDB_SIGNAL_0)
6948 {
6949 /* Zero length reply means that we tried 'S' or 'C' and the
6950 remote system doesn't support it. */
6951 target_terminal_ours_for_output ();
6952 printf_filtered
6953 ("Can't send signals to this remote system. %s not sent.\n",
6954 gdb_signal_to_name (rs->last_sent_signal));
6955 rs->last_sent_signal = GDB_SIGNAL_0;
6956 target_terminal_inferior ();
6957
6958 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6959 putpkt ((char *) buf);
6960 break;
6961 }
6962 /* else fallthrough */
6963 default:
6964 warning (_("Invalid remote reply: %s"), buf);
6965 break;
6966 }
6967
6968 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6969 return minus_one_ptid;
6970 else if (status->kind == TARGET_WAITKIND_IGNORE)
6971 {
6972 /* Nothing interesting happened. If we're doing a non-blocking
6973 poll, we're done. Otherwise, go back to waiting. */
6974 if (options & TARGET_WNOHANG)
6975 return minus_one_ptid;
6976 else
6977 goto again;
6978 }
6979 else if (status->kind != TARGET_WAITKIND_EXITED
6980 && status->kind != TARGET_WAITKIND_SIGNALLED)
6981 {
6982 if (!ptid_equal (event_ptid, null_ptid))
6983 record_currthread (rs, event_ptid);
6984 else
6985 event_ptid = inferior_ptid;
6986 }
6987 else
6988 /* A process exit. Invalidate our notion of current thread. */
6989 record_currthread (rs, minus_one_ptid);
6990
6991 return event_ptid;
6992 }
6993
6994 /* Wait until the remote machine stops, then return, storing status in
6995 STATUS just as `wait' would. */
6996
6997 static ptid_t
6998 remote_wait (struct target_ops *ops,
6999 ptid_t ptid, struct target_waitstatus *status, int options)
7000 {
7001 ptid_t event_ptid;
7002
7003 if (target_is_non_stop_p ())
7004 event_ptid = remote_wait_ns (ptid, status, options);
7005 else
7006 event_ptid = remote_wait_as (ptid, status, options);
7007
7008 if (target_is_async_p ())
7009 {
7010 /* If there are are events left in the queue tell the event loop
7011 to return here. */
7012 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7013 mark_async_event_handler (remote_async_inferior_event_token);
7014 }
7015
7016 return event_ptid;
7017 }
7018
7019 /* Fetch a single register using a 'p' packet. */
7020
7021 static int
7022 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7023 {
7024 struct remote_state *rs = get_remote_state ();
7025 char *buf, *p;
7026 char regp[MAX_REGISTER_SIZE];
7027 int i;
7028
7029 if (packet_support (PACKET_p) == PACKET_DISABLE)
7030 return 0;
7031
7032 if (reg->pnum == -1)
7033 return 0;
7034
7035 p = rs->buf;
7036 *p++ = 'p';
7037 p += hexnumstr (p, reg->pnum);
7038 *p++ = '\0';
7039 putpkt (rs->buf);
7040 getpkt (&rs->buf, &rs->buf_size, 0);
7041
7042 buf = rs->buf;
7043
7044 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7045 {
7046 case PACKET_OK:
7047 break;
7048 case PACKET_UNKNOWN:
7049 return 0;
7050 case PACKET_ERROR:
7051 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7052 gdbarch_register_name (get_regcache_arch (regcache),
7053 reg->regnum),
7054 buf);
7055 }
7056
7057 /* If this register is unfetchable, tell the regcache. */
7058 if (buf[0] == 'x')
7059 {
7060 regcache_raw_supply (regcache, reg->regnum, NULL);
7061 return 1;
7062 }
7063
7064 /* Otherwise, parse and supply the value. */
7065 p = buf;
7066 i = 0;
7067 while (p[0] != 0)
7068 {
7069 if (p[1] == 0)
7070 error (_("fetch_register_using_p: early buf termination"));
7071
7072 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7073 p += 2;
7074 }
7075 regcache_raw_supply (regcache, reg->regnum, regp);
7076 return 1;
7077 }
7078
7079 /* Fetch the registers included in the target's 'g' packet. */
7080
7081 static int
7082 send_g_packet (void)
7083 {
7084 struct remote_state *rs = get_remote_state ();
7085 int buf_len;
7086
7087 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7088 remote_send (&rs->buf, &rs->buf_size);
7089
7090 /* We can get out of synch in various cases. If the first character
7091 in the buffer is not a hex character, assume that has happened
7092 and try to fetch another packet to read. */
7093 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7094 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7095 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7096 && rs->buf[0] != 'x') /* New: unavailable register value. */
7097 {
7098 if (remote_debug)
7099 fprintf_unfiltered (gdb_stdlog,
7100 "Bad register packet; fetching a new packet\n");
7101 getpkt (&rs->buf, &rs->buf_size, 0);
7102 }
7103
7104 buf_len = strlen (rs->buf);
7105
7106 /* Sanity check the received packet. */
7107 if (buf_len % 2 != 0)
7108 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7109
7110 return buf_len / 2;
7111 }
7112
7113 static void
7114 process_g_packet (struct regcache *regcache)
7115 {
7116 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7117 struct remote_state *rs = get_remote_state ();
7118 struct remote_arch_state *rsa = get_remote_arch_state ();
7119 int i, buf_len;
7120 char *p;
7121 char *regs;
7122
7123 buf_len = strlen (rs->buf);
7124
7125 /* Further sanity checks, with knowledge of the architecture. */
7126 if (buf_len > 2 * rsa->sizeof_g_packet)
7127 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7128
7129 /* Save the size of the packet sent to us by the target. It is used
7130 as a heuristic when determining the max size of packets that the
7131 target can safely receive. */
7132 if (rsa->actual_register_packet_size == 0)
7133 rsa->actual_register_packet_size = buf_len;
7134
7135 /* If this is smaller than we guessed the 'g' packet would be,
7136 update our records. A 'g' reply that doesn't include a register's
7137 value implies either that the register is not available, or that
7138 the 'p' packet must be used. */
7139 if (buf_len < 2 * rsa->sizeof_g_packet)
7140 {
7141 rsa->sizeof_g_packet = buf_len / 2;
7142
7143 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7144 {
7145 if (rsa->regs[i].pnum == -1)
7146 continue;
7147
7148 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7149 rsa->regs[i].in_g_packet = 0;
7150 else
7151 rsa->regs[i].in_g_packet = 1;
7152 }
7153 }
7154
7155 regs = (char *) alloca (rsa->sizeof_g_packet);
7156
7157 /* Unimplemented registers read as all bits zero. */
7158 memset (regs, 0, rsa->sizeof_g_packet);
7159
7160 /* Reply describes registers byte by byte, each byte encoded as two
7161 hex characters. Suck them all up, then supply them to the
7162 register cacheing/storage mechanism. */
7163
7164 p = rs->buf;
7165 for (i = 0; i < rsa->sizeof_g_packet; i++)
7166 {
7167 if (p[0] == 0 || p[1] == 0)
7168 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7169 internal_error (__FILE__, __LINE__,
7170 _("unexpected end of 'g' packet reply"));
7171
7172 if (p[0] == 'x' && p[1] == 'x')
7173 regs[i] = 0; /* 'x' */
7174 else
7175 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7176 p += 2;
7177 }
7178
7179 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7180 {
7181 struct packet_reg *r = &rsa->regs[i];
7182
7183 if (r->in_g_packet)
7184 {
7185 if (r->offset * 2 >= strlen (rs->buf))
7186 /* This shouldn't happen - we adjusted in_g_packet above. */
7187 internal_error (__FILE__, __LINE__,
7188 _("unexpected end of 'g' packet reply"));
7189 else if (rs->buf[r->offset * 2] == 'x')
7190 {
7191 gdb_assert (r->offset * 2 < strlen (rs->buf));
7192 /* The register isn't available, mark it as such (at
7193 the same time setting the value to zero). */
7194 regcache_raw_supply (regcache, r->regnum, NULL);
7195 }
7196 else
7197 regcache_raw_supply (regcache, r->regnum,
7198 regs + r->offset);
7199 }
7200 }
7201 }
7202
7203 static void
7204 fetch_registers_using_g (struct regcache *regcache)
7205 {
7206 send_g_packet ();
7207 process_g_packet (regcache);
7208 }
7209
7210 /* Make the remote selected traceframe match GDB's selected
7211 traceframe. */
7212
7213 static void
7214 set_remote_traceframe (void)
7215 {
7216 int newnum;
7217 struct remote_state *rs = get_remote_state ();
7218
7219 if (rs->remote_traceframe_number == get_traceframe_number ())
7220 return;
7221
7222 /* Avoid recursion, remote_trace_find calls us again. */
7223 rs->remote_traceframe_number = get_traceframe_number ();
7224
7225 newnum = target_trace_find (tfind_number,
7226 get_traceframe_number (), 0, 0, NULL);
7227
7228 /* Should not happen. If it does, all bets are off. */
7229 if (newnum != get_traceframe_number ())
7230 warning (_("could not set remote traceframe"));
7231 }
7232
7233 static void
7234 remote_fetch_registers (struct target_ops *ops,
7235 struct regcache *regcache, int regnum)
7236 {
7237 struct remote_arch_state *rsa = get_remote_arch_state ();
7238 int i;
7239
7240 set_remote_traceframe ();
7241 set_general_thread (inferior_ptid);
7242
7243 if (regnum >= 0)
7244 {
7245 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7246
7247 gdb_assert (reg != NULL);
7248
7249 /* If this register might be in the 'g' packet, try that first -
7250 we are likely to read more than one register. If this is the
7251 first 'g' packet, we might be overly optimistic about its
7252 contents, so fall back to 'p'. */
7253 if (reg->in_g_packet)
7254 {
7255 fetch_registers_using_g (regcache);
7256 if (reg->in_g_packet)
7257 return;
7258 }
7259
7260 if (fetch_register_using_p (regcache, reg))
7261 return;
7262
7263 /* This register is not available. */
7264 regcache_raw_supply (regcache, reg->regnum, NULL);
7265
7266 return;
7267 }
7268
7269 fetch_registers_using_g (regcache);
7270
7271 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7272 if (!rsa->regs[i].in_g_packet)
7273 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7274 {
7275 /* This register is not available. */
7276 regcache_raw_supply (regcache, i, NULL);
7277 }
7278 }
7279
7280 /* Prepare to store registers. Since we may send them all (using a
7281 'G' request), we have to read out the ones we don't want to change
7282 first. */
7283
7284 static void
7285 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7286 {
7287 struct remote_arch_state *rsa = get_remote_arch_state ();
7288 int i;
7289 gdb_byte buf[MAX_REGISTER_SIZE];
7290
7291 /* Make sure the entire registers array is valid. */
7292 switch (packet_support (PACKET_P))
7293 {
7294 case PACKET_DISABLE:
7295 case PACKET_SUPPORT_UNKNOWN:
7296 /* Make sure all the necessary registers are cached. */
7297 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7298 if (rsa->regs[i].in_g_packet)
7299 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7300 break;
7301 case PACKET_ENABLE:
7302 break;
7303 }
7304 }
7305
7306 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7307 packet was not recognized. */
7308
7309 static int
7310 store_register_using_P (const struct regcache *regcache,
7311 struct packet_reg *reg)
7312 {
7313 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7314 struct remote_state *rs = get_remote_state ();
7315 /* Try storing a single register. */
7316 char *buf = rs->buf;
7317 gdb_byte regp[MAX_REGISTER_SIZE];
7318 char *p;
7319
7320 if (packet_support (PACKET_P) == PACKET_DISABLE)
7321 return 0;
7322
7323 if (reg->pnum == -1)
7324 return 0;
7325
7326 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7327 p = buf + strlen (buf);
7328 regcache_raw_collect (regcache, reg->regnum, regp);
7329 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7330 putpkt (rs->buf);
7331 getpkt (&rs->buf, &rs->buf_size, 0);
7332
7333 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7334 {
7335 case PACKET_OK:
7336 return 1;
7337 case PACKET_ERROR:
7338 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7339 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7340 case PACKET_UNKNOWN:
7341 return 0;
7342 default:
7343 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7344 }
7345 }
7346
7347 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7348 contents of the register cache buffer. FIXME: ignores errors. */
7349
7350 static void
7351 store_registers_using_G (const struct regcache *regcache)
7352 {
7353 struct remote_state *rs = get_remote_state ();
7354 struct remote_arch_state *rsa = get_remote_arch_state ();
7355 gdb_byte *regs;
7356 char *p;
7357
7358 /* Extract all the registers in the regcache copying them into a
7359 local buffer. */
7360 {
7361 int i;
7362
7363 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7364 memset (regs, 0, rsa->sizeof_g_packet);
7365 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7366 {
7367 struct packet_reg *r = &rsa->regs[i];
7368
7369 if (r->in_g_packet)
7370 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7371 }
7372 }
7373
7374 /* Command describes registers byte by byte,
7375 each byte encoded as two hex characters. */
7376 p = rs->buf;
7377 *p++ = 'G';
7378 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7379 updated. */
7380 bin2hex (regs, p, rsa->sizeof_g_packet);
7381 putpkt (rs->buf);
7382 getpkt (&rs->buf, &rs->buf_size, 0);
7383 if (packet_check_result (rs->buf) == PACKET_ERROR)
7384 error (_("Could not write registers; remote failure reply '%s'"),
7385 rs->buf);
7386 }
7387
7388 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7389 of the register cache buffer. FIXME: ignores errors. */
7390
7391 static void
7392 remote_store_registers (struct target_ops *ops,
7393 struct regcache *regcache, int regnum)
7394 {
7395 struct remote_arch_state *rsa = get_remote_arch_state ();
7396 int i;
7397
7398 set_remote_traceframe ();
7399 set_general_thread (inferior_ptid);
7400
7401 if (regnum >= 0)
7402 {
7403 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7404
7405 gdb_assert (reg != NULL);
7406
7407 /* Always prefer to store registers using the 'P' packet if
7408 possible; we often change only a small number of registers.
7409 Sometimes we change a larger number; we'd need help from a
7410 higher layer to know to use 'G'. */
7411 if (store_register_using_P (regcache, reg))
7412 return;
7413
7414 /* For now, don't complain if we have no way to write the
7415 register. GDB loses track of unavailable registers too
7416 easily. Some day, this may be an error. We don't have
7417 any way to read the register, either... */
7418 if (!reg->in_g_packet)
7419 return;
7420
7421 store_registers_using_G (regcache);
7422 return;
7423 }
7424
7425 store_registers_using_G (regcache);
7426
7427 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7428 if (!rsa->regs[i].in_g_packet)
7429 if (!store_register_using_P (regcache, &rsa->regs[i]))
7430 /* See above for why we do not issue an error here. */
7431 continue;
7432 }
7433 \f
7434
7435 /* Return the number of hex digits in num. */
7436
7437 static int
7438 hexnumlen (ULONGEST num)
7439 {
7440 int i;
7441
7442 for (i = 0; num != 0; i++)
7443 num >>= 4;
7444
7445 return max (i, 1);
7446 }
7447
7448 /* Set BUF to the minimum number of hex digits representing NUM. */
7449
7450 static int
7451 hexnumstr (char *buf, ULONGEST num)
7452 {
7453 int len = hexnumlen (num);
7454
7455 return hexnumnstr (buf, num, len);
7456 }
7457
7458
7459 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7460
7461 static int
7462 hexnumnstr (char *buf, ULONGEST num, int width)
7463 {
7464 int i;
7465
7466 buf[width] = '\0';
7467
7468 for (i = width - 1; i >= 0; i--)
7469 {
7470 buf[i] = "0123456789abcdef"[(num & 0xf)];
7471 num >>= 4;
7472 }
7473
7474 return width;
7475 }
7476
7477 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7478
7479 static CORE_ADDR
7480 remote_address_masked (CORE_ADDR addr)
7481 {
7482 unsigned int address_size = remote_address_size;
7483
7484 /* If "remoteaddresssize" was not set, default to target address size. */
7485 if (!address_size)
7486 address_size = gdbarch_addr_bit (target_gdbarch ());
7487
7488 if (address_size > 0
7489 && address_size < (sizeof (ULONGEST) * 8))
7490 {
7491 /* Only create a mask when that mask can safely be constructed
7492 in a ULONGEST variable. */
7493 ULONGEST mask = 1;
7494
7495 mask = (mask << address_size) - 1;
7496 addr &= mask;
7497 }
7498 return addr;
7499 }
7500
7501 /* Determine whether the remote target supports binary downloading.
7502 This is accomplished by sending a no-op memory write of zero length
7503 to the target at the specified address. It does not suffice to send
7504 the whole packet, since many stubs strip the eighth bit and
7505 subsequently compute a wrong checksum, which causes real havoc with
7506 remote_write_bytes.
7507
7508 NOTE: This can still lose if the serial line is not eight-bit
7509 clean. In cases like this, the user should clear "remote
7510 X-packet". */
7511
7512 static void
7513 check_binary_download (CORE_ADDR addr)
7514 {
7515 struct remote_state *rs = get_remote_state ();
7516
7517 switch (packet_support (PACKET_X))
7518 {
7519 case PACKET_DISABLE:
7520 break;
7521 case PACKET_ENABLE:
7522 break;
7523 case PACKET_SUPPORT_UNKNOWN:
7524 {
7525 char *p;
7526
7527 p = rs->buf;
7528 *p++ = 'X';
7529 p += hexnumstr (p, (ULONGEST) addr);
7530 *p++ = ',';
7531 p += hexnumstr (p, (ULONGEST) 0);
7532 *p++ = ':';
7533 *p = '\0';
7534
7535 putpkt_binary (rs->buf, (int) (p - rs->buf));
7536 getpkt (&rs->buf, &rs->buf_size, 0);
7537
7538 if (rs->buf[0] == '\0')
7539 {
7540 if (remote_debug)
7541 fprintf_unfiltered (gdb_stdlog,
7542 "binary downloading NOT "
7543 "supported by target\n");
7544 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7545 }
7546 else
7547 {
7548 if (remote_debug)
7549 fprintf_unfiltered (gdb_stdlog,
7550 "binary downloading supported by target\n");
7551 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7552 }
7553 break;
7554 }
7555 }
7556 }
7557
7558 /* Helper function to resize the payload in order to try to get a good
7559 alignment. We try to write an amount of data such that the next write will
7560 start on an address aligned on REMOTE_ALIGN_WRITES. */
7561
7562 static int
7563 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7564 {
7565 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7566 }
7567
7568 /* Write memory data directly to the remote machine.
7569 This does not inform the data cache; the data cache uses this.
7570 HEADER is the starting part of the packet.
7571 MEMADDR is the address in the remote memory space.
7572 MYADDR is the address of the buffer in our space.
7573 LEN_UNITS is the number of addressable units to write.
7574 UNIT_SIZE is the length in bytes of an addressable unit.
7575 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7576 should send data as binary ('X'), or hex-encoded ('M').
7577
7578 The function creates packet of the form
7579 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7580
7581 where encoding of <DATA> is terminated by PACKET_FORMAT.
7582
7583 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7584 are omitted.
7585
7586 Return the transferred status, error or OK (an
7587 'enum target_xfer_status' value). Save the number of addressable units
7588 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7589
7590 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7591 exchange between gdb and the stub could look like (?? in place of the
7592 checksum):
7593
7594 -> $m1000,4#??
7595 <- aaaabbbbccccdddd
7596
7597 -> $M1000,3:eeeeffffeeee#??
7598 <- OK
7599
7600 -> $m1000,4#??
7601 <- eeeeffffeeeedddd */
7602
7603 static enum target_xfer_status
7604 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7605 const gdb_byte *myaddr, ULONGEST len_units,
7606 int unit_size, ULONGEST *xfered_len_units,
7607 char packet_format, int use_length)
7608 {
7609 struct remote_state *rs = get_remote_state ();
7610 char *p;
7611 char *plen = NULL;
7612 int plenlen = 0;
7613 int todo_units;
7614 int units_written;
7615 int payload_capacity_bytes;
7616 int payload_length_bytes;
7617
7618 if (packet_format != 'X' && packet_format != 'M')
7619 internal_error (__FILE__, __LINE__,
7620 _("remote_write_bytes_aux: bad packet format"));
7621
7622 if (len_units == 0)
7623 return TARGET_XFER_EOF;
7624
7625 payload_capacity_bytes = get_memory_write_packet_size ();
7626
7627 /* The packet buffer will be large enough for the payload;
7628 get_memory_packet_size ensures this. */
7629 rs->buf[0] = '\0';
7630
7631 /* Compute the size of the actual payload by subtracting out the
7632 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7633
7634 payload_capacity_bytes -= strlen ("$,:#NN");
7635 if (!use_length)
7636 /* The comma won't be used. */
7637 payload_capacity_bytes += 1;
7638 payload_capacity_bytes -= strlen (header);
7639 payload_capacity_bytes -= hexnumlen (memaddr);
7640
7641 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7642
7643 strcat (rs->buf, header);
7644 p = rs->buf + strlen (header);
7645
7646 /* Compute a best guess of the number of bytes actually transfered. */
7647 if (packet_format == 'X')
7648 {
7649 /* Best guess at number of bytes that will fit. */
7650 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7651 if (use_length)
7652 payload_capacity_bytes -= hexnumlen (todo_units);
7653 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7654 }
7655 else
7656 {
7657 /* Number of bytes that will fit. */
7658 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7659 if (use_length)
7660 payload_capacity_bytes -= hexnumlen (todo_units);
7661 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7662 }
7663
7664 if (todo_units <= 0)
7665 internal_error (__FILE__, __LINE__,
7666 _("minimum packet size too small to write data"));
7667
7668 /* If we already need another packet, then try to align the end
7669 of this packet to a useful boundary. */
7670 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7671 todo_units = align_for_efficient_write (todo_units, memaddr);
7672
7673 /* Append "<memaddr>". */
7674 memaddr = remote_address_masked (memaddr);
7675 p += hexnumstr (p, (ULONGEST) memaddr);
7676
7677 if (use_length)
7678 {
7679 /* Append ",". */
7680 *p++ = ',';
7681
7682 /* Append the length and retain its location and size. It may need to be
7683 adjusted once the packet body has been created. */
7684 plen = p;
7685 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7686 p += plenlen;
7687 }
7688
7689 /* Append ":". */
7690 *p++ = ':';
7691 *p = '\0';
7692
7693 /* Append the packet body. */
7694 if (packet_format == 'X')
7695 {
7696 /* Binary mode. Send target system values byte by byte, in
7697 increasing byte addresses. Only escape certain critical
7698 characters. */
7699 payload_length_bytes =
7700 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7701 &units_written, payload_capacity_bytes);
7702
7703 /* If not all TODO units fit, then we'll need another packet. Make
7704 a second try to keep the end of the packet aligned. Don't do
7705 this if the packet is tiny. */
7706 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7707 {
7708 int new_todo_units;
7709
7710 new_todo_units = align_for_efficient_write (units_written, memaddr);
7711
7712 if (new_todo_units != units_written)
7713 payload_length_bytes =
7714 remote_escape_output (myaddr, new_todo_units, unit_size,
7715 (gdb_byte *) p, &units_written,
7716 payload_capacity_bytes);
7717 }
7718
7719 p += payload_length_bytes;
7720 if (use_length && units_written < todo_units)
7721 {
7722 /* Escape chars have filled up the buffer prematurely,
7723 and we have actually sent fewer units than planned.
7724 Fix-up the length field of the packet. Use the same
7725 number of characters as before. */
7726 plen += hexnumnstr (plen, (ULONGEST) units_written,
7727 plenlen);
7728 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7729 }
7730 }
7731 else
7732 {
7733 /* Normal mode: Send target system values byte by byte, in
7734 increasing byte addresses. Each byte is encoded as a two hex
7735 value. */
7736 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7737 units_written = todo_units;
7738 }
7739
7740 putpkt_binary (rs->buf, (int) (p - rs->buf));
7741 getpkt (&rs->buf, &rs->buf_size, 0);
7742
7743 if (rs->buf[0] == 'E')
7744 return TARGET_XFER_E_IO;
7745
7746 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7747 send fewer units than we'd planned. */
7748 *xfered_len_units = (ULONGEST) units_written;
7749 return TARGET_XFER_OK;
7750 }
7751
7752 /* Write memory data directly to the remote machine.
7753 This does not inform the data cache; the data cache uses this.
7754 MEMADDR is the address in the remote memory space.
7755 MYADDR is the address of the buffer in our space.
7756 LEN is the number of bytes.
7757
7758 Return the transferred status, error or OK (an
7759 'enum target_xfer_status' value). Save the number of bytes
7760 transferred in *XFERED_LEN. Only transfer a single packet. */
7761
7762 static enum target_xfer_status
7763 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7764 int unit_size, ULONGEST *xfered_len)
7765 {
7766 char *packet_format = 0;
7767
7768 /* Check whether the target supports binary download. */
7769 check_binary_download (memaddr);
7770
7771 switch (packet_support (PACKET_X))
7772 {
7773 case PACKET_ENABLE:
7774 packet_format = "X";
7775 break;
7776 case PACKET_DISABLE:
7777 packet_format = "M";
7778 break;
7779 case PACKET_SUPPORT_UNKNOWN:
7780 internal_error (__FILE__, __LINE__,
7781 _("remote_write_bytes: bad internal state"));
7782 default:
7783 internal_error (__FILE__, __LINE__, _("bad switch"));
7784 }
7785
7786 return remote_write_bytes_aux (packet_format,
7787 memaddr, myaddr, len, unit_size, xfered_len,
7788 packet_format[0], 1);
7789 }
7790
7791 /* Read memory data directly from the remote machine.
7792 This does not use the data cache; the data cache uses this.
7793 MEMADDR is the address in the remote memory space.
7794 MYADDR is the address of the buffer in our space.
7795 LEN_UNITS is the number of addressable memory units to read..
7796 UNIT_SIZE is the length in bytes of an addressable unit.
7797
7798 Return the transferred status, error or OK (an
7799 'enum target_xfer_status' value). Save the number of bytes
7800 transferred in *XFERED_LEN_UNITS.
7801
7802 See the comment of remote_write_bytes_aux for an example of
7803 memory read/write exchange between gdb and the stub. */
7804
7805 static enum target_xfer_status
7806 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7807 int unit_size, ULONGEST *xfered_len_units)
7808 {
7809 struct remote_state *rs = get_remote_state ();
7810 int buf_size_bytes; /* Max size of packet output buffer. */
7811 char *p;
7812 int todo_units;
7813 int decoded_bytes;
7814
7815 buf_size_bytes = get_memory_read_packet_size ();
7816 /* The packet buffer will be large enough for the payload;
7817 get_memory_packet_size ensures this. */
7818
7819 /* Number of units that will fit. */
7820 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7821
7822 /* Construct "m"<memaddr>","<len>". */
7823 memaddr = remote_address_masked (memaddr);
7824 p = rs->buf;
7825 *p++ = 'm';
7826 p += hexnumstr (p, (ULONGEST) memaddr);
7827 *p++ = ',';
7828 p += hexnumstr (p, (ULONGEST) todo_units);
7829 *p = '\0';
7830 putpkt (rs->buf);
7831 getpkt (&rs->buf, &rs->buf_size, 0);
7832 if (rs->buf[0] == 'E'
7833 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7834 && rs->buf[3] == '\0')
7835 return TARGET_XFER_E_IO;
7836 /* Reply describes memory byte by byte, each byte encoded as two hex
7837 characters. */
7838 p = rs->buf;
7839 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7840 /* Return what we have. Let higher layers handle partial reads. */
7841 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7842 return TARGET_XFER_OK;
7843 }
7844
7845 /* Using the set of read-only target sections of remote, read live
7846 read-only memory.
7847
7848 For interface/parameters/return description see target.h,
7849 to_xfer_partial. */
7850
7851 static enum target_xfer_status
7852 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7853 ULONGEST memaddr, ULONGEST len,
7854 int unit_size, ULONGEST *xfered_len)
7855 {
7856 struct target_section *secp;
7857 struct target_section_table *table;
7858
7859 secp = target_section_by_addr (ops, memaddr);
7860 if (secp != NULL
7861 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7862 secp->the_bfd_section)
7863 & SEC_READONLY))
7864 {
7865 struct target_section *p;
7866 ULONGEST memend = memaddr + len;
7867
7868 table = target_get_section_table (ops);
7869
7870 for (p = table->sections; p < table->sections_end; p++)
7871 {
7872 if (memaddr >= p->addr)
7873 {
7874 if (memend <= p->endaddr)
7875 {
7876 /* Entire transfer is within this section. */
7877 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7878 xfered_len);
7879 }
7880 else if (memaddr >= p->endaddr)
7881 {
7882 /* This section ends before the transfer starts. */
7883 continue;
7884 }
7885 else
7886 {
7887 /* This section overlaps the transfer. Just do half. */
7888 len = p->endaddr - memaddr;
7889 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7890 xfered_len);
7891 }
7892 }
7893 }
7894 }
7895
7896 return TARGET_XFER_EOF;
7897 }
7898
7899 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7900 first if the requested memory is unavailable in traceframe.
7901 Otherwise, fall back to remote_read_bytes_1. */
7902
7903 static enum target_xfer_status
7904 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7905 gdb_byte *myaddr, ULONGEST len, int unit_size,
7906 ULONGEST *xfered_len)
7907 {
7908 if (len == 0)
7909 return TARGET_XFER_EOF;
7910
7911 if (get_traceframe_number () != -1)
7912 {
7913 VEC(mem_range_s) *available;
7914
7915 /* If we fail to get the set of available memory, then the
7916 target does not support querying traceframe info, and so we
7917 attempt reading from the traceframe anyway (assuming the
7918 target implements the old QTro packet then). */
7919 if (traceframe_available_memory (&available, memaddr, len))
7920 {
7921 struct cleanup *old_chain;
7922
7923 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7924
7925 if (VEC_empty (mem_range_s, available)
7926 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7927 {
7928 enum target_xfer_status res;
7929
7930 /* Don't read into the traceframe's available
7931 memory. */
7932 if (!VEC_empty (mem_range_s, available))
7933 {
7934 LONGEST oldlen = len;
7935
7936 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7937 gdb_assert (len <= oldlen);
7938 }
7939
7940 do_cleanups (old_chain);
7941
7942 /* This goes through the topmost target again. */
7943 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7944 len, unit_size, xfered_len);
7945 if (res == TARGET_XFER_OK)
7946 return TARGET_XFER_OK;
7947 else
7948 {
7949 /* No use trying further, we know some memory starting
7950 at MEMADDR isn't available. */
7951 *xfered_len = len;
7952 return TARGET_XFER_UNAVAILABLE;
7953 }
7954 }
7955
7956 /* Don't try to read more than how much is available, in
7957 case the target implements the deprecated QTro packet to
7958 cater for older GDBs (the target's knowledge of read-only
7959 sections may be outdated by now). */
7960 len = VEC_index (mem_range_s, available, 0)->length;
7961
7962 do_cleanups (old_chain);
7963 }
7964 }
7965
7966 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7967 }
7968
7969 \f
7970
7971 /* Sends a packet with content determined by the printf format string
7972 FORMAT and the remaining arguments, then gets the reply. Returns
7973 whether the packet was a success, a failure, or unknown. */
7974
7975 static enum packet_result remote_send_printf (const char *format, ...)
7976 ATTRIBUTE_PRINTF (1, 2);
7977
7978 static enum packet_result
7979 remote_send_printf (const char *format, ...)
7980 {
7981 struct remote_state *rs = get_remote_state ();
7982 int max_size = get_remote_packet_size ();
7983 va_list ap;
7984
7985 va_start (ap, format);
7986
7987 rs->buf[0] = '\0';
7988 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7989 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7990
7991 if (putpkt (rs->buf) < 0)
7992 error (_("Communication problem with target."));
7993
7994 rs->buf[0] = '\0';
7995 getpkt (&rs->buf, &rs->buf_size, 0);
7996
7997 return packet_check_result (rs->buf);
7998 }
7999
8000 static void
8001 restore_remote_timeout (void *p)
8002 {
8003 int value = *(int *)p;
8004
8005 remote_timeout = value;
8006 }
8007
8008 /* Flash writing can take quite some time. We'll set
8009 effectively infinite timeout for flash operations.
8010 In future, we'll need to decide on a better approach. */
8011 static const int remote_flash_timeout = 1000;
8012
8013 static void
8014 remote_flash_erase (struct target_ops *ops,
8015 ULONGEST address, LONGEST length)
8016 {
8017 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8018 int saved_remote_timeout = remote_timeout;
8019 enum packet_result ret;
8020 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8021 &saved_remote_timeout);
8022
8023 remote_timeout = remote_flash_timeout;
8024
8025 ret = remote_send_printf ("vFlashErase:%s,%s",
8026 phex (address, addr_size),
8027 phex (length, 4));
8028 switch (ret)
8029 {
8030 case PACKET_UNKNOWN:
8031 error (_("Remote target does not support flash erase"));
8032 case PACKET_ERROR:
8033 error (_("Error erasing flash with vFlashErase packet"));
8034 default:
8035 break;
8036 }
8037
8038 do_cleanups (back_to);
8039 }
8040
8041 static enum target_xfer_status
8042 remote_flash_write (struct target_ops *ops, ULONGEST address,
8043 ULONGEST length, ULONGEST *xfered_len,
8044 const gdb_byte *data)
8045 {
8046 int saved_remote_timeout = remote_timeout;
8047 enum target_xfer_status ret;
8048 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8049 &saved_remote_timeout);
8050
8051 remote_timeout = remote_flash_timeout;
8052 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8053 xfered_len,'X', 0);
8054 do_cleanups (back_to);
8055
8056 return ret;
8057 }
8058
8059 static void
8060 remote_flash_done (struct target_ops *ops)
8061 {
8062 int saved_remote_timeout = remote_timeout;
8063 int ret;
8064 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8065 &saved_remote_timeout);
8066
8067 remote_timeout = remote_flash_timeout;
8068 ret = remote_send_printf ("vFlashDone");
8069 do_cleanups (back_to);
8070
8071 switch (ret)
8072 {
8073 case PACKET_UNKNOWN:
8074 error (_("Remote target does not support vFlashDone"));
8075 case PACKET_ERROR:
8076 error (_("Error finishing flash operation"));
8077 default:
8078 break;
8079 }
8080 }
8081
8082 static void
8083 remote_files_info (struct target_ops *ignore)
8084 {
8085 puts_filtered ("Debugging a target over a serial line.\n");
8086 }
8087 \f
8088 /* Stuff for dealing with the packets which are part of this protocol.
8089 See comment at top of file for details. */
8090
8091 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8092 error to higher layers. Called when a serial error is detected.
8093 The exception message is STRING, followed by a colon and a blank,
8094 the system error message for errno at function entry and final dot
8095 for output compatibility with throw_perror_with_name. */
8096
8097 static void
8098 unpush_and_perror (const char *string)
8099 {
8100 int saved_errno = errno;
8101
8102 remote_unpush_target ();
8103 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8104 safe_strerror (saved_errno));
8105 }
8106
8107 /* Read a single character from the remote end. The current quit
8108 handler is overridden to avoid quitting in the middle of packet
8109 sequence, as that would break communication with the remote server.
8110 See remote_serial_quit_handler for more detail. */
8111
8112 static int
8113 readchar (int timeout)
8114 {
8115 int ch;
8116 struct remote_state *rs = get_remote_state ();
8117 struct cleanup *old_chain;
8118
8119 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8120
8121 rs->got_ctrlc_during_io = 0;
8122
8123 ch = serial_readchar (rs->remote_desc, timeout);
8124
8125 if (rs->got_ctrlc_during_io)
8126 set_quit_flag ();
8127
8128 do_cleanups (old_chain);
8129
8130 if (ch >= 0)
8131 return ch;
8132
8133 switch ((enum serial_rc) ch)
8134 {
8135 case SERIAL_EOF:
8136 remote_unpush_target ();
8137 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8138 /* no return */
8139 case SERIAL_ERROR:
8140 unpush_and_perror (_("Remote communication error. "
8141 "Target disconnected."));
8142 /* no return */
8143 case SERIAL_TIMEOUT:
8144 break;
8145 }
8146 return ch;
8147 }
8148
8149 /* Wrapper for serial_write that closes the target and throws if
8150 writing fails. The current quit handler is overridden to avoid
8151 quitting in the middle of packet sequence, as that would break
8152 communication with the remote server. See
8153 remote_serial_quit_handler for more detail. */
8154
8155 static void
8156 remote_serial_write (const char *str, int len)
8157 {
8158 struct remote_state *rs = get_remote_state ();
8159 struct cleanup *old_chain;
8160
8161 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8162
8163 rs->got_ctrlc_during_io = 0;
8164
8165 if (serial_write (rs->remote_desc, str, len))
8166 {
8167 unpush_and_perror (_("Remote communication error. "
8168 "Target disconnected."));
8169 }
8170
8171 if (rs->got_ctrlc_during_io)
8172 set_quit_flag ();
8173
8174 do_cleanups (old_chain);
8175 }
8176
8177 /* Send the command in *BUF to the remote machine, and read the reply
8178 into *BUF. Report an error if we get an error reply. Resize
8179 *BUF using xrealloc if necessary to hold the result, and update
8180 *SIZEOF_BUF. */
8181
8182 static void
8183 remote_send (char **buf,
8184 long *sizeof_buf)
8185 {
8186 putpkt (*buf);
8187 getpkt (buf, sizeof_buf, 0);
8188
8189 if ((*buf)[0] == 'E')
8190 error (_("Remote failure reply: %s"), *buf);
8191 }
8192
8193 /* Return a pointer to an xmalloc'ed string representing an escaped
8194 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8195 etc. The caller is responsible for releasing the returned
8196 memory. */
8197
8198 static char *
8199 escape_buffer (const char *buf, int n)
8200 {
8201 struct cleanup *old_chain;
8202 struct ui_file *stb;
8203 char *str;
8204
8205 stb = mem_fileopen ();
8206 old_chain = make_cleanup_ui_file_delete (stb);
8207
8208 fputstrn_unfiltered (buf, n, '\\', stb);
8209 str = ui_file_xstrdup (stb, NULL);
8210 do_cleanups (old_chain);
8211 return str;
8212 }
8213
8214 /* Display a null-terminated packet on stdout, for debugging, using C
8215 string notation. */
8216
8217 static void
8218 print_packet (const char *buf)
8219 {
8220 puts_filtered ("\"");
8221 fputstr_filtered (buf, '"', gdb_stdout);
8222 puts_filtered ("\"");
8223 }
8224
8225 int
8226 putpkt (const char *buf)
8227 {
8228 return putpkt_binary (buf, strlen (buf));
8229 }
8230
8231 /* Send a packet to the remote machine, with error checking. The data
8232 of the packet is in BUF. The string in BUF can be at most
8233 get_remote_packet_size () - 5 to account for the $, # and checksum,
8234 and for a possible /0 if we are debugging (remote_debug) and want
8235 to print the sent packet as a string. */
8236
8237 static int
8238 putpkt_binary (const char *buf, int cnt)
8239 {
8240 struct remote_state *rs = get_remote_state ();
8241 int i;
8242 unsigned char csum = 0;
8243 char *buf2 = (char *) xmalloc (cnt + 6);
8244 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8245
8246 int ch;
8247 int tcount = 0;
8248 char *p;
8249
8250 /* Catch cases like trying to read memory or listing threads while
8251 we're waiting for a stop reply. The remote server wouldn't be
8252 ready to handle this request, so we'd hang and timeout. We don't
8253 have to worry about this in synchronous mode, because in that
8254 case it's not possible to issue a command while the target is
8255 running. This is not a problem in non-stop mode, because in that
8256 case, the stub is always ready to process serial input. */
8257 if (!target_is_non_stop_p ()
8258 && target_is_async_p ()
8259 && rs->waiting_for_stop_reply)
8260 {
8261 error (_("Cannot execute this command while the target is running.\n"
8262 "Use the \"interrupt\" command to stop the target\n"
8263 "and then try again."));
8264 }
8265
8266 /* We're sending out a new packet. Make sure we don't look at a
8267 stale cached response. */
8268 rs->cached_wait_status = 0;
8269
8270 /* Copy the packet into buffer BUF2, encapsulating it
8271 and giving it a checksum. */
8272
8273 p = buf2;
8274 *p++ = '$';
8275
8276 for (i = 0; i < cnt; i++)
8277 {
8278 csum += buf[i];
8279 *p++ = buf[i];
8280 }
8281 *p++ = '#';
8282 *p++ = tohex ((csum >> 4) & 0xf);
8283 *p++ = tohex (csum & 0xf);
8284
8285 /* Send it over and over until we get a positive ack. */
8286
8287 while (1)
8288 {
8289 int started_error_output = 0;
8290
8291 if (remote_debug)
8292 {
8293 struct cleanup *old_chain;
8294 char *str;
8295
8296 *p = '\0';
8297 str = escape_buffer (buf2, p - buf2);
8298 old_chain = make_cleanup (xfree, str);
8299 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8300 gdb_flush (gdb_stdlog);
8301 do_cleanups (old_chain);
8302 }
8303 remote_serial_write (buf2, p - buf2);
8304
8305 /* If this is a no acks version of the remote protocol, send the
8306 packet and move on. */
8307 if (rs->noack_mode)
8308 break;
8309
8310 /* Read until either a timeout occurs (-2) or '+' is read.
8311 Handle any notification that arrives in the mean time. */
8312 while (1)
8313 {
8314 ch = readchar (remote_timeout);
8315
8316 if (remote_debug)
8317 {
8318 switch (ch)
8319 {
8320 case '+':
8321 case '-':
8322 case SERIAL_TIMEOUT:
8323 case '$':
8324 case '%':
8325 if (started_error_output)
8326 {
8327 putchar_unfiltered ('\n');
8328 started_error_output = 0;
8329 }
8330 }
8331 }
8332
8333 switch (ch)
8334 {
8335 case '+':
8336 if (remote_debug)
8337 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8338 do_cleanups (old_chain);
8339 return 1;
8340 case '-':
8341 if (remote_debug)
8342 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8343 /* FALLTHROUGH */
8344 case SERIAL_TIMEOUT:
8345 tcount++;
8346 if (tcount > 3)
8347 {
8348 do_cleanups (old_chain);
8349 return 0;
8350 }
8351 break; /* Retransmit buffer. */
8352 case '$':
8353 {
8354 if (remote_debug)
8355 fprintf_unfiltered (gdb_stdlog,
8356 "Packet instead of Ack, ignoring it\n");
8357 /* It's probably an old response sent because an ACK
8358 was lost. Gobble up the packet and ack it so it
8359 doesn't get retransmitted when we resend this
8360 packet. */
8361 skip_frame ();
8362 remote_serial_write ("+", 1);
8363 continue; /* Now, go look for +. */
8364 }
8365
8366 case '%':
8367 {
8368 int val;
8369
8370 /* If we got a notification, handle it, and go back to looking
8371 for an ack. */
8372 /* We've found the start of a notification. Now
8373 collect the data. */
8374 val = read_frame (&rs->buf, &rs->buf_size);
8375 if (val >= 0)
8376 {
8377 if (remote_debug)
8378 {
8379 struct cleanup *old_chain;
8380 char *str;
8381
8382 str = escape_buffer (rs->buf, val);
8383 old_chain = make_cleanup (xfree, str);
8384 fprintf_unfiltered (gdb_stdlog,
8385 " Notification received: %s\n",
8386 str);
8387 do_cleanups (old_chain);
8388 }
8389 handle_notification (rs->notif_state, rs->buf);
8390 /* We're in sync now, rewait for the ack. */
8391 tcount = 0;
8392 }
8393 else
8394 {
8395 if (remote_debug)
8396 {
8397 if (!started_error_output)
8398 {
8399 started_error_output = 1;
8400 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8401 }
8402 fputc_unfiltered (ch & 0177, gdb_stdlog);
8403 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8404 }
8405 }
8406 continue;
8407 }
8408 /* fall-through */
8409 default:
8410 if (remote_debug)
8411 {
8412 if (!started_error_output)
8413 {
8414 started_error_output = 1;
8415 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8416 }
8417 fputc_unfiltered (ch & 0177, gdb_stdlog);
8418 }
8419 continue;
8420 }
8421 break; /* Here to retransmit. */
8422 }
8423
8424 #if 0
8425 /* This is wrong. If doing a long backtrace, the user should be
8426 able to get out next time we call QUIT, without anything as
8427 violent as interrupt_query. If we want to provide a way out of
8428 here without getting to the next QUIT, it should be based on
8429 hitting ^C twice as in remote_wait. */
8430 if (quit_flag)
8431 {
8432 quit_flag = 0;
8433 interrupt_query ();
8434 }
8435 #endif
8436 }
8437
8438 do_cleanups (old_chain);
8439 return 0;
8440 }
8441
8442 /* Come here after finding the start of a frame when we expected an
8443 ack. Do our best to discard the rest of this packet. */
8444
8445 static void
8446 skip_frame (void)
8447 {
8448 int c;
8449
8450 while (1)
8451 {
8452 c = readchar (remote_timeout);
8453 switch (c)
8454 {
8455 case SERIAL_TIMEOUT:
8456 /* Nothing we can do. */
8457 return;
8458 case '#':
8459 /* Discard the two bytes of checksum and stop. */
8460 c = readchar (remote_timeout);
8461 if (c >= 0)
8462 c = readchar (remote_timeout);
8463
8464 return;
8465 case '*': /* Run length encoding. */
8466 /* Discard the repeat count. */
8467 c = readchar (remote_timeout);
8468 if (c < 0)
8469 return;
8470 break;
8471 default:
8472 /* A regular character. */
8473 break;
8474 }
8475 }
8476 }
8477
8478 /* Come here after finding the start of the frame. Collect the rest
8479 into *BUF, verifying the checksum, length, and handling run-length
8480 compression. NUL terminate the buffer. If there is not enough room,
8481 expand *BUF using xrealloc.
8482
8483 Returns -1 on error, number of characters in buffer (ignoring the
8484 trailing NULL) on success. (could be extended to return one of the
8485 SERIAL status indications). */
8486
8487 static long
8488 read_frame (char **buf_p,
8489 long *sizeof_buf)
8490 {
8491 unsigned char csum;
8492 long bc;
8493 int c;
8494 char *buf = *buf_p;
8495 struct remote_state *rs = get_remote_state ();
8496
8497 csum = 0;
8498 bc = 0;
8499
8500 while (1)
8501 {
8502 c = readchar (remote_timeout);
8503 switch (c)
8504 {
8505 case SERIAL_TIMEOUT:
8506 if (remote_debug)
8507 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8508 return -1;
8509 case '$':
8510 if (remote_debug)
8511 fputs_filtered ("Saw new packet start in middle of old one\n",
8512 gdb_stdlog);
8513 return -1; /* Start a new packet, count retries. */
8514 case '#':
8515 {
8516 unsigned char pktcsum;
8517 int check_0 = 0;
8518 int check_1 = 0;
8519
8520 buf[bc] = '\0';
8521
8522 check_0 = readchar (remote_timeout);
8523 if (check_0 >= 0)
8524 check_1 = readchar (remote_timeout);
8525
8526 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8527 {
8528 if (remote_debug)
8529 fputs_filtered ("Timeout in checksum, retrying\n",
8530 gdb_stdlog);
8531 return -1;
8532 }
8533 else if (check_0 < 0 || check_1 < 0)
8534 {
8535 if (remote_debug)
8536 fputs_filtered ("Communication error in checksum\n",
8537 gdb_stdlog);
8538 return -1;
8539 }
8540
8541 /* Don't recompute the checksum; with no ack packets we
8542 don't have any way to indicate a packet retransmission
8543 is necessary. */
8544 if (rs->noack_mode)
8545 return bc;
8546
8547 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8548 if (csum == pktcsum)
8549 return bc;
8550
8551 if (remote_debug)
8552 {
8553 struct cleanup *old_chain;
8554 char *str;
8555
8556 str = escape_buffer (buf, bc);
8557 old_chain = make_cleanup (xfree, str);
8558 fprintf_unfiltered (gdb_stdlog,
8559 "Bad checksum, sentsum=0x%x, "
8560 "csum=0x%x, buf=%s\n",
8561 pktcsum, csum, str);
8562 do_cleanups (old_chain);
8563 }
8564 /* Number of characters in buffer ignoring trailing
8565 NULL. */
8566 return -1;
8567 }
8568 case '*': /* Run length encoding. */
8569 {
8570 int repeat;
8571
8572 csum += c;
8573 c = readchar (remote_timeout);
8574 csum += c;
8575 repeat = c - ' ' + 3; /* Compute repeat count. */
8576
8577 /* The character before ``*'' is repeated. */
8578
8579 if (repeat > 0 && repeat <= 255 && bc > 0)
8580 {
8581 if (bc + repeat - 1 >= *sizeof_buf - 1)
8582 {
8583 /* Make some more room in the buffer. */
8584 *sizeof_buf += repeat;
8585 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8586 buf = *buf_p;
8587 }
8588
8589 memset (&buf[bc], buf[bc - 1], repeat);
8590 bc += repeat;
8591 continue;
8592 }
8593
8594 buf[bc] = '\0';
8595 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8596 return -1;
8597 }
8598 default:
8599 if (bc >= *sizeof_buf - 1)
8600 {
8601 /* Make some more room in the buffer. */
8602 *sizeof_buf *= 2;
8603 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8604 buf = *buf_p;
8605 }
8606
8607 buf[bc++] = c;
8608 csum += c;
8609 continue;
8610 }
8611 }
8612 }
8613
8614 /* Read a packet from the remote machine, with error checking, and
8615 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8616 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8617 rather than timing out; this is used (in synchronous mode) to wait
8618 for a target that is is executing user code to stop. */
8619 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8620 don't have to change all the calls to getpkt to deal with the
8621 return value, because at the moment I don't know what the right
8622 thing to do it for those. */
8623 void
8624 getpkt (char **buf,
8625 long *sizeof_buf,
8626 int forever)
8627 {
8628 getpkt_sane (buf, sizeof_buf, forever);
8629 }
8630
8631
8632 /* Read a packet from the remote machine, with error checking, and
8633 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8634 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8635 rather than timing out; this is used (in synchronous mode) to wait
8636 for a target that is is executing user code to stop. If FOREVER ==
8637 0, this function is allowed to time out gracefully and return an
8638 indication of this to the caller. Otherwise return the number of
8639 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8640 enough reason to return to the caller. *IS_NOTIF is an output
8641 boolean that indicates whether *BUF holds a notification or not
8642 (a regular packet). */
8643
8644 static int
8645 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8646 int expecting_notif, int *is_notif)
8647 {
8648 struct remote_state *rs = get_remote_state ();
8649 int c;
8650 int tries;
8651 int timeout;
8652 int val = -1;
8653
8654 /* We're reading a new response. Make sure we don't look at a
8655 previously cached response. */
8656 rs->cached_wait_status = 0;
8657
8658 strcpy (*buf, "timeout");
8659
8660 if (forever)
8661 timeout = watchdog > 0 ? watchdog : -1;
8662 else if (expecting_notif)
8663 timeout = 0; /* There should already be a char in the buffer. If
8664 not, bail out. */
8665 else
8666 timeout = remote_timeout;
8667
8668 #define MAX_TRIES 3
8669
8670 /* Process any number of notifications, and then return when
8671 we get a packet. */
8672 for (;;)
8673 {
8674 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8675 times. */
8676 for (tries = 1; tries <= MAX_TRIES; tries++)
8677 {
8678 /* This can loop forever if the remote side sends us
8679 characters continuously, but if it pauses, we'll get
8680 SERIAL_TIMEOUT from readchar because of timeout. Then
8681 we'll count that as a retry.
8682
8683 Note that even when forever is set, we will only wait
8684 forever prior to the start of a packet. After that, we
8685 expect characters to arrive at a brisk pace. They should
8686 show up within remote_timeout intervals. */
8687 do
8688 c = readchar (timeout);
8689 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8690
8691 if (c == SERIAL_TIMEOUT)
8692 {
8693 if (expecting_notif)
8694 return -1; /* Don't complain, it's normal to not get
8695 anything in this case. */
8696
8697 if (forever) /* Watchdog went off? Kill the target. */
8698 {
8699 remote_unpush_target ();
8700 throw_error (TARGET_CLOSE_ERROR,
8701 _("Watchdog timeout has expired. "
8702 "Target detached."));
8703 }
8704 if (remote_debug)
8705 fputs_filtered ("Timed out.\n", gdb_stdlog);
8706 }
8707 else
8708 {
8709 /* We've found the start of a packet or notification.
8710 Now collect the data. */
8711 val = read_frame (buf, sizeof_buf);
8712 if (val >= 0)
8713 break;
8714 }
8715
8716 remote_serial_write ("-", 1);
8717 }
8718
8719 if (tries > MAX_TRIES)
8720 {
8721 /* We have tried hard enough, and just can't receive the
8722 packet/notification. Give up. */
8723 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8724
8725 /* Skip the ack char if we're in no-ack mode. */
8726 if (!rs->noack_mode)
8727 remote_serial_write ("+", 1);
8728 return -1;
8729 }
8730
8731 /* If we got an ordinary packet, return that to our caller. */
8732 if (c == '$')
8733 {
8734 if (remote_debug)
8735 {
8736 struct cleanup *old_chain;
8737 char *str;
8738
8739 str = escape_buffer (*buf, val);
8740 old_chain = make_cleanup (xfree, str);
8741 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8742 do_cleanups (old_chain);
8743 }
8744
8745 /* Skip the ack char if we're in no-ack mode. */
8746 if (!rs->noack_mode)
8747 remote_serial_write ("+", 1);
8748 if (is_notif != NULL)
8749 *is_notif = 0;
8750 return val;
8751 }
8752
8753 /* If we got a notification, handle it, and go back to looking
8754 for a packet. */
8755 else
8756 {
8757 gdb_assert (c == '%');
8758
8759 if (remote_debug)
8760 {
8761 struct cleanup *old_chain;
8762 char *str;
8763
8764 str = escape_buffer (*buf, val);
8765 old_chain = make_cleanup (xfree, str);
8766 fprintf_unfiltered (gdb_stdlog,
8767 " Notification received: %s\n",
8768 str);
8769 do_cleanups (old_chain);
8770 }
8771 if (is_notif != NULL)
8772 *is_notif = 1;
8773
8774 handle_notification (rs->notif_state, *buf);
8775
8776 /* Notifications require no acknowledgement. */
8777
8778 if (expecting_notif)
8779 return val;
8780 }
8781 }
8782 }
8783
8784 static int
8785 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8786 {
8787 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8788 }
8789
8790 static int
8791 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8792 int *is_notif)
8793 {
8794 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8795 is_notif);
8796 }
8797
8798 /* Check whether EVENT is a fork event for the process specified
8799 by the pid passed in DATA, and if it is, kill the fork child. */
8800
8801 static int
8802 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8803 QUEUE_ITER (stop_reply_p) *iter,
8804 stop_reply_p event,
8805 void *data)
8806 {
8807 struct queue_iter_param *param = (struct queue_iter_param *) data;
8808 int parent_pid = *(int *) param->input;
8809
8810 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8811 {
8812 struct remote_state *rs = get_remote_state ();
8813 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8814 int res;
8815
8816 res = remote_vkill (child_pid, rs);
8817 if (res != 0)
8818 error (_("Can't kill fork child process %d"), child_pid);
8819 }
8820
8821 return 1;
8822 }
8823
8824 /* Kill any new fork children of process PID that haven't been
8825 processed by follow_fork. */
8826
8827 static void
8828 kill_new_fork_children (int pid, struct remote_state *rs)
8829 {
8830 struct thread_info *thread;
8831 struct notif_client *notif = &notif_client_stop;
8832 struct queue_iter_param param;
8833
8834 /* Kill the fork child threads of any threads in process PID
8835 that are stopped at a fork event. */
8836 ALL_NON_EXITED_THREADS (thread)
8837 {
8838 struct target_waitstatus *ws = &thread->pending_follow;
8839
8840 if (is_pending_fork_parent (ws, pid, thread->ptid))
8841 {
8842 struct remote_state *rs = get_remote_state ();
8843 int child_pid = ptid_get_pid (ws->value.related_pid);
8844 int res;
8845
8846 res = remote_vkill (child_pid, rs);
8847 if (res != 0)
8848 error (_("Can't kill fork child process %d"), child_pid);
8849 }
8850 }
8851
8852 /* Check for any pending fork events (not reported or processed yet)
8853 in process PID and kill those fork child threads as well. */
8854 remote_notif_get_pending_events (notif);
8855 param.input = &pid;
8856 param.output = NULL;
8857 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8858 kill_child_of_pending_fork, &param);
8859 }
8860
8861 \f
8862 /* Target hook to kill the current inferior. */
8863
8864 static void
8865 remote_kill (struct target_ops *ops)
8866 {
8867 int res = -1;
8868 int pid = ptid_get_pid (inferior_ptid);
8869 struct remote_state *rs = get_remote_state ();
8870
8871 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
8872 {
8873 /* If we're stopped while forking and we haven't followed yet,
8874 kill the child task. We need to do this before killing the
8875 parent task because if this is a vfork then the parent will
8876 be sleeping. */
8877 kill_new_fork_children (pid, rs);
8878
8879 res = remote_vkill (pid, rs);
8880 if (res == 0)
8881 {
8882 target_mourn_inferior ();
8883 return;
8884 }
8885 }
8886
8887 /* If we are in 'target remote' mode and we are killing the only
8888 inferior, then we will tell gdbserver to exit and unpush the
8889 target. */
8890 if (res == -1 && !remote_multi_process_p (rs)
8891 && number_of_live_inferiors () == 1)
8892 {
8893 remote_kill_k ();
8894
8895 /* We've killed the remote end, we get to mourn it. If we are
8896 not in extended mode, mourning the inferior also unpushes
8897 remote_ops from the target stack, which closes the remote
8898 connection. */
8899 target_mourn_inferior ();
8900
8901 return;
8902 }
8903
8904 error (_("Can't kill process"));
8905 }
8906
8907 /* Send a kill request to the target using the 'vKill' packet. */
8908
8909 static int
8910 remote_vkill (int pid, struct remote_state *rs)
8911 {
8912 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8913 return -1;
8914
8915 /* Tell the remote target to detach. */
8916 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8917 putpkt (rs->buf);
8918 getpkt (&rs->buf, &rs->buf_size, 0);
8919
8920 switch (packet_ok (rs->buf,
8921 &remote_protocol_packets[PACKET_vKill]))
8922 {
8923 case PACKET_OK:
8924 return 0;
8925 case PACKET_ERROR:
8926 return 1;
8927 case PACKET_UNKNOWN:
8928 return -1;
8929 default:
8930 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8931 }
8932 }
8933
8934 /* Send a kill request to the target using the 'k' packet. */
8935
8936 static void
8937 remote_kill_k (void)
8938 {
8939 /* Catch errors so the user can quit from gdb even when we
8940 aren't on speaking terms with the remote system. */
8941 TRY
8942 {
8943 putpkt ("k");
8944 }
8945 CATCH (ex, RETURN_MASK_ERROR)
8946 {
8947 if (ex.error == TARGET_CLOSE_ERROR)
8948 {
8949 /* If we got an (EOF) error that caused the target
8950 to go away, then we're done, that's what we wanted.
8951 "k" is susceptible to cause a premature EOF, given
8952 that the remote server isn't actually required to
8953 reply to "k", and it can happen that it doesn't
8954 even get to reply ACK to the "k". */
8955 return;
8956 }
8957
8958 /* Otherwise, something went wrong. We didn't actually kill
8959 the target. Just propagate the exception, and let the
8960 user or higher layers decide what to do. */
8961 throw_exception (ex);
8962 }
8963 END_CATCH
8964 }
8965
8966 static void
8967 remote_mourn (struct target_ops *target)
8968 {
8969 struct remote_state *rs = get_remote_state ();
8970
8971 /* In 'target remote' mode with one inferior, we close the connection. */
8972 if (!rs->extended && number_of_live_inferiors () <= 1)
8973 {
8974 unpush_target (target);
8975
8976 /* remote_close takes care of doing most of the clean up. */
8977 generic_mourn_inferior ();
8978 return;
8979 }
8980
8981 /* In case we got here due to an error, but we're going to stay
8982 connected. */
8983 rs->waiting_for_stop_reply = 0;
8984
8985 /* If the current general thread belonged to the process we just
8986 detached from or has exited, the remote side current general
8987 thread becomes undefined. Considering a case like this:
8988
8989 - We just got here due to a detach.
8990 - The process that we're detaching from happens to immediately
8991 report a global breakpoint being hit in non-stop mode, in the
8992 same thread we had selected before.
8993 - GDB attaches to this process again.
8994 - This event happens to be the next event we handle.
8995
8996 GDB would consider that the current general thread didn't need to
8997 be set on the stub side (with Hg), since for all it knew,
8998 GENERAL_THREAD hadn't changed.
8999
9000 Notice that although in all-stop mode, the remote server always
9001 sets the current thread to the thread reporting the stop event,
9002 that doesn't happen in non-stop mode; in non-stop, the stub *must
9003 not* change the current thread when reporting a breakpoint hit,
9004 due to the decoupling of event reporting and event handling.
9005
9006 To keep things simple, we always invalidate our notion of the
9007 current thread. */
9008 record_currthread (rs, minus_one_ptid);
9009
9010 /* Call common code to mark the inferior as not running. */
9011 generic_mourn_inferior ();
9012
9013 if (!have_inferiors ())
9014 {
9015 if (!remote_multi_process_p (rs))
9016 {
9017 /* Check whether the target is running now - some remote stubs
9018 automatically restart after kill. */
9019 putpkt ("?");
9020 getpkt (&rs->buf, &rs->buf_size, 0);
9021
9022 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9023 {
9024 /* Assume that the target has been restarted. Set
9025 inferior_ptid so that bits of core GDB realizes
9026 there's something here, e.g., so that the user can
9027 say "kill" again. */
9028 inferior_ptid = magic_null_ptid;
9029 }
9030 }
9031 }
9032 }
9033
9034 static int
9035 extended_remote_supports_disable_randomization (struct target_ops *self)
9036 {
9037 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9038 }
9039
9040 static void
9041 extended_remote_disable_randomization (int val)
9042 {
9043 struct remote_state *rs = get_remote_state ();
9044 char *reply;
9045
9046 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9047 val);
9048 putpkt (rs->buf);
9049 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9050 if (*reply == '\0')
9051 error (_("Target does not support QDisableRandomization."));
9052 if (strcmp (reply, "OK") != 0)
9053 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9054 }
9055
9056 static int
9057 extended_remote_run (char *args)
9058 {
9059 struct remote_state *rs = get_remote_state ();
9060 int len;
9061 const char *remote_exec_file = get_remote_exec_file ();
9062
9063 /* If the user has disabled vRun support, or we have detected that
9064 support is not available, do not try it. */
9065 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9066 return -1;
9067
9068 strcpy (rs->buf, "vRun;");
9069 len = strlen (rs->buf);
9070
9071 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9072 error (_("Remote file name too long for run packet"));
9073 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9074 strlen (remote_exec_file));
9075
9076 gdb_assert (args != NULL);
9077 if (*args)
9078 {
9079 struct cleanup *back_to;
9080 int i;
9081 char **argv;
9082
9083 argv = gdb_buildargv (args);
9084 back_to = make_cleanup_freeargv (argv);
9085 for (i = 0; argv[i] != NULL; i++)
9086 {
9087 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9088 error (_("Argument list too long for run packet"));
9089 rs->buf[len++] = ';';
9090 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9091 strlen (argv[i]));
9092 }
9093 do_cleanups (back_to);
9094 }
9095
9096 rs->buf[len++] = '\0';
9097
9098 putpkt (rs->buf);
9099 getpkt (&rs->buf, &rs->buf_size, 0);
9100
9101 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9102 {
9103 case PACKET_OK:
9104 /* We have a wait response. All is well. */
9105 return 0;
9106 case PACKET_UNKNOWN:
9107 return -1;
9108 case PACKET_ERROR:
9109 if (remote_exec_file[0] == '\0')
9110 error (_("Running the default executable on the remote target failed; "
9111 "try \"set remote exec-file\"?"));
9112 else
9113 error (_("Running \"%s\" on the remote target failed"),
9114 remote_exec_file);
9115 default:
9116 gdb_assert_not_reached (_("bad switch"));
9117 }
9118 }
9119
9120 /* In the extended protocol we want to be able to do things like
9121 "run" and have them basically work as expected. So we need
9122 a special create_inferior function. We support changing the
9123 executable file and the command line arguments, but not the
9124 environment. */
9125
9126 static void
9127 extended_remote_create_inferior (struct target_ops *ops,
9128 char *exec_file, char *args,
9129 char **env, int from_tty)
9130 {
9131 int run_worked;
9132 char *stop_reply;
9133 struct remote_state *rs = get_remote_state ();
9134 const char *remote_exec_file = get_remote_exec_file ();
9135
9136 /* If running asynchronously, register the target file descriptor
9137 with the event loop. */
9138 if (target_can_async_p ())
9139 target_async (1);
9140
9141 /* Disable address space randomization if requested (and supported). */
9142 if (extended_remote_supports_disable_randomization (ops))
9143 extended_remote_disable_randomization (disable_randomization);
9144
9145 /* Now restart the remote server. */
9146 run_worked = extended_remote_run (args) != -1;
9147 if (!run_worked)
9148 {
9149 /* vRun was not supported. Fail if we need it to do what the
9150 user requested. */
9151 if (remote_exec_file[0])
9152 error (_("Remote target does not support \"set remote exec-file\""));
9153 if (args[0])
9154 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9155
9156 /* Fall back to "R". */
9157 extended_remote_restart ();
9158 }
9159
9160 if (!have_inferiors ())
9161 {
9162 /* Clean up from the last time we ran, before we mark the target
9163 running again. This will mark breakpoints uninserted, and
9164 get_offsets may insert breakpoints. */
9165 init_thread_list ();
9166 init_wait_for_inferior ();
9167 }
9168
9169 /* vRun's success return is a stop reply. */
9170 stop_reply = run_worked ? rs->buf : NULL;
9171 add_current_inferior_and_thread (stop_reply);
9172
9173 /* Get updated offsets, if the stub uses qOffsets. */
9174 get_offsets ();
9175 }
9176 \f
9177
9178 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9179 the list of conditions (in agent expression bytecode format), if any, the
9180 target needs to evaluate. The output is placed into the packet buffer
9181 started from BUF and ended at BUF_END. */
9182
9183 static int
9184 remote_add_target_side_condition (struct gdbarch *gdbarch,
9185 struct bp_target_info *bp_tgt, char *buf,
9186 char *buf_end)
9187 {
9188 struct agent_expr *aexpr = NULL;
9189 int i, ix;
9190
9191 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9192 return 0;
9193
9194 buf += strlen (buf);
9195 xsnprintf (buf, buf_end - buf, "%s", ";");
9196 buf++;
9197
9198 /* Send conditions to the target and free the vector. */
9199 for (ix = 0;
9200 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9201 ix++)
9202 {
9203 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9204 buf += strlen (buf);
9205 for (i = 0; i < aexpr->len; ++i)
9206 buf = pack_hex_byte (buf, aexpr->buf[i]);
9207 *buf = '\0';
9208 }
9209 return 0;
9210 }
9211
9212 static void
9213 remote_add_target_side_commands (struct gdbarch *gdbarch,
9214 struct bp_target_info *bp_tgt, char *buf)
9215 {
9216 struct agent_expr *aexpr = NULL;
9217 int i, ix;
9218
9219 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9220 return;
9221
9222 buf += strlen (buf);
9223
9224 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9225 buf += strlen (buf);
9226
9227 /* Concatenate all the agent expressions that are commands into the
9228 cmds parameter. */
9229 for (ix = 0;
9230 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9231 ix++)
9232 {
9233 sprintf (buf, "X%x,", aexpr->len);
9234 buf += strlen (buf);
9235 for (i = 0; i < aexpr->len; ++i)
9236 buf = pack_hex_byte (buf, aexpr->buf[i]);
9237 *buf = '\0';
9238 }
9239 }
9240
9241 /* Insert a breakpoint. On targets that have software breakpoint
9242 support, we ask the remote target to do the work; on targets
9243 which don't, we insert a traditional memory breakpoint. */
9244
9245 static int
9246 remote_insert_breakpoint (struct target_ops *ops,
9247 struct gdbarch *gdbarch,
9248 struct bp_target_info *bp_tgt)
9249 {
9250 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9251 If it succeeds, then set the support to PACKET_ENABLE. If it
9252 fails, and the user has explicitly requested the Z support then
9253 report an error, otherwise, mark it disabled and go on. */
9254
9255 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9256 {
9257 CORE_ADDR addr = bp_tgt->reqstd_address;
9258 struct remote_state *rs;
9259 char *p, *endbuf;
9260 int bpsize;
9261
9262 /* Make sure the remote is pointing at the right process, if
9263 necessary. */
9264 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9265 set_general_process ();
9266
9267 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9268
9269 rs = get_remote_state ();
9270 p = rs->buf;
9271 endbuf = rs->buf + get_remote_packet_size ();
9272
9273 *(p++) = 'Z';
9274 *(p++) = '0';
9275 *(p++) = ',';
9276 addr = (ULONGEST) remote_address_masked (addr);
9277 p += hexnumstr (p, addr);
9278 xsnprintf (p, endbuf - p, ",%d", bpsize);
9279
9280 if (remote_supports_cond_breakpoints (ops))
9281 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9282
9283 if (remote_can_run_breakpoint_commands (ops))
9284 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9285
9286 putpkt (rs->buf);
9287 getpkt (&rs->buf, &rs->buf_size, 0);
9288
9289 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9290 {
9291 case PACKET_ERROR:
9292 return -1;
9293 case PACKET_OK:
9294 bp_tgt->placed_address = addr;
9295 bp_tgt->placed_size = bpsize;
9296 return 0;
9297 case PACKET_UNKNOWN:
9298 break;
9299 }
9300 }
9301
9302 /* If this breakpoint has target-side commands but this stub doesn't
9303 support Z0 packets, throw error. */
9304 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9305 throw_error (NOT_SUPPORTED_ERROR, _("\
9306 Target doesn't support breakpoints that have target side commands."));
9307
9308 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9309 }
9310
9311 static int
9312 remote_remove_breakpoint (struct target_ops *ops,
9313 struct gdbarch *gdbarch,
9314 struct bp_target_info *bp_tgt)
9315 {
9316 CORE_ADDR addr = bp_tgt->placed_address;
9317 struct remote_state *rs = get_remote_state ();
9318
9319 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9320 {
9321 char *p = rs->buf;
9322 char *endbuf = rs->buf + get_remote_packet_size ();
9323
9324 /* Make sure the remote is pointing at the right process, if
9325 necessary. */
9326 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9327 set_general_process ();
9328
9329 *(p++) = 'z';
9330 *(p++) = '0';
9331 *(p++) = ',';
9332
9333 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9334 p += hexnumstr (p, addr);
9335 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9336
9337 putpkt (rs->buf);
9338 getpkt (&rs->buf, &rs->buf_size, 0);
9339
9340 return (rs->buf[0] == 'E');
9341 }
9342
9343 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9344 }
9345
9346 static enum Z_packet_type
9347 watchpoint_to_Z_packet (int type)
9348 {
9349 switch (type)
9350 {
9351 case hw_write:
9352 return Z_PACKET_WRITE_WP;
9353 break;
9354 case hw_read:
9355 return Z_PACKET_READ_WP;
9356 break;
9357 case hw_access:
9358 return Z_PACKET_ACCESS_WP;
9359 break;
9360 default:
9361 internal_error (__FILE__, __LINE__,
9362 _("hw_bp_to_z: bad watchpoint type %d"), type);
9363 }
9364 }
9365
9366 static int
9367 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9368 enum target_hw_bp_type type, struct expression *cond)
9369 {
9370 struct remote_state *rs = get_remote_state ();
9371 char *endbuf = rs->buf + get_remote_packet_size ();
9372 char *p;
9373 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9374
9375 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9376 return 1;
9377
9378 /* Make sure the remote is pointing at the right process, if
9379 necessary. */
9380 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9381 set_general_process ();
9382
9383 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9384 p = strchr (rs->buf, '\0');
9385 addr = remote_address_masked (addr);
9386 p += hexnumstr (p, (ULONGEST) addr);
9387 xsnprintf (p, endbuf - p, ",%x", len);
9388
9389 putpkt (rs->buf);
9390 getpkt (&rs->buf, &rs->buf_size, 0);
9391
9392 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9393 {
9394 case PACKET_ERROR:
9395 return -1;
9396 case PACKET_UNKNOWN:
9397 return 1;
9398 case PACKET_OK:
9399 return 0;
9400 }
9401 internal_error (__FILE__, __LINE__,
9402 _("remote_insert_watchpoint: reached end of function"));
9403 }
9404
9405 static int
9406 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9407 CORE_ADDR start, int length)
9408 {
9409 CORE_ADDR diff = remote_address_masked (addr - start);
9410
9411 return diff < length;
9412 }
9413
9414
9415 static int
9416 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9417 enum target_hw_bp_type type, struct expression *cond)
9418 {
9419 struct remote_state *rs = get_remote_state ();
9420 char *endbuf = rs->buf + get_remote_packet_size ();
9421 char *p;
9422 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9423
9424 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9425 return -1;
9426
9427 /* Make sure the remote is pointing at the right process, if
9428 necessary. */
9429 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9430 set_general_process ();
9431
9432 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9433 p = strchr (rs->buf, '\0');
9434 addr = remote_address_masked (addr);
9435 p += hexnumstr (p, (ULONGEST) addr);
9436 xsnprintf (p, endbuf - p, ",%x", len);
9437 putpkt (rs->buf);
9438 getpkt (&rs->buf, &rs->buf_size, 0);
9439
9440 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9441 {
9442 case PACKET_ERROR:
9443 case PACKET_UNKNOWN:
9444 return -1;
9445 case PACKET_OK:
9446 return 0;
9447 }
9448 internal_error (__FILE__, __LINE__,
9449 _("remote_remove_watchpoint: reached end of function"));
9450 }
9451
9452
9453 int remote_hw_watchpoint_limit = -1;
9454 int remote_hw_watchpoint_length_limit = -1;
9455 int remote_hw_breakpoint_limit = -1;
9456
9457 static int
9458 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9459 CORE_ADDR addr, int len)
9460 {
9461 if (remote_hw_watchpoint_length_limit == 0)
9462 return 0;
9463 else if (remote_hw_watchpoint_length_limit < 0)
9464 return 1;
9465 else if (len <= remote_hw_watchpoint_length_limit)
9466 return 1;
9467 else
9468 return 0;
9469 }
9470
9471 static int
9472 remote_check_watch_resources (struct target_ops *self,
9473 enum bptype type, int cnt, int ot)
9474 {
9475 if (type == bp_hardware_breakpoint)
9476 {
9477 if (remote_hw_breakpoint_limit == 0)
9478 return 0;
9479 else if (remote_hw_breakpoint_limit < 0)
9480 return 1;
9481 else if (cnt <= remote_hw_breakpoint_limit)
9482 return 1;
9483 }
9484 else
9485 {
9486 if (remote_hw_watchpoint_limit == 0)
9487 return 0;
9488 else if (remote_hw_watchpoint_limit < 0)
9489 return 1;
9490 else if (ot)
9491 return -1;
9492 else if (cnt <= remote_hw_watchpoint_limit)
9493 return 1;
9494 }
9495 return -1;
9496 }
9497
9498 /* The to_stopped_by_sw_breakpoint method of target remote. */
9499
9500 static int
9501 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9502 {
9503 struct thread_info *thread = inferior_thread ();
9504
9505 return (thread->priv != NULL
9506 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9507 }
9508
9509 /* The to_supports_stopped_by_sw_breakpoint method of target
9510 remote. */
9511
9512 static int
9513 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9514 {
9515 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9516 }
9517
9518 /* The to_stopped_by_hw_breakpoint method of target remote. */
9519
9520 static int
9521 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9522 {
9523 struct thread_info *thread = inferior_thread ();
9524
9525 return (thread->priv != NULL
9526 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9527 }
9528
9529 /* The to_supports_stopped_by_hw_breakpoint method of target
9530 remote. */
9531
9532 static int
9533 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9534 {
9535 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9536 }
9537
9538 static int
9539 remote_stopped_by_watchpoint (struct target_ops *ops)
9540 {
9541 struct thread_info *thread = inferior_thread ();
9542
9543 return (thread->priv != NULL
9544 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9545 }
9546
9547 static int
9548 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9549 {
9550 struct thread_info *thread = inferior_thread ();
9551
9552 if (thread->priv != NULL
9553 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9554 {
9555 *addr_p = thread->priv->watch_data_address;
9556 return 1;
9557 }
9558
9559 return 0;
9560 }
9561
9562
9563 static int
9564 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9565 struct bp_target_info *bp_tgt)
9566 {
9567 CORE_ADDR addr = bp_tgt->reqstd_address;
9568 struct remote_state *rs;
9569 char *p, *endbuf;
9570 char *message;
9571 int bpsize;
9572
9573 /* The length field should be set to the size of a breakpoint
9574 instruction, even though we aren't inserting one ourselves. */
9575
9576 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9577
9578 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9579 return -1;
9580
9581 /* Make sure the remote is pointing at the right process, if
9582 necessary. */
9583 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9584 set_general_process ();
9585
9586 rs = get_remote_state ();
9587 p = rs->buf;
9588 endbuf = rs->buf + get_remote_packet_size ();
9589
9590 *(p++) = 'Z';
9591 *(p++) = '1';
9592 *(p++) = ',';
9593
9594 addr = remote_address_masked (addr);
9595 p += hexnumstr (p, (ULONGEST) addr);
9596 xsnprintf (p, endbuf - p, ",%x", bpsize);
9597
9598 if (remote_supports_cond_breakpoints (self))
9599 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9600
9601 if (remote_can_run_breakpoint_commands (self))
9602 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9603
9604 putpkt (rs->buf);
9605 getpkt (&rs->buf, &rs->buf_size, 0);
9606
9607 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9608 {
9609 case PACKET_ERROR:
9610 if (rs->buf[1] == '.')
9611 {
9612 message = strchr (rs->buf + 2, '.');
9613 if (message)
9614 error (_("Remote failure reply: %s"), message + 1);
9615 }
9616 return -1;
9617 case PACKET_UNKNOWN:
9618 return -1;
9619 case PACKET_OK:
9620 bp_tgt->placed_address = addr;
9621 bp_tgt->placed_size = bpsize;
9622 return 0;
9623 }
9624 internal_error (__FILE__, __LINE__,
9625 _("remote_insert_hw_breakpoint: reached end of function"));
9626 }
9627
9628
9629 static int
9630 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9631 struct bp_target_info *bp_tgt)
9632 {
9633 CORE_ADDR addr;
9634 struct remote_state *rs = get_remote_state ();
9635 char *p = rs->buf;
9636 char *endbuf = rs->buf + get_remote_packet_size ();
9637
9638 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9639 return -1;
9640
9641 /* Make sure the remote is pointing at the right process, if
9642 necessary. */
9643 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9644 set_general_process ();
9645
9646 *(p++) = 'z';
9647 *(p++) = '1';
9648 *(p++) = ',';
9649
9650 addr = remote_address_masked (bp_tgt->placed_address);
9651 p += hexnumstr (p, (ULONGEST) addr);
9652 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9653
9654 putpkt (rs->buf);
9655 getpkt (&rs->buf, &rs->buf_size, 0);
9656
9657 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9658 {
9659 case PACKET_ERROR:
9660 case PACKET_UNKNOWN:
9661 return -1;
9662 case PACKET_OK:
9663 return 0;
9664 }
9665 internal_error (__FILE__, __LINE__,
9666 _("remote_remove_hw_breakpoint: reached end of function"));
9667 }
9668
9669 /* Verify memory using the "qCRC:" request. */
9670
9671 static int
9672 remote_verify_memory (struct target_ops *ops,
9673 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9674 {
9675 struct remote_state *rs = get_remote_state ();
9676 unsigned long host_crc, target_crc;
9677 char *tmp;
9678
9679 /* It doesn't make sense to use qCRC if the remote target is
9680 connected but not running. */
9681 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9682 {
9683 enum packet_result result;
9684
9685 /* Make sure the remote is pointing at the right process. */
9686 set_general_process ();
9687
9688 /* FIXME: assumes lma can fit into long. */
9689 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9690 (long) lma, (long) size);
9691 putpkt (rs->buf);
9692
9693 /* Be clever; compute the host_crc before waiting for target
9694 reply. */
9695 host_crc = xcrc32 (data, size, 0xffffffff);
9696
9697 getpkt (&rs->buf, &rs->buf_size, 0);
9698
9699 result = packet_ok (rs->buf,
9700 &remote_protocol_packets[PACKET_qCRC]);
9701 if (result == PACKET_ERROR)
9702 return -1;
9703 else if (result == PACKET_OK)
9704 {
9705 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9706 target_crc = target_crc * 16 + fromhex (*tmp);
9707
9708 return (host_crc == target_crc);
9709 }
9710 }
9711
9712 return simple_verify_memory (ops, data, lma, size);
9713 }
9714
9715 /* compare-sections command
9716
9717 With no arguments, compares each loadable section in the exec bfd
9718 with the same memory range on the target, and reports mismatches.
9719 Useful for verifying the image on the target against the exec file. */
9720
9721 static void
9722 compare_sections_command (char *args, int from_tty)
9723 {
9724 asection *s;
9725 struct cleanup *old_chain;
9726 gdb_byte *sectdata;
9727 const char *sectname;
9728 bfd_size_type size;
9729 bfd_vma lma;
9730 int matched = 0;
9731 int mismatched = 0;
9732 int res;
9733 int read_only = 0;
9734
9735 if (!exec_bfd)
9736 error (_("command cannot be used without an exec file"));
9737
9738 /* Make sure the remote is pointing at the right process. */
9739 set_general_process ();
9740
9741 if (args != NULL && strcmp (args, "-r") == 0)
9742 {
9743 read_only = 1;
9744 args = NULL;
9745 }
9746
9747 for (s = exec_bfd->sections; s; s = s->next)
9748 {
9749 if (!(s->flags & SEC_LOAD))
9750 continue; /* Skip non-loadable section. */
9751
9752 if (read_only && (s->flags & SEC_READONLY) == 0)
9753 continue; /* Skip writeable sections */
9754
9755 size = bfd_get_section_size (s);
9756 if (size == 0)
9757 continue; /* Skip zero-length section. */
9758
9759 sectname = bfd_get_section_name (exec_bfd, s);
9760 if (args && strcmp (args, sectname) != 0)
9761 continue; /* Not the section selected by user. */
9762
9763 matched = 1; /* Do this section. */
9764 lma = s->lma;
9765
9766 sectdata = (gdb_byte *) xmalloc (size);
9767 old_chain = make_cleanup (xfree, sectdata);
9768 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9769
9770 res = target_verify_memory (sectdata, lma, size);
9771
9772 if (res == -1)
9773 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9774 paddress (target_gdbarch (), lma),
9775 paddress (target_gdbarch (), lma + size));
9776
9777 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9778 paddress (target_gdbarch (), lma),
9779 paddress (target_gdbarch (), lma + size));
9780 if (res)
9781 printf_filtered ("matched.\n");
9782 else
9783 {
9784 printf_filtered ("MIS-MATCHED!\n");
9785 mismatched++;
9786 }
9787
9788 do_cleanups (old_chain);
9789 }
9790 if (mismatched > 0)
9791 warning (_("One or more sections of the target image does not match\n\
9792 the loaded file\n"));
9793 if (args && !matched)
9794 printf_filtered (_("No loaded section named '%s'.\n"), args);
9795 }
9796
9797 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9798 into remote target. The number of bytes written to the remote
9799 target is returned, or -1 for error. */
9800
9801 static enum target_xfer_status
9802 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9803 const char *annex, const gdb_byte *writebuf,
9804 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9805 struct packet_config *packet)
9806 {
9807 int i, buf_len;
9808 ULONGEST n;
9809 struct remote_state *rs = get_remote_state ();
9810 int max_size = get_memory_write_packet_size ();
9811
9812 if (packet->support == PACKET_DISABLE)
9813 return TARGET_XFER_E_IO;
9814
9815 /* Insert header. */
9816 i = snprintf (rs->buf, max_size,
9817 "qXfer:%s:write:%s:%s:",
9818 object_name, annex ? annex : "",
9819 phex_nz (offset, sizeof offset));
9820 max_size -= (i + 1);
9821
9822 /* Escape as much data as fits into rs->buf. */
9823 buf_len = remote_escape_output
9824 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9825
9826 if (putpkt_binary (rs->buf, i + buf_len) < 0
9827 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9828 || packet_ok (rs->buf, packet) != PACKET_OK)
9829 return TARGET_XFER_E_IO;
9830
9831 unpack_varlen_hex (rs->buf, &n);
9832
9833 *xfered_len = n;
9834 return TARGET_XFER_OK;
9835 }
9836
9837 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9838 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9839 number of bytes read is returned, or 0 for EOF, or -1 for error.
9840 The number of bytes read may be less than LEN without indicating an
9841 EOF. PACKET is checked and updated to indicate whether the remote
9842 target supports this object. */
9843
9844 static enum target_xfer_status
9845 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9846 const char *annex,
9847 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9848 ULONGEST *xfered_len,
9849 struct packet_config *packet)
9850 {
9851 struct remote_state *rs = get_remote_state ();
9852 LONGEST i, n, packet_len;
9853
9854 if (packet->support == PACKET_DISABLE)
9855 return TARGET_XFER_E_IO;
9856
9857 /* Check whether we've cached an end-of-object packet that matches
9858 this request. */
9859 if (rs->finished_object)
9860 {
9861 if (strcmp (object_name, rs->finished_object) == 0
9862 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9863 && offset == rs->finished_offset)
9864 return TARGET_XFER_EOF;
9865
9866
9867 /* Otherwise, we're now reading something different. Discard
9868 the cache. */
9869 xfree (rs->finished_object);
9870 xfree (rs->finished_annex);
9871 rs->finished_object = NULL;
9872 rs->finished_annex = NULL;
9873 }
9874
9875 /* Request only enough to fit in a single packet. The actual data
9876 may not, since we don't know how much of it will need to be escaped;
9877 the target is free to respond with slightly less data. We subtract
9878 five to account for the response type and the protocol frame. */
9879 n = min (get_remote_packet_size () - 5, len);
9880 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9881 object_name, annex ? annex : "",
9882 phex_nz (offset, sizeof offset),
9883 phex_nz (n, sizeof n));
9884 i = putpkt (rs->buf);
9885 if (i < 0)
9886 return TARGET_XFER_E_IO;
9887
9888 rs->buf[0] = '\0';
9889 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9890 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9891 return TARGET_XFER_E_IO;
9892
9893 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9894 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9895
9896 /* 'm' means there is (or at least might be) more data after this
9897 batch. That does not make sense unless there's at least one byte
9898 of data in this reply. */
9899 if (rs->buf[0] == 'm' && packet_len == 1)
9900 error (_("Remote qXfer reply contained no data."));
9901
9902 /* Got some data. */
9903 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9904 packet_len - 1, readbuf, n);
9905
9906 /* 'l' is an EOF marker, possibly including a final block of data,
9907 or possibly empty. If we have the final block of a non-empty
9908 object, record this fact to bypass a subsequent partial read. */
9909 if (rs->buf[0] == 'l' && offset + i > 0)
9910 {
9911 rs->finished_object = xstrdup (object_name);
9912 rs->finished_annex = xstrdup (annex ? annex : "");
9913 rs->finished_offset = offset + i;
9914 }
9915
9916 if (i == 0)
9917 return TARGET_XFER_EOF;
9918 else
9919 {
9920 *xfered_len = i;
9921 return TARGET_XFER_OK;
9922 }
9923 }
9924
9925 static enum target_xfer_status
9926 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9927 const char *annex, gdb_byte *readbuf,
9928 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9929 ULONGEST *xfered_len)
9930 {
9931 struct remote_state *rs;
9932 int i;
9933 char *p2;
9934 char query_type;
9935 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9936
9937 set_remote_traceframe ();
9938 set_general_thread (inferior_ptid);
9939
9940 rs = get_remote_state ();
9941
9942 /* Handle memory using the standard memory routines. */
9943 if (object == TARGET_OBJECT_MEMORY)
9944 {
9945 /* If the remote target is connected but not running, we should
9946 pass this request down to a lower stratum (e.g. the executable
9947 file). */
9948 if (!target_has_execution)
9949 return TARGET_XFER_EOF;
9950
9951 if (writebuf != NULL)
9952 return remote_write_bytes (offset, writebuf, len, unit_size,
9953 xfered_len);
9954 else
9955 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9956 xfered_len);
9957 }
9958
9959 /* Handle SPU memory using qxfer packets. */
9960 if (object == TARGET_OBJECT_SPU)
9961 {
9962 if (readbuf)
9963 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9964 xfered_len, &remote_protocol_packets
9965 [PACKET_qXfer_spu_read]);
9966 else
9967 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9968 xfered_len, &remote_protocol_packets
9969 [PACKET_qXfer_spu_write]);
9970 }
9971
9972 /* Handle extra signal info using qxfer packets. */
9973 if (object == TARGET_OBJECT_SIGNAL_INFO)
9974 {
9975 if (readbuf)
9976 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9977 xfered_len, &remote_protocol_packets
9978 [PACKET_qXfer_siginfo_read]);
9979 else
9980 return remote_write_qxfer (ops, "siginfo", annex,
9981 writebuf, offset, len, xfered_len,
9982 &remote_protocol_packets
9983 [PACKET_qXfer_siginfo_write]);
9984 }
9985
9986 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9987 {
9988 if (readbuf)
9989 return remote_read_qxfer (ops, "statictrace", annex,
9990 readbuf, offset, len, xfered_len,
9991 &remote_protocol_packets
9992 [PACKET_qXfer_statictrace_read]);
9993 else
9994 return TARGET_XFER_E_IO;
9995 }
9996
9997 /* Only handle flash writes. */
9998 if (writebuf != NULL)
9999 {
10000 switch (object)
10001 {
10002 case TARGET_OBJECT_FLASH:
10003 return remote_flash_write (ops, offset, len, xfered_len,
10004 writebuf);
10005
10006 default:
10007 return TARGET_XFER_E_IO;
10008 }
10009 }
10010
10011 /* Map pre-existing objects onto letters. DO NOT do this for new
10012 objects!!! Instead specify new query packets. */
10013 switch (object)
10014 {
10015 case TARGET_OBJECT_AVR:
10016 query_type = 'R';
10017 break;
10018
10019 case TARGET_OBJECT_AUXV:
10020 gdb_assert (annex == NULL);
10021 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10022 xfered_len,
10023 &remote_protocol_packets[PACKET_qXfer_auxv]);
10024
10025 case TARGET_OBJECT_AVAILABLE_FEATURES:
10026 return remote_read_qxfer
10027 (ops, "features", annex, readbuf, offset, len, xfered_len,
10028 &remote_protocol_packets[PACKET_qXfer_features]);
10029
10030 case TARGET_OBJECT_LIBRARIES:
10031 return remote_read_qxfer
10032 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10033 &remote_protocol_packets[PACKET_qXfer_libraries]);
10034
10035 case TARGET_OBJECT_LIBRARIES_SVR4:
10036 return remote_read_qxfer
10037 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10038 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10039
10040 case TARGET_OBJECT_MEMORY_MAP:
10041 gdb_assert (annex == NULL);
10042 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10043 xfered_len,
10044 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10045
10046 case TARGET_OBJECT_OSDATA:
10047 /* Should only get here if we're connected. */
10048 gdb_assert (rs->remote_desc);
10049 return remote_read_qxfer
10050 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10051 &remote_protocol_packets[PACKET_qXfer_osdata]);
10052
10053 case TARGET_OBJECT_THREADS:
10054 gdb_assert (annex == NULL);
10055 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10056 xfered_len,
10057 &remote_protocol_packets[PACKET_qXfer_threads]);
10058
10059 case TARGET_OBJECT_TRACEFRAME_INFO:
10060 gdb_assert (annex == NULL);
10061 return remote_read_qxfer
10062 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10063 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10064
10065 case TARGET_OBJECT_FDPIC:
10066 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10067 xfered_len,
10068 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10069
10070 case TARGET_OBJECT_OPENVMS_UIB:
10071 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10072 xfered_len,
10073 &remote_protocol_packets[PACKET_qXfer_uib]);
10074
10075 case TARGET_OBJECT_BTRACE:
10076 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10077 xfered_len,
10078 &remote_protocol_packets[PACKET_qXfer_btrace]);
10079
10080 case TARGET_OBJECT_BTRACE_CONF:
10081 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10082 len, xfered_len,
10083 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10084
10085 case TARGET_OBJECT_EXEC_FILE:
10086 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10087 len, xfered_len,
10088 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10089
10090 default:
10091 return TARGET_XFER_E_IO;
10092 }
10093
10094 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10095 large enough let the caller deal with it. */
10096 if (len < get_remote_packet_size ())
10097 return TARGET_XFER_E_IO;
10098 len = get_remote_packet_size ();
10099
10100 /* Except for querying the minimum buffer size, target must be open. */
10101 if (!rs->remote_desc)
10102 error (_("remote query is only available after target open"));
10103
10104 gdb_assert (annex != NULL);
10105 gdb_assert (readbuf != NULL);
10106
10107 p2 = rs->buf;
10108 *p2++ = 'q';
10109 *p2++ = query_type;
10110
10111 /* We used one buffer char for the remote protocol q command and
10112 another for the query type. As the remote protocol encapsulation
10113 uses 4 chars plus one extra in case we are debugging
10114 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10115 string. */
10116 i = 0;
10117 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10118 {
10119 /* Bad caller may have sent forbidden characters. */
10120 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10121 *p2++ = annex[i];
10122 i++;
10123 }
10124 *p2 = '\0';
10125 gdb_assert (annex[i] == '\0');
10126
10127 i = putpkt (rs->buf);
10128 if (i < 0)
10129 return TARGET_XFER_E_IO;
10130
10131 getpkt (&rs->buf, &rs->buf_size, 0);
10132 strcpy ((char *) readbuf, rs->buf);
10133
10134 *xfered_len = strlen ((char *) readbuf);
10135 return TARGET_XFER_OK;
10136 }
10137
10138 static int
10139 remote_search_memory (struct target_ops* ops,
10140 CORE_ADDR start_addr, ULONGEST search_space_len,
10141 const gdb_byte *pattern, ULONGEST pattern_len,
10142 CORE_ADDR *found_addrp)
10143 {
10144 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10145 struct remote_state *rs = get_remote_state ();
10146 int max_size = get_memory_write_packet_size ();
10147 struct packet_config *packet =
10148 &remote_protocol_packets[PACKET_qSearch_memory];
10149 /* Number of packet bytes used to encode the pattern;
10150 this could be more than PATTERN_LEN due to escape characters. */
10151 int escaped_pattern_len;
10152 /* Amount of pattern that was encodable in the packet. */
10153 int used_pattern_len;
10154 int i;
10155 int found;
10156 ULONGEST found_addr;
10157
10158 /* Don't go to the target if we don't have to.
10159 This is done before checking packet->support to avoid the possibility that
10160 a success for this edge case means the facility works in general. */
10161 if (pattern_len > search_space_len)
10162 return 0;
10163 if (pattern_len == 0)
10164 {
10165 *found_addrp = start_addr;
10166 return 1;
10167 }
10168
10169 /* If we already know the packet isn't supported, fall back to the simple
10170 way of searching memory. */
10171
10172 if (packet_config_support (packet) == PACKET_DISABLE)
10173 {
10174 /* Target doesn't provided special support, fall back and use the
10175 standard support (copy memory and do the search here). */
10176 return simple_search_memory (ops, start_addr, search_space_len,
10177 pattern, pattern_len, found_addrp);
10178 }
10179
10180 /* Make sure the remote is pointing at the right process. */
10181 set_general_process ();
10182
10183 /* Insert header. */
10184 i = snprintf (rs->buf, max_size,
10185 "qSearch:memory:%s;%s;",
10186 phex_nz (start_addr, addr_size),
10187 phex_nz (search_space_len, sizeof (search_space_len)));
10188 max_size -= (i + 1);
10189
10190 /* Escape as much data as fits into rs->buf. */
10191 escaped_pattern_len =
10192 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10193 &used_pattern_len, max_size);
10194
10195 /* Bail if the pattern is too large. */
10196 if (used_pattern_len != pattern_len)
10197 error (_("Pattern is too large to transmit to remote target."));
10198
10199 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10200 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10201 || packet_ok (rs->buf, packet) != PACKET_OK)
10202 {
10203 /* The request may not have worked because the command is not
10204 supported. If so, fall back to the simple way. */
10205 if (packet->support == PACKET_DISABLE)
10206 {
10207 return simple_search_memory (ops, start_addr, search_space_len,
10208 pattern, pattern_len, found_addrp);
10209 }
10210 return -1;
10211 }
10212
10213 if (rs->buf[0] == '0')
10214 found = 0;
10215 else if (rs->buf[0] == '1')
10216 {
10217 found = 1;
10218 if (rs->buf[1] != ',')
10219 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10220 unpack_varlen_hex (rs->buf + 2, &found_addr);
10221 *found_addrp = found_addr;
10222 }
10223 else
10224 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10225
10226 return found;
10227 }
10228
10229 static void
10230 remote_rcmd (struct target_ops *self, const char *command,
10231 struct ui_file *outbuf)
10232 {
10233 struct remote_state *rs = get_remote_state ();
10234 char *p = rs->buf;
10235
10236 if (!rs->remote_desc)
10237 error (_("remote rcmd is only available after target open"));
10238
10239 /* Send a NULL command across as an empty command. */
10240 if (command == NULL)
10241 command = "";
10242
10243 /* The query prefix. */
10244 strcpy (rs->buf, "qRcmd,");
10245 p = strchr (rs->buf, '\0');
10246
10247 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10248 > get_remote_packet_size ())
10249 error (_("\"monitor\" command ``%s'' is too long."), command);
10250
10251 /* Encode the actual command. */
10252 bin2hex ((const gdb_byte *) command, p, strlen (command));
10253
10254 if (putpkt (rs->buf) < 0)
10255 error (_("Communication problem with target."));
10256
10257 /* get/display the response */
10258 while (1)
10259 {
10260 char *buf;
10261
10262 /* XXX - see also remote_get_noisy_reply(). */
10263 QUIT; /* Allow user to bail out with ^C. */
10264 rs->buf[0] = '\0';
10265 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10266 {
10267 /* Timeout. Continue to (try to) read responses.
10268 This is better than stopping with an error, assuming the stub
10269 is still executing the (long) monitor command.
10270 If needed, the user can interrupt gdb using C-c, obtaining
10271 an effect similar to stop on timeout. */
10272 continue;
10273 }
10274 buf = rs->buf;
10275 if (buf[0] == '\0')
10276 error (_("Target does not support this command."));
10277 if (buf[0] == 'O' && buf[1] != 'K')
10278 {
10279 remote_console_output (buf + 1); /* 'O' message from stub. */
10280 continue;
10281 }
10282 if (strcmp (buf, "OK") == 0)
10283 break;
10284 if (strlen (buf) == 3 && buf[0] == 'E'
10285 && isdigit (buf[1]) && isdigit (buf[2]))
10286 {
10287 error (_("Protocol error with Rcmd"));
10288 }
10289 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10290 {
10291 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10292
10293 fputc_unfiltered (c, outbuf);
10294 }
10295 break;
10296 }
10297 }
10298
10299 static VEC(mem_region_s) *
10300 remote_memory_map (struct target_ops *ops)
10301 {
10302 VEC(mem_region_s) *result = NULL;
10303 char *text = target_read_stralloc (&current_target,
10304 TARGET_OBJECT_MEMORY_MAP, NULL);
10305
10306 if (text)
10307 {
10308 struct cleanup *back_to = make_cleanup (xfree, text);
10309
10310 result = parse_memory_map (text);
10311 do_cleanups (back_to);
10312 }
10313
10314 return result;
10315 }
10316
10317 static void
10318 packet_command (char *args, int from_tty)
10319 {
10320 struct remote_state *rs = get_remote_state ();
10321
10322 if (!rs->remote_desc)
10323 error (_("command can only be used with remote target"));
10324
10325 if (!args)
10326 error (_("remote-packet command requires packet text as argument"));
10327
10328 puts_filtered ("sending: ");
10329 print_packet (args);
10330 puts_filtered ("\n");
10331 putpkt (args);
10332
10333 getpkt (&rs->buf, &rs->buf_size, 0);
10334 puts_filtered ("received: ");
10335 print_packet (rs->buf);
10336 puts_filtered ("\n");
10337 }
10338
10339 #if 0
10340 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10341
10342 static void display_thread_info (struct gdb_ext_thread_info *info);
10343
10344 static void threadset_test_cmd (char *cmd, int tty);
10345
10346 static void threadalive_test (char *cmd, int tty);
10347
10348 static void threadlist_test_cmd (char *cmd, int tty);
10349
10350 int get_and_display_threadinfo (threadref *ref);
10351
10352 static void threadinfo_test_cmd (char *cmd, int tty);
10353
10354 static int thread_display_step (threadref *ref, void *context);
10355
10356 static void threadlist_update_test_cmd (char *cmd, int tty);
10357
10358 static void init_remote_threadtests (void);
10359
10360 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10361
10362 static void
10363 threadset_test_cmd (char *cmd, int tty)
10364 {
10365 int sample_thread = SAMPLE_THREAD;
10366
10367 printf_filtered (_("Remote threadset test\n"));
10368 set_general_thread (sample_thread);
10369 }
10370
10371
10372 static void
10373 threadalive_test (char *cmd, int tty)
10374 {
10375 int sample_thread = SAMPLE_THREAD;
10376 int pid = ptid_get_pid (inferior_ptid);
10377 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10378
10379 if (remote_thread_alive (ptid))
10380 printf_filtered ("PASS: Thread alive test\n");
10381 else
10382 printf_filtered ("FAIL: Thread alive test\n");
10383 }
10384
10385 void output_threadid (char *title, threadref *ref);
10386
10387 void
10388 output_threadid (char *title, threadref *ref)
10389 {
10390 char hexid[20];
10391
10392 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10393 hexid[16] = 0;
10394 printf_filtered ("%s %s\n", title, (&hexid[0]));
10395 }
10396
10397 static void
10398 threadlist_test_cmd (char *cmd, int tty)
10399 {
10400 int startflag = 1;
10401 threadref nextthread;
10402 int done, result_count;
10403 threadref threadlist[3];
10404
10405 printf_filtered ("Remote Threadlist test\n");
10406 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10407 &result_count, &threadlist[0]))
10408 printf_filtered ("FAIL: threadlist test\n");
10409 else
10410 {
10411 threadref *scan = threadlist;
10412 threadref *limit = scan + result_count;
10413
10414 while (scan < limit)
10415 output_threadid (" thread ", scan++);
10416 }
10417 }
10418
10419 void
10420 display_thread_info (struct gdb_ext_thread_info *info)
10421 {
10422 output_threadid ("Threadid: ", &info->threadid);
10423 printf_filtered ("Name: %s\n ", info->shortname);
10424 printf_filtered ("State: %s\n", info->display);
10425 printf_filtered ("other: %s\n\n", info->more_display);
10426 }
10427
10428 int
10429 get_and_display_threadinfo (threadref *ref)
10430 {
10431 int result;
10432 int set;
10433 struct gdb_ext_thread_info threadinfo;
10434
10435 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10436 | TAG_MOREDISPLAY | TAG_DISPLAY;
10437 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10438 display_thread_info (&threadinfo);
10439 return result;
10440 }
10441
10442 static void
10443 threadinfo_test_cmd (char *cmd, int tty)
10444 {
10445 int athread = SAMPLE_THREAD;
10446 threadref thread;
10447 int set;
10448
10449 int_to_threadref (&thread, athread);
10450 printf_filtered ("Remote Threadinfo test\n");
10451 if (!get_and_display_threadinfo (&thread))
10452 printf_filtered ("FAIL cannot get thread info\n");
10453 }
10454
10455 static int
10456 thread_display_step (threadref *ref, void *context)
10457 {
10458 /* output_threadid(" threadstep ",ref); *//* simple test */
10459 return get_and_display_threadinfo (ref);
10460 }
10461
10462 static void
10463 threadlist_update_test_cmd (char *cmd, int tty)
10464 {
10465 printf_filtered ("Remote Threadlist update test\n");
10466 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10467 }
10468
10469 static void
10470 init_remote_threadtests (void)
10471 {
10472 add_com ("tlist", class_obscure, threadlist_test_cmd,
10473 _("Fetch and print the remote list of "
10474 "thread identifiers, one pkt only"));
10475 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10476 _("Fetch and display info about one thread"));
10477 add_com ("tset", class_obscure, threadset_test_cmd,
10478 _("Test setting to a different thread"));
10479 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10480 _("Iterate through updating all remote thread info"));
10481 add_com ("talive", class_obscure, threadalive_test,
10482 _(" Remote thread alive test "));
10483 }
10484
10485 #endif /* 0 */
10486
10487 /* Convert a thread ID to a string. Returns the string in a static
10488 buffer. */
10489
10490 static char *
10491 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10492 {
10493 static char buf[64];
10494 struct remote_state *rs = get_remote_state ();
10495
10496 if (ptid_equal (ptid, null_ptid))
10497 return normal_pid_to_str (ptid);
10498 else if (ptid_is_pid (ptid))
10499 {
10500 /* Printing an inferior target id. */
10501
10502 /* When multi-process extensions are off, there's no way in the
10503 remote protocol to know the remote process id, if there's any
10504 at all. There's one exception --- when we're connected with
10505 target extended-remote, and we manually attached to a process
10506 with "attach PID". We don't record anywhere a flag that
10507 allows us to distinguish that case from the case of
10508 connecting with extended-remote and the stub already being
10509 attached to a process, and reporting yes to qAttached, hence
10510 no smart special casing here. */
10511 if (!remote_multi_process_p (rs))
10512 {
10513 xsnprintf (buf, sizeof buf, "Remote target");
10514 return buf;
10515 }
10516
10517 return normal_pid_to_str (ptid);
10518 }
10519 else
10520 {
10521 if (ptid_equal (magic_null_ptid, ptid))
10522 xsnprintf (buf, sizeof buf, "Thread <main>");
10523 else if (remote_multi_process_p (rs))
10524 if (ptid_get_lwp (ptid) == 0)
10525 return normal_pid_to_str (ptid);
10526 else
10527 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10528 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10529 else
10530 xsnprintf (buf, sizeof buf, "Thread %ld",
10531 ptid_get_lwp (ptid));
10532 return buf;
10533 }
10534 }
10535
10536 /* Get the address of the thread local variable in OBJFILE which is
10537 stored at OFFSET within the thread local storage for thread PTID. */
10538
10539 static CORE_ADDR
10540 remote_get_thread_local_address (struct target_ops *ops,
10541 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10542 {
10543 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10544 {
10545 struct remote_state *rs = get_remote_state ();
10546 char *p = rs->buf;
10547 char *endp = rs->buf + get_remote_packet_size ();
10548 enum packet_result result;
10549
10550 strcpy (p, "qGetTLSAddr:");
10551 p += strlen (p);
10552 p = write_ptid (p, endp, ptid);
10553 *p++ = ',';
10554 p += hexnumstr (p, offset);
10555 *p++ = ',';
10556 p += hexnumstr (p, lm);
10557 *p++ = '\0';
10558
10559 putpkt (rs->buf);
10560 getpkt (&rs->buf, &rs->buf_size, 0);
10561 result = packet_ok (rs->buf,
10562 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10563 if (result == PACKET_OK)
10564 {
10565 ULONGEST result;
10566
10567 unpack_varlen_hex (rs->buf, &result);
10568 return result;
10569 }
10570 else if (result == PACKET_UNKNOWN)
10571 throw_error (TLS_GENERIC_ERROR,
10572 _("Remote target doesn't support qGetTLSAddr packet"));
10573 else
10574 throw_error (TLS_GENERIC_ERROR,
10575 _("Remote target failed to process qGetTLSAddr request"));
10576 }
10577 else
10578 throw_error (TLS_GENERIC_ERROR,
10579 _("TLS not supported or disabled on this target"));
10580 /* Not reached. */
10581 return 0;
10582 }
10583
10584 /* Provide thread local base, i.e. Thread Information Block address.
10585 Returns 1 if ptid is found and thread_local_base is non zero. */
10586
10587 static int
10588 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10589 {
10590 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10591 {
10592 struct remote_state *rs = get_remote_state ();
10593 char *p = rs->buf;
10594 char *endp = rs->buf + get_remote_packet_size ();
10595 enum packet_result result;
10596
10597 strcpy (p, "qGetTIBAddr:");
10598 p += strlen (p);
10599 p = write_ptid (p, endp, ptid);
10600 *p++ = '\0';
10601
10602 putpkt (rs->buf);
10603 getpkt (&rs->buf, &rs->buf_size, 0);
10604 result = packet_ok (rs->buf,
10605 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10606 if (result == PACKET_OK)
10607 {
10608 ULONGEST result;
10609
10610 unpack_varlen_hex (rs->buf, &result);
10611 if (addr)
10612 *addr = (CORE_ADDR) result;
10613 return 1;
10614 }
10615 else if (result == PACKET_UNKNOWN)
10616 error (_("Remote target doesn't support qGetTIBAddr packet"));
10617 else
10618 error (_("Remote target failed to process qGetTIBAddr request"));
10619 }
10620 else
10621 error (_("qGetTIBAddr not supported or disabled on this target"));
10622 /* Not reached. */
10623 return 0;
10624 }
10625
10626 /* Support for inferring a target description based on the current
10627 architecture and the size of a 'g' packet. While the 'g' packet
10628 can have any size (since optional registers can be left off the
10629 end), some sizes are easily recognizable given knowledge of the
10630 approximate architecture. */
10631
10632 struct remote_g_packet_guess
10633 {
10634 int bytes;
10635 const struct target_desc *tdesc;
10636 };
10637 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10638 DEF_VEC_O(remote_g_packet_guess_s);
10639
10640 struct remote_g_packet_data
10641 {
10642 VEC(remote_g_packet_guess_s) *guesses;
10643 };
10644
10645 static struct gdbarch_data *remote_g_packet_data_handle;
10646
10647 static void *
10648 remote_g_packet_data_init (struct obstack *obstack)
10649 {
10650 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10651 }
10652
10653 void
10654 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10655 const struct target_desc *tdesc)
10656 {
10657 struct remote_g_packet_data *data
10658 = ((struct remote_g_packet_data *)
10659 gdbarch_data (gdbarch, remote_g_packet_data_handle));
10660 struct remote_g_packet_guess new_guess, *guess;
10661 int ix;
10662
10663 gdb_assert (tdesc != NULL);
10664
10665 for (ix = 0;
10666 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10667 ix++)
10668 if (guess->bytes == bytes)
10669 internal_error (__FILE__, __LINE__,
10670 _("Duplicate g packet description added for size %d"),
10671 bytes);
10672
10673 new_guess.bytes = bytes;
10674 new_guess.tdesc = tdesc;
10675 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10676 }
10677
10678 /* Return 1 if remote_read_description would do anything on this target
10679 and architecture, 0 otherwise. */
10680
10681 static int
10682 remote_read_description_p (struct target_ops *target)
10683 {
10684 struct remote_g_packet_data *data
10685 = ((struct remote_g_packet_data *)
10686 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10687
10688 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10689 return 1;
10690
10691 return 0;
10692 }
10693
10694 static const struct target_desc *
10695 remote_read_description (struct target_ops *target)
10696 {
10697 struct remote_g_packet_data *data
10698 = ((struct remote_g_packet_data *)
10699 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10700
10701 /* Do not try this during initial connection, when we do not know
10702 whether there is a running but stopped thread. */
10703 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10704 return target->beneath->to_read_description (target->beneath);
10705
10706 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10707 {
10708 struct remote_g_packet_guess *guess;
10709 int ix;
10710 int bytes = send_g_packet ();
10711
10712 for (ix = 0;
10713 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10714 ix++)
10715 if (guess->bytes == bytes)
10716 return guess->tdesc;
10717
10718 /* We discard the g packet. A minor optimization would be to
10719 hold on to it, and fill the register cache once we have selected
10720 an architecture, but it's too tricky to do safely. */
10721 }
10722
10723 return target->beneath->to_read_description (target->beneath);
10724 }
10725
10726 /* Remote file transfer support. This is host-initiated I/O, not
10727 target-initiated; for target-initiated, see remote-fileio.c. */
10728
10729 /* If *LEFT is at least the length of STRING, copy STRING to
10730 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10731 decrease *LEFT. Otherwise raise an error. */
10732
10733 static void
10734 remote_buffer_add_string (char **buffer, int *left, char *string)
10735 {
10736 int len = strlen (string);
10737
10738 if (len > *left)
10739 error (_("Packet too long for target."));
10740
10741 memcpy (*buffer, string, len);
10742 *buffer += len;
10743 *left -= len;
10744
10745 /* NUL-terminate the buffer as a convenience, if there is
10746 room. */
10747 if (*left)
10748 **buffer = '\0';
10749 }
10750
10751 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10752 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10753 decrease *LEFT. Otherwise raise an error. */
10754
10755 static void
10756 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10757 int len)
10758 {
10759 if (2 * len > *left)
10760 error (_("Packet too long for target."));
10761
10762 bin2hex (bytes, *buffer, len);
10763 *buffer += 2 * len;
10764 *left -= 2 * len;
10765
10766 /* NUL-terminate the buffer as a convenience, if there is
10767 room. */
10768 if (*left)
10769 **buffer = '\0';
10770 }
10771
10772 /* If *LEFT is large enough, convert VALUE to hex and add it to
10773 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10774 decrease *LEFT. Otherwise raise an error. */
10775
10776 static void
10777 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10778 {
10779 int len = hexnumlen (value);
10780
10781 if (len > *left)
10782 error (_("Packet too long for target."));
10783
10784 hexnumstr (*buffer, value);
10785 *buffer += len;
10786 *left -= len;
10787
10788 /* NUL-terminate the buffer as a convenience, if there is
10789 room. */
10790 if (*left)
10791 **buffer = '\0';
10792 }
10793
10794 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10795 value, *REMOTE_ERRNO to the remote error number or zero if none
10796 was included, and *ATTACHMENT to point to the start of the annex
10797 if any. The length of the packet isn't needed here; there may
10798 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10799
10800 Return 0 if the packet could be parsed, -1 if it could not. If
10801 -1 is returned, the other variables may not be initialized. */
10802
10803 static int
10804 remote_hostio_parse_result (char *buffer, int *retcode,
10805 int *remote_errno, char **attachment)
10806 {
10807 char *p, *p2;
10808
10809 *remote_errno = 0;
10810 *attachment = NULL;
10811
10812 if (buffer[0] != 'F')
10813 return -1;
10814
10815 errno = 0;
10816 *retcode = strtol (&buffer[1], &p, 16);
10817 if (errno != 0 || p == &buffer[1])
10818 return -1;
10819
10820 /* Check for ",errno". */
10821 if (*p == ',')
10822 {
10823 errno = 0;
10824 *remote_errno = strtol (p + 1, &p2, 16);
10825 if (errno != 0 || p + 1 == p2)
10826 return -1;
10827 p = p2;
10828 }
10829
10830 /* Check for ";attachment". If there is no attachment, the
10831 packet should end here. */
10832 if (*p == ';')
10833 {
10834 *attachment = p + 1;
10835 return 0;
10836 }
10837 else if (*p == '\0')
10838 return 0;
10839 else
10840 return -1;
10841 }
10842
10843 /* Send a prepared I/O packet to the target and read its response.
10844 The prepared packet is in the global RS->BUF before this function
10845 is called, and the answer is there when we return.
10846
10847 COMMAND_BYTES is the length of the request to send, which may include
10848 binary data. WHICH_PACKET is the packet configuration to check
10849 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10850 is set to the error number and -1 is returned. Otherwise the value
10851 returned by the function is returned.
10852
10853 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10854 attachment is expected; an error will be reported if there's a
10855 mismatch. If one is found, *ATTACHMENT will be set to point into
10856 the packet buffer and *ATTACHMENT_LEN will be set to the
10857 attachment's length. */
10858
10859 static int
10860 remote_hostio_send_command (int command_bytes, int which_packet,
10861 int *remote_errno, char **attachment,
10862 int *attachment_len)
10863 {
10864 struct remote_state *rs = get_remote_state ();
10865 int ret, bytes_read;
10866 char *attachment_tmp;
10867
10868 if (!rs->remote_desc
10869 || packet_support (which_packet) == PACKET_DISABLE)
10870 {
10871 *remote_errno = FILEIO_ENOSYS;
10872 return -1;
10873 }
10874
10875 putpkt_binary (rs->buf, command_bytes);
10876 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10877
10878 /* If it timed out, something is wrong. Don't try to parse the
10879 buffer. */
10880 if (bytes_read < 0)
10881 {
10882 *remote_errno = FILEIO_EINVAL;
10883 return -1;
10884 }
10885
10886 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10887 {
10888 case PACKET_ERROR:
10889 *remote_errno = FILEIO_EINVAL;
10890 return -1;
10891 case PACKET_UNKNOWN:
10892 *remote_errno = FILEIO_ENOSYS;
10893 return -1;
10894 case PACKET_OK:
10895 break;
10896 }
10897
10898 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10899 &attachment_tmp))
10900 {
10901 *remote_errno = FILEIO_EINVAL;
10902 return -1;
10903 }
10904
10905 /* Make sure we saw an attachment if and only if we expected one. */
10906 if ((attachment_tmp == NULL && attachment != NULL)
10907 || (attachment_tmp != NULL && attachment == NULL))
10908 {
10909 *remote_errno = FILEIO_EINVAL;
10910 return -1;
10911 }
10912
10913 /* If an attachment was found, it must point into the packet buffer;
10914 work out how many bytes there were. */
10915 if (attachment_tmp != NULL)
10916 {
10917 *attachment = attachment_tmp;
10918 *attachment_len = bytes_read - (*attachment - rs->buf);
10919 }
10920
10921 return ret;
10922 }
10923
10924 /* Invalidate the readahead cache. */
10925
10926 static void
10927 readahead_cache_invalidate (void)
10928 {
10929 struct remote_state *rs = get_remote_state ();
10930
10931 rs->readahead_cache.fd = -1;
10932 }
10933
10934 /* Invalidate the readahead cache if it is holding data for FD. */
10935
10936 static void
10937 readahead_cache_invalidate_fd (int fd)
10938 {
10939 struct remote_state *rs = get_remote_state ();
10940
10941 if (rs->readahead_cache.fd == fd)
10942 rs->readahead_cache.fd = -1;
10943 }
10944
10945 /* Set the filesystem remote_hostio functions that take FILENAME
10946 arguments will use. Return 0 on success, or -1 if an error
10947 occurs (and set *REMOTE_ERRNO). */
10948
10949 static int
10950 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10951 {
10952 struct remote_state *rs = get_remote_state ();
10953 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10954 char *p = rs->buf;
10955 int left = get_remote_packet_size () - 1;
10956 char arg[9];
10957 int ret;
10958
10959 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10960 return 0;
10961
10962 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10963 return 0;
10964
10965 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10966
10967 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10968 remote_buffer_add_string (&p, &left, arg);
10969
10970 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10971 remote_errno, NULL, NULL);
10972
10973 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10974 return 0;
10975
10976 if (ret == 0)
10977 rs->fs_pid = required_pid;
10978
10979 return ret;
10980 }
10981
10982 /* Implementation of to_fileio_open. */
10983
10984 static int
10985 remote_hostio_open (struct target_ops *self,
10986 struct inferior *inf, const char *filename,
10987 int flags, int mode, int warn_if_slow,
10988 int *remote_errno)
10989 {
10990 struct remote_state *rs = get_remote_state ();
10991 char *p = rs->buf;
10992 int left = get_remote_packet_size () - 1;
10993
10994 if (warn_if_slow)
10995 {
10996 static int warning_issued = 0;
10997
10998 printf_unfiltered (_("Reading %s from remote target...\n"),
10999 filename);
11000
11001 if (!warning_issued)
11002 {
11003 warning (_("File transfers from remote targets can be slow."
11004 " Use \"set sysroot\" to access files locally"
11005 " instead."));
11006 warning_issued = 1;
11007 }
11008 }
11009
11010 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11011 return -1;
11012
11013 remote_buffer_add_string (&p, &left, "vFile:open:");
11014
11015 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11016 strlen (filename));
11017 remote_buffer_add_string (&p, &left, ",");
11018
11019 remote_buffer_add_int (&p, &left, flags);
11020 remote_buffer_add_string (&p, &left, ",");
11021
11022 remote_buffer_add_int (&p, &left, mode);
11023
11024 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11025 remote_errno, NULL, NULL);
11026 }
11027
11028 /* Implementation of to_fileio_pwrite. */
11029
11030 static int
11031 remote_hostio_pwrite (struct target_ops *self,
11032 int fd, const gdb_byte *write_buf, int len,
11033 ULONGEST offset, int *remote_errno)
11034 {
11035 struct remote_state *rs = get_remote_state ();
11036 char *p = rs->buf;
11037 int left = get_remote_packet_size ();
11038 int out_len;
11039
11040 readahead_cache_invalidate_fd (fd);
11041
11042 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11043
11044 remote_buffer_add_int (&p, &left, fd);
11045 remote_buffer_add_string (&p, &left, ",");
11046
11047 remote_buffer_add_int (&p, &left, offset);
11048 remote_buffer_add_string (&p, &left, ",");
11049
11050 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11051 get_remote_packet_size () - (p - rs->buf));
11052
11053 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11054 remote_errno, NULL, NULL);
11055 }
11056
11057 /* Helper for the implementation of to_fileio_pread. Read the file
11058 from the remote side with vFile:pread. */
11059
11060 static int
11061 remote_hostio_pread_vFile (struct target_ops *self,
11062 int fd, gdb_byte *read_buf, int len,
11063 ULONGEST offset, int *remote_errno)
11064 {
11065 struct remote_state *rs = get_remote_state ();
11066 char *p = rs->buf;
11067 char *attachment;
11068 int left = get_remote_packet_size ();
11069 int ret, attachment_len;
11070 int read_len;
11071
11072 remote_buffer_add_string (&p, &left, "vFile:pread:");
11073
11074 remote_buffer_add_int (&p, &left, fd);
11075 remote_buffer_add_string (&p, &left, ",");
11076
11077 remote_buffer_add_int (&p, &left, len);
11078 remote_buffer_add_string (&p, &left, ",");
11079
11080 remote_buffer_add_int (&p, &left, offset);
11081
11082 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11083 remote_errno, &attachment,
11084 &attachment_len);
11085
11086 if (ret < 0)
11087 return ret;
11088
11089 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11090 read_buf, len);
11091 if (read_len != ret)
11092 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11093
11094 return ret;
11095 }
11096
11097 /* Serve pread from the readahead cache. Returns number of bytes
11098 read, or 0 if the request can't be served from the cache. */
11099
11100 static int
11101 remote_hostio_pread_from_cache (struct remote_state *rs,
11102 int fd, gdb_byte *read_buf, size_t len,
11103 ULONGEST offset)
11104 {
11105 struct readahead_cache *cache = &rs->readahead_cache;
11106
11107 if (cache->fd == fd
11108 && cache->offset <= offset
11109 && offset < cache->offset + cache->bufsize)
11110 {
11111 ULONGEST max = cache->offset + cache->bufsize;
11112
11113 if (offset + len > max)
11114 len = max - offset;
11115
11116 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11117 return len;
11118 }
11119
11120 return 0;
11121 }
11122
11123 /* Implementation of to_fileio_pread. */
11124
11125 static int
11126 remote_hostio_pread (struct target_ops *self,
11127 int fd, gdb_byte *read_buf, int len,
11128 ULONGEST offset, int *remote_errno)
11129 {
11130 int ret;
11131 struct remote_state *rs = get_remote_state ();
11132 struct readahead_cache *cache = &rs->readahead_cache;
11133
11134 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11135 if (ret > 0)
11136 {
11137 cache->hit_count++;
11138
11139 if (remote_debug)
11140 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11141 pulongest (cache->hit_count));
11142 return ret;
11143 }
11144
11145 cache->miss_count++;
11146 if (remote_debug)
11147 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11148 pulongest (cache->miss_count));
11149
11150 cache->fd = fd;
11151 cache->offset = offset;
11152 cache->bufsize = get_remote_packet_size ();
11153 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11154
11155 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11156 cache->offset, remote_errno);
11157 if (ret <= 0)
11158 {
11159 readahead_cache_invalidate_fd (fd);
11160 return ret;
11161 }
11162
11163 cache->bufsize = ret;
11164 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11165 }
11166
11167 /* Implementation of to_fileio_close. */
11168
11169 static int
11170 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11171 {
11172 struct remote_state *rs = get_remote_state ();
11173 char *p = rs->buf;
11174 int left = get_remote_packet_size () - 1;
11175
11176 readahead_cache_invalidate_fd (fd);
11177
11178 remote_buffer_add_string (&p, &left, "vFile:close:");
11179
11180 remote_buffer_add_int (&p, &left, fd);
11181
11182 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11183 remote_errno, NULL, NULL);
11184 }
11185
11186 /* Implementation of to_fileio_unlink. */
11187
11188 static int
11189 remote_hostio_unlink (struct target_ops *self,
11190 struct inferior *inf, const char *filename,
11191 int *remote_errno)
11192 {
11193 struct remote_state *rs = get_remote_state ();
11194 char *p = rs->buf;
11195 int left = get_remote_packet_size () - 1;
11196
11197 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11198 return -1;
11199
11200 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11201
11202 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11203 strlen (filename));
11204
11205 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11206 remote_errno, NULL, NULL);
11207 }
11208
11209 /* Implementation of to_fileio_readlink. */
11210
11211 static char *
11212 remote_hostio_readlink (struct target_ops *self,
11213 struct inferior *inf, const char *filename,
11214 int *remote_errno)
11215 {
11216 struct remote_state *rs = get_remote_state ();
11217 char *p = rs->buf;
11218 char *attachment;
11219 int left = get_remote_packet_size ();
11220 int len, attachment_len;
11221 int read_len;
11222 char *ret;
11223
11224 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11225 return NULL;
11226
11227 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11228
11229 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11230 strlen (filename));
11231
11232 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11233 remote_errno, &attachment,
11234 &attachment_len);
11235
11236 if (len < 0)
11237 return NULL;
11238
11239 ret = (char *) xmalloc (len + 1);
11240
11241 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11242 (gdb_byte *) ret, len);
11243 if (read_len != len)
11244 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11245
11246 ret[len] = '\0';
11247 return ret;
11248 }
11249
11250 /* Implementation of to_fileio_fstat. */
11251
11252 static int
11253 remote_hostio_fstat (struct target_ops *self,
11254 int fd, struct stat *st,
11255 int *remote_errno)
11256 {
11257 struct remote_state *rs = get_remote_state ();
11258 char *p = rs->buf;
11259 int left = get_remote_packet_size ();
11260 int attachment_len, ret;
11261 char *attachment;
11262 struct fio_stat fst;
11263 int read_len;
11264
11265 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11266
11267 remote_buffer_add_int (&p, &left, fd);
11268
11269 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11270 remote_errno, &attachment,
11271 &attachment_len);
11272 if (ret < 0)
11273 {
11274 if (*remote_errno != FILEIO_ENOSYS)
11275 return ret;
11276
11277 /* Strictly we should return -1, ENOSYS here, but when
11278 "set sysroot remote:" was implemented in August 2008
11279 BFD's need for a stat function was sidestepped with
11280 this hack. This was not remedied until March 2015
11281 so we retain the previous behavior to avoid breaking
11282 compatibility.
11283
11284 Note that the memset is a March 2015 addition; older
11285 GDBs set st_size *and nothing else* so the structure
11286 would have garbage in all other fields. This might
11287 break something but retaining the previous behavior
11288 here would be just too wrong. */
11289
11290 memset (st, 0, sizeof (struct stat));
11291 st->st_size = INT_MAX;
11292 return 0;
11293 }
11294
11295 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11296 (gdb_byte *) &fst, sizeof (fst));
11297
11298 if (read_len != ret)
11299 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11300
11301 if (read_len != sizeof (fst))
11302 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11303 read_len, (int) sizeof (fst));
11304
11305 remote_fileio_to_host_stat (&fst, st);
11306
11307 return 0;
11308 }
11309
11310 /* Implementation of to_filesystem_is_local. */
11311
11312 static int
11313 remote_filesystem_is_local (struct target_ops *self)
11314 {
11315 /* Valgrind GDB presents itself as a remote target but works
11316 on the local filesystem: it does not implement remote get
11317 and users are not expected to set a sysroot. To handle
11318 this case we treat the remote filesystem as local if the
11319 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11320 does not support vFile:open. */
11321 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11322 {
11323 enum packet_support ps = packet_support (PACKET_vFile_open);
11324
11325 if (ps == PACKET_SUPPORT_UNKNOWN)
11326 {
11327 int fd, remote_errno;
11328
11329 /* Try opening a file to probe support. The supplied
11330 filename is irrelevant, we only care about whether
11331 the stub recognizes the packet or not. */
11332 fd = remote_hostio_open (self, NULL, "just probing",
11333 FILEIO_O_RDONLY, 0700, 0,
11334 &remote_errno);
11335
11336 if (fd >= 0)
11337 remote_hostio_close (self, fd, &remote_errno);
11338
11339 ps = packet_support (PACKET_vFile_open);
11340 }
11341
11342 if (ps == PACKET_DISABLE)
11343 {
11344 static int warning_issued = 0;
11345
11346 if (!warning_issued)
11347 {
11348 warning (_("remote target does not support file"
11349 " transfer, attempting to access files"
11350 " from local filesystem."));
11351 warning_issued = 1;
11352 }
11353
11354 return 1;
11355 }
11356 }
11357
11358 return 0;
11359 }
11360
11361 static int
11362 remote_fileio_errno_to_host (int errnum)
11363 {
11364 switch (errnum)
11365 {
11366 case FILEIO_EPERM:
11367 return EPERM;
11368 case FILEIO_ENOENT:
11369 return ENOENT;
11370 case FILEIO_EINTR:
11371 return EINTR;
11372 case FILEIO_EIO:
11373 return EIO;
11374 case FILEIO_EBADF:
11375 return EBADF;
11376 case FILEIO_EACCES:
11377 return EACCES;
11378 case FILEIO_EFAULT:
11379 return EFAULT;
11380 case FILEIO_EBUSY:
11381 return EBUSY;
11382 case FILEIO_EEXIST:
11383 return EEXIST;
11384 case FILEIO_ENODEV:
11385 return ENODEV;
11386 case FILEIO_ENOTDIR:
11387 return ENOTDIR;
11388 case FILEIO_EISDIR:
11389 return EISDIR;
11390 case FILEIO_EINVAL:
11391 return EINVAL;
11392 case FILEIO_ENFILE:
11393 return ENFILE;
11394 case FILEIO_EMFILE:
11395 return EMFILE;
11396 case FILEIO_EFBIG:
11397 return EFBIG;
11398 case FILEIO_ENOSPC:
11399 return ENOSPC;
11400 case FILEIO_ESPIPE:
11401 return ESPIPE;
11402 case FILEIO_EROFS:
11403 return EROFS;
11404 case FILEIO_ENOSYS:
11405 return ENOSYS;
11406 case FILEIO_ENAMETOOLONG:
11407 return ENAMETOOLONG;
11408 }
11409 return -1;
11410 }
11411
11412 static char *
11413 remote_hostio_error (int errnum)
11414 {
11415 int host_error = remote_fileio_errno_to_host (errnum);
11416
11417 if (host_error == -1)
11418 error (_("Unknown remote I/O error %d"), errnum);
11419 else
11420 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11421 }
11422
11423 static void
11424 remote_hostio_close_cleanup (void *opaque)
11425 {
11426 int fd = *(int *) opaque;
11427 int remote_errno;
11428
11429 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11430 }
11431
11432 void
11433 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11434 {
11435 struct cleanup *back_to, *close_cleanup;
11436 int retcode, fd, remote_errno, bytes, io_size;
11437 FILE *file;
11438 gdb_byte *buffer;
11439 int bytes_in_buffer;
11440 int saw_eof;
11441 ULONGEST offset;
11442 struct remote_state *rs = get_remote_state ();
11443
11444 if (!rs->remote_desc)
11445 error (_("command can only be used with remote target"));
11446
11447 file = gdb_fopen_cloexec (local_file, "rb");
11448 if (file == NULL)
11449 perror_with_name (local_file);
11450 back_to = make_cleanup_fclose (file);
11451
11452 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11453 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11454 | FILEIO_O_TRUNC),
11455 0700, 0, &remote_errno);
11456 if (fd == -1)
11457 remote_hostio_error (remote_errno);
11458
11459 /* Send up to this many bytes at once. They won't all fit in the
11460 remote packet limit, so we'll transfer slightly fewer. */
11461 io_size = get_remote_packet_size ();
11462 buffer = (gdb_byte *) xmalloc (io_size);
11463 make_cleanup (xfree, buffer);
11464
11465 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11466
11467 bytes_in_buffer = 0;
11468 saw_eof = 0;
11469 offset = 0;
11470 while (bytes_in_buffer || !saw_eof)
11471 {
11472 if (!saw_eof)
11473 {
11474 bytes = fread (buffer + bytes_in_buffer, 1,
11475 io_size - bytes_in_buffer,
11476 file);
11477 if (bytes == 0)
11478 {
11479 if (ferror (file))
11480 error (_("Error reading %s."), local_file);
11481 else
11482 {
11483 /* EOF. Unless there is something still in the
11484 buffer from the last iteration, we are done. */
11485 saw_eof = 1;
11486 if (bytes_in_buffer == 0)
11487 break;
11488 }
11489 }
11490 }
11491 else
11492 bytes = 0;
11493
11494 bytes += bytes_in_buffer;
11495 bytes_in_buffer = 0;
11496
11497 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11498 fd, buffer, bytes,
11499 offset, &remote_errno);
11500
11501 if (retcode < 0)
11502 remote_hostio_error (remote_errno);
11503 else if (retcode == 0)
11504 error (_("Remote write of %d bytes returned 0!"), bytes);
11505 else if (retcode < bytes)
11506 {
11507 /* Short write. Save the rest of the read data for the next
11508 write. */
11509 bytes_in_buffer = bytes - retcode;
11510 memmove (buffer, buffer + retcode, bytes_in_buffer);
11511 }
11512
11513 offset += retcode;
11514 }
11515
11516 discard_cleanups (close_cleanup);
11517 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11518 remote_hostio_error (remote_errno);
11519
11520 if (from_tty)
11521 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11522 do_cleanups (back_to);
11523 }
11524
11525 void
11526 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11527 {
11528 struct cleanup *back_to, *close_cleanup;
11529 int fd, remote_errno, bytes, io_size;
11530 FILE *file;
11531 gdb_byte *buffer;
11532 ULONGEST offset;
11533 struct remote_state *rs = get_remote_state ();
11534
11535 if (!rs->remote_desc)
11536 error (_("command can only be used with remote target"));
11537
11538 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11539 remote_file, FILEIO_O_RDONLY, 0, 0,
11540 &remote_errno);
11541 if (fd == -1)
11542 remote_hostio_error (remote_errno);
11543
11544 file = gdb_fopen_cloexec (local_file, "wb");
11545 if (file == NULL)
11546 perror_with_name (local_file);
11547 back_to = make_cleanup_fclose (file);
11548
11549 /* Send up to this many bytes at once. They won't all fit in the
11550 remote packet limit, so we'll transfer slightly fewer. */
11551 io_size = get_remote_packet_size ();
11552 buffer = (gdb_byte *) xmalloc (io_size);
11553 make_cleanup (xfree, buffer);
11554
11555 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11556
11557 offset = 0;
11558 while (1)
11559 {
11560 bytes = remote_hostio_pread (find_target_at (process_stratum),
11561 fd, buffer, io_size, offset, &remote_errno);
11562 if (bytes == 0)
11563 /* Success, but no bytes, means end-of-file. */
11564 break;
11565 if (bytes == -1)
11566 remote_hostio_error (remote_errno);
11567
11568 offset += bytes;
11569
11570 bytes = fwrite (buffer, 1, bytes, file);
11571 if (bytes == 0)
11572 perror_with_name (local_file);
11573 }
11574
11575 discard_cleanups (close_cleanup);
11576 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11577 remote_hostio_error (remote_errno);
11578
11579 if (from_tty)
11580 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11581 do_cleanups (back_to);
11582 }
11583
11584 void
11585 remote_file_delete (const char *remote_file, int from_tty)
11586 {
11587 int retcode, remote_errno;
11588 struct remote_state *rs = get_remote_state ();
11589
11590 if (!rs->remote_desc)
11591 error (_("command can only be used with remote target"));
11592
11593 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11594 NULL, remote_file, &remote_errno);
11595 if (retcode == -1)
11596 remote_hostio_error (remote_errno);
11597
11598 if (from_tty)
11599 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11600 }
11601
11602 static void
11603 remote_put_command (char *args, int from_tty)
11604 {
11605 struct cleanup *back_to;
11606 char **argv;
11607
11608 if (args == NULL)
11609 error_no_arg (_("file to put"));
11610
11611 argv = gdb_buildargv (args);
11612 back_to = make_cleanup_freeargv (argv);
11613 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11614 error (_("Invalid parameters to remote put"));
11615
11616 remote_file_put (argv[0], argv[1], from_tty);
11617
11618 do_cleanups (back_to);
11619 }
11620
11621 static void
11622 remote_get_command (char *args, int from_tty)
11623 {
11624 struct cleanup *back_to;
11625 char **argv;
11626
11627 if (args == NULL)
11628 error_no_arg (_("file to get"));
11629
11630 argv = gdb_buildargv (args);
11631 back_to = make_cleanup_freeargv (argv);
11632 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11633 error (_("Invalid parameters to remote get"));
11634
11635 remote_file_get (argv[0], argv[1], from_tty);
11636
11637 do_cleanups (back_to);
11638 }
11639
11640 static void
11641 remote_delete_command (char *args, int from_tty)
11642 {
11643 struct cleanup *back_to;
11644 char **argv;
11645
11646 if (args == NULL)
11647 error_no_arg (_("file to delete"));
11648
11649 argv = gdb_buildargv (args);
11650 back_to = make_cleanup_freeargv (argv);
11651 if (argv[0] == NULL || argv[1] != NULL)
11652 error (_("Invalid parameters to remote delete"));
11653
11654 remote_file_delete (argv[0], from_tty);
11655
11656 do_cleanups (back_to);
11657 }
11658
11659 static void
11660 remote_command (char *args, int from_tty)
11661 {
11662 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11663 }
11664
11665 static int
11666 remote_can_execute_reverse (struct target_ops *self)
11667 {
11668 if (packet_support (PACKET_bs) == PACKET_ENABLE
11669 || packet_support (PACKET_bc) == PACKET_ENABLE)
11670 return 1;
11671 else
11672 return 0;
11673 }
11674
11675 static int
11676 remote_supports_non_stop (struct target_ops *self)
11677 {
11678 return 1;
11679 }
11680
11681 static int
11682 remote_supports_disable_randomization (struct target_ops *self)
11683 {
11684 /* Only supported in extended mode. */
11685 return 0;
11686 }
11687
11688 static int
11689 remote_supports_multi_process (struct target_ops *self)
11690 {
11691 struct remote_state *rs = get_remote_state ();
11692
11693 return remote_multi_process_p (rs);
11694 }
11695
11696 static int
11697 remote_supports_cond_tracepoints (void)
11698 {
11699 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11700 }
11701
11702 static int
11703 remote_supports_cond_breakpoints (struct target_ops *self)
11704 {
11705 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11706 }
11707
11708 static int
11709 remote_supports_fast_tracepoints (void)
11710 {
11711 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11712 }
11713
11714 static int
11715 remote_supports_static_tracepoints (void)
11716 {
11717 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11718 }
11719
11720 static int
11721 remote_supports_install_in_trace (void)
11722 {
11723 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11724 }
11725
11726 static int
11727 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11728 {
11729 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11730 == PACKET_ENABLE);
11731 }
11732
11733 static int
11734 remote_supports_string_tracing (struct target_ops *self)
11735 {
11736 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11737 }
11738
11739 static int
11740 remote_can_run_breakpoint_commands (struct target_ops *self)
11741 {
11742 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11743 }
11744
11745 static void
11746 remote_trace_init (struct target_ops *self)
11747 {
11748 putpkt ("QTinit");
11749 remote_get_noisy_reply (&target_buf, &target_buf_size);
11750 if (strcmp (target_buf, "OK") != 0)
11751 error (_("Target does not support this command."));
11752 }
11753
11754 static void free_actions_list (char **actions_list);
11755 static void free_actions_list_cleanup_wrapper (void *);
11756 static void
11757 free_actions_list_cleanup_wrapper (void *al)
11758 {
11759 free_actions_list ((char **) al);
11760 }
11761
11762 static void
11763 free_actions_list (char **actions_list)
11764 {
11765 int ndx;
11766
11767 if (actions_list == 0)
11768 return;
11769
11770 for (ndx = 0; actions_list[ndx]; ndx++)
11771 xfree (actions_list[ndx]);
11772
11773 xfree (actions_list);
11774 }
11775
11776 /* Recursive routine to walk through command list including loops, and
11777 download packets for each command. */
11778
11779 static void
11780 remote_download_command_source (int num, ULONGEST addr,
11781 struct command_line *cmds)
11782 {
11783 struct remote_state *rs = get_remote_state ();
11784 struct command_line *cmd;
11785
11786 for (cmd = cmds; cmd; cmd = cmd->next)
11787 {
11788 QUIT; /* Allow user to bail out with ^C. */
11789 strcpy (rs->buf, "QTDPsrc:");
11790 encode_source_string (num, addr, "cmd", cmd->line,
11791 rs->buf + strlen (rs->buf),
11792 rs->buf_size - strlen (rs->buf));
11793 putpkt (rs->buf);
11794 remote_get_noisy_reply (&target_buf, &target_buf_size);
11795 if (strcmp (target_buf, "OK"))
11796 warning (_("Target does not support source download."));
11797
11798 if (cmd->control_type == while_control
11799 || cmd->control_type == while_stepping_control)
11800 {
11801 remote_download_command_source (num, addr, *cmd->body_list);
11802
11803 QUIT; /* Allow user to bail out with ^C. */
11804 strcpy (rs->buf, "QTDPsrc:");
11805 encode_source_string (num, addr, "cmd", "end",
11806 rs->buf + strlen (rs->buf),
11807 rs->buf_size - strlen (rs->buf));
11808 putpkt (rs->buf);
11809 remote_get_noisy_reply (&target_buf, &target_buf_size);
11810 if (strcmp (target_buf, "OK"))
11811 warning (_("Target does not support source download."));
11812 }
11813 }
11814 }
11815
11816 static void
11817 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11818 {
11819 #define BUF_SIZE 2048
11820
11821 CORE_ADDR tpaddr;
11822 char addrbuf[40];
11823 char buf[BUF_SIZE];
11824 char **tdp_actions;
11825 char **stepping_actions;
11826 int ndx;
11827 struct cleanup *old_chain = NULL;
11828 struct agent_expr *aexpr;
11829 struct cleanup *aexpr_chain = NULL;
11830 char *pkt;
11831 struct breakpoint *b = loc->owner;
11832 struct tracepoint *t = (struct tracepoint *) b;
11833
11834 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11835 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11836 tdp_actions);
11837 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11838 stepping_actions);
11839
11840 tpaddr = loc->address;
11841 sprintf_vma (addrbuf, tpaddr);
11842 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11843 addrbuf, /* address */
11844 (b->enable_state == bp_enabled ? 'E' : 'D'),
11845 t->step_count, t->pass_count);
11846 /* Fast tracepoints are mostly handled by the target, but we can
11847 tell the target how big of an instruction block should be moved
11848 around. */
11849 if (b->type == bp_fast_tracepoint)
11850 {
11851 /* Only test for support at download time; we may not know
11852 target capabilities at definition time. */
11853 if (remote_supports_fast_tracepoints ())
11854 {
11855 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11856 NULL))
11857 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11858 gdb_insn_length (loc->gdbarch, tpaddr));
11859 else
11860 /* If it passed validation at definition but fails now,
11861 something is very wrong. */
11862 internal_error (__FILE__, __LINE__,
11863 _("Fast tracepoint not "
11864 "valid during download"));
11865 }
11866 else
11867 /* Fast tracepoints are functionally identical to regular
11868 tracepoints, so don't take lack of support as a reason to
11869 give up on the trace run. */
11870 warning (_("Target does not support fast tracepoints, "
11871 "downloading %d as regular tracepoint"), b->number);
11872 }
11873 else if (b->type == bp_static_tracepoint)
11874 {
11875 /* Only test for support at download time; we may not know
11876 target capabilities at definition time. */
11877 if (remote_supports_static_tracepoints ())
11878 {
11879 struct static_tracepoint_marker marker;
11880
11881 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11882 strcat (buf, ":S");
11883 else
11884 error (_("Static tracepoint not valid during download"));
11885 }
11886 else
11887 /* Fast tracepoints are functionally identical to regular
11888 tracepoints, so don't take lack of support as a reason
11889 to give up on the trace run. */
11890 error (_("Target does not support static tracepoints"));
11891 }
11892 /* If the tracepoint has a conditional, make it into an agent
11893 expression and append to the definition. */
11894 if (loc->cond)
11895 {
11896 /* Only test support at download time, we may not know target
11897 capabilities at definition time. */
11898 if (remote_supports_cond_tracepoints ())
11899 {
11900 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11901 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11902 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11903 aexpr->len);
11904 pkt = buf + strlen (buf);
11905 for (ndx = 0; ndx < aexpr->len; ++ndx)
11906 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11907 *pkt = '\0';
11908 do_cleanups (aexpr_chain);
11909 }
11910 else
11911 warning (_("Target does not support conditional tracepoints, "
11912 "ignoring tp %d cond"), b->number);
11913 }
11914
11915 if (b->commands || *default_collect)
11916 strcat (buf, "-");
11917 putpkt (buf);
11918 remote_get_noisy_reply (&target_buf, &target_buf_size);
11919 if (strcmp (target_buf, "OK"))
11920 error (_("Target does not support tracepoints."));
11921
11922 /* do_single_steps (t); */
11923 if (tdp_actions)
11924 {
11925 for (ndx = 0; tdp_actions[ndx]; ndx++)
11926 {
11927 QUIT; /* Allow user to bail out with ^C. */
11928 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11929 b->number, addrbuf, /* address */
11930 tdp_actions[ndx],
11931 ((tdp_actions[ndx + 1] || stepping_actions)
11932 ? '-' : 0));
11933 putpkt (buf);
11934 remote_get_noisy_reply (&target_buf,
11935 &target_buf_size);
11936 if (strcmp (target_buf, "OK"))
11937 error (_("Error on target while setting tracepoints."));
11938 }
11939 }
11940 if (stepping_actions)
11941 {
11942 for (ndx = 0; stepping_actions[ndx]; ndx++)
11943 {
11944 QUIT; /* Allow user to bail out with ^C. */
11945 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11946 b->number, addrbuf, /* address */
11947 ((ndx == 0) ? "S" : ""),
11948 stepping_actions[ndx],
11949 (stepping_actions[ndx + 1] ? "-" : ""));
11950 putpkt (buf);
11951 remote_get_noisy_reply (&target_buf,
11952 &target_buf_size);
11953 if (strcmp (target_buf, "OK"))
11954 error (_("Error on target while setting tracepoints."));
11955 }
11956 }
11957
11958 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11959 {
11960 if (b->location != NULL)
11961 {
11962 strcpy (buf, "QTDPsrc:");
11963 encode_source_string (b->number, loc->address, "at",
11964 event_location_to_string (b->location),
11965 buf + strlen (buf), 2048 - strlen (buf));
11966 putpkt (buf);
11967 remote_get_noisy_reply (&target_buf, &target_buf_size);
11968 if (strcmp (target_buf, "OK"))
11969 warning (_("Target does not support source download."));
11970 }
11971 if (b->cond_string)
11972 {
11973 strcpy (buf, "QTDPsrc:");
11974 encode_source_string (b->number, loc->address,
11975 "cond", b->cond_string, buf + strlen (buf),
11976 2048 - strlen (buf));
11977 putpkt (buf);
11978 remote_get_noisy_reply (&target_buf, &target_buf_size);
11979 if (strcmp (target_buf, "OK"))
11980 warning (_("Target does not support source download."));
11981 }
11982 remote_download_command_source (b->number, loc->address,
11983 breakpoint_commands (b));
11984 }
11985
11986 do_cleanups (old_chain);
11987 }
11988
11989 static int
11990 remote_can_download_tracepoint (struct target_ops *self)
11991 {
11992 struct remote_state *rs = get_remote_state ();
11993 struct trace_status *ts;
11994 int status;
11995
11996 /* Don't try to install tracepoints until we've relocated our
11997 symbols, and fetched and merged the target's tracepoint list with
11998 ours. */
11999 if (rs->starting_up)
12000 return 0;
12001
12002 ts = current_trace_status ();
12003 status = remote_get_trace_status (self, ts);
12004
12005 if (status == -1 || !ts->running_known || !ts->running)
12006 return 0;
12007
12008 /* If we are in a tracing experiment, but remote stub doesn't support
12009 installing tracepoint in trace, we have to return. */
12010 if (!remote_supports_install_in_trace ())
12011 return 0;
12012
12013 return 1;
12014 }
12015
12016
12017 static void
12018 remote_download_trace_state_variable (struct target_ops *self,
12019 struct trace_state_variable *tsv)
12020 {
12021 struct remote_state *rs = get_remote_state ();
12022 char *p;
12023
12024 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12025 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12026 tsv->builtin);
12027 p = rs->buf + strlen (rs->buf);
12028 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12029 error (_("Trace state variable name too long for tsv definition packet"));
12030 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12031 *p++ = '\0';
12032 putpkt (rs->buf);
12033 remote_get_noisy_reply (&target_buf, &target_buf_size);
12034 if (*target_buf == '\0')
12035 error (_("Target does not support this command."));
12036 if (strcmp (target_buf, "OK") != 0)
12037 error (_("Error on target while downloading trace state variable."));
12038 }
12039
12040 static void
12041 remote_enable_tracepoint (struct target_ops *self,
12042 struct bp_location *location)
12043 {
12044 struct remote_state *rs = get_remote_state ();
12045 char addr_buf[40];
12046
12047 sprintf_vma (addr_buf, location->address);
12048 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12049 location->owner->number, addr_buf);
12050 putpkt (rs->buf);
12051 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12052 if (*rs->buf == '\0')
12053 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12054 if (strcmp (rs->buf, "OK") != 0)
12055 error (_("Error on target while enabling tracepoint."));
12056 }
12057
12058 static void
12059 remote_disable_tracepoint (struct target_ops *self,
12060 struct bp_location *location)
12061 {
12062 struct remote_state *rs = get_remote_state ();
12063 char addr_buf[40];
12064
12065 sprintf_vma (addr_buf, location->address);
12066 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12067 location->owner->number, addr_buf);
12068 putpkt (rs->buf);
12069 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12070 if (*rs->buf == '\0')
12071 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12072 if (strcmp (rs->buf, "OK") != 0)
12073 error (_("Error on target while disabling tracepoint."));
12074 }
12075
12076 static void
12077 remote_trace_set_readonly_regions (struct target_ops *self)
12078 {
12079 asection *s;
12080 bfd *abfd = NULL;
12081 bfd_size_type size;
12082 bfd_vma vma;
12083 int anysecs = 0;
12084 int offset = 0;
12085
12086 if (!exec_bfd)
12087 return; /* No information to give. */
12088
12089 strcpy (target_buf, "QTro");
12090 offset = strlen (target_buf);
12091 for (s = exec_bfd->sections; s; s = s->next)
12092 {
12093 char tmp1[40], tmp2[40];
12094 int sec_length;
12095
12096 if ((s->flags & SEC_LOAD) == 0 ||
12097 /* (s->flags & SEC_CODE) == 0 || */
12098 (s->flags & SEC_READONLY) == 0)
12099 continue;
12100
12101 anysecs = 1;
12102 vma = bfd_get_section_vma (abfd, s);
12103 size = bfd_get_section_size (s);
12104 sprintf_vma (tmp1, vma);
12105 sprintf_vma (tmp2, vma + size);
12106 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12107 if (offset + sec_length + 1 > target_buf_size)
12108 {
12109 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12110 warning (_("\
12111 Too many sections for read-only sections definition packet."));
12112 break;
12113 }
12114 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12115 tmp1, tmp2);
12116 offset += sec_length;
12117 }
12118 if (anysecs)
12119 {
12120 putpkt (target_buf);
12121 getpkt (&target_buf, &target_buf_size, 0);
12122 }
12123 }
12124
12125 static void
12126 remote_trace_start (struct target_ops *self)
12127 {
12128 putpkt ("QTStart");
12129 remote_get_noisy_reply (&target_buf, &target_buf_size);
12130 if (*target_buf == '\0')
12131 error (_("Target does not support this command."));
12132 if (strcmp (target_buf, "OK") != 0)
12133 error (_("Bogus reply from target: %s"), target_buf);
12134 }
12135
12136 static int
12137 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12138 {
12139 /* Initialize it just to avoid a GCC false warning. */
12140 char *p = NULL;
12141 /* FIXME we need to get register block size some other way. */
12142 extern int trace_regblock_size;
12143 enum packet_result result;
12144
12145 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12146 return -1;
12147
12148 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12149
12150 putpkt ("qTStatus");
12151
12152 TRY
12153 {
12154 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12155 }
12156 CATCH (ex, RETURN_MASK_ERROR)
12157 {
12158 if (ex.error != TARGET_CLOSE_ERROR)
12159 {
12160 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12161 return -1;
12162 }
12163 throw_exception (ex);
12164 }
12165 END_CATCH
12166
12167 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12168
12169 /* If the remote target doesn't do tracing, flag it. */
12170 if (result == PACKET_UNKNOWN)
12171 return -1;
12172
12173 /* We're working with a live target. */
12174 ts->filename = NULL;
12175
12176 if (*p++ != 'T')
12177 error (_("Bogus trace status reply from target: %s"), target_buf);
12178
12179 /* Function 'parse_trace_status' sets default value of each field of
12180 'ts' at first, so we don't have to do it here. */
12181 parse_trace_status (p, ts);
12182
12183 return ts->running;
12184 }
12185
12186 static void
12187 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12188 struct uploaded_tp *utp)
12189 {
12190 struct remote_state *rs = get_remote_state ();
12191 char *reply;
12192 struct bp_location *loc;
12193 struct tracepoint *tp = (struct tracepoint *) bp;
12194 size_t size = get_remote_packet_size ();
12195
12196 if (tp)
12197 {
12198 tp->base.hit_count = 0;
12199 tp->traceframe_usage = 0;
12200 for (loc = tp->base.loc; loc; loc = loc->next)
12201 {
12202 /* If the tracepoint was never downloaded, don't go asking for
12203 any status. */
12204 if (tp->number_on_target == 0)
12205 continue;
12206 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12207 phex_nz (loc->address, 0));
12208 putpkt (rs->buf);
12209 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12210 if (reply && *reply)
12211 {
12212 if (*reply == 'V')
12213 parse_tracepoint_status (reply + 1, bp, utp);
12214 }
12215 }
12216 }
12217 else if (utp)
12218 {
12219 utp->hit_count = 0;
12220 utp->traceframe_usage = 0;
12221 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12222 phex_nz (utp->addr, 0));
12223 putpkt (rs->buf);
12224 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12225 if (reply && *reply)
12226 {
12227 if (*reply == 'V')
12228 parse_tracepoint_status (reply + 1, bp, utp);
12229 }
12230 }
12231 }
12232
12233 static void
12234 remote_trace_stop (struct target_ops *self)
12235 {
12236 putpkt ("QTStop");
12237 remote_get_noisy_reply (&target_buf, &target_buf_size);
12238 if (*target_buf == '\0')
12239 error (_("Target does not support this command."));
12240 if (strcmp (target_buf, "OK") != 0)
12241 error (_("Bogus reply from target: %s"), target_buf);
12242 }
12243
12244 static int
12245 remote_trace_find (struct target_ops *self,
12246 enum trace_find_type type, int num,
12247 CORE_ADDR addr1, CORE_ADDR addr2,
12248 int *tpp)
12249 {
12250 struct remote_state *rs = get_remote_state ();
12251 char *endbuf = rs->buf + get_remote_packet_size ();
12252 char *p, *reply;
12253 int target_frameno = -1, target_tracept = -1;
12254
12255 /* Lookups other than by absolute frame number depend on the current
12256 trace selected, so make sure it is correct on the remote end
12257 first. */
12258 if (type != tfind_number)
12259 set_remote_traceframe ();
12260
12261 p = rs->buf;
12262 strcpy (p, "QTFrame:");
12263 p = strchr (p, '\0');
12264 switch (type)
12265 {
12266 case tfind_number:
12267 xsnprintf (p, endbuf - p, "%x", num);
12268 break;
12269 case tfind_pc:
12270 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12271 break;
12272 case tfind_tp:
12273 xsnprintf (p, endbuf - p, "tdp:%x", num);
12274 break;
12275 case tfind_range:
12276 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12277 phex_nz (addr2, 0));
12278 break;
12279 case tfind_outside:
12280 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12281 phex_nz (addr2, 0));
12282 break;
12283 default:
12284 error (_("Unknown trace find type %d"), type);
12285 }
12286
12287 putpkt (rs->buf);
12288 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12289 if (*reply == '\0')
12290 error (_("Target does not support this command."));
12291
12292 while (reply && *reply)
12293 switch (*reply)
12294 {
12295 case 'F':
12296 p = ++reply;
12297 target_frameno = (int) strtol (p, &reply, 16);
12298 if (reply == p)
12299 error (_("Unable to parse trace frame number"));
12300 /* Don't update our remote traceframe number cache on failure
12301 to select a remote traceframe. */
12302 if (target_frameno == -1)
12303 return -1;
12304 break;
12305 case 'T':
12306 p = ++reply;
12307 target_tracept = (int) strtol (p, &reply, 16);
12308 if (reply == p)
12309 error (_("Unable to parse tracepoint number"));
12310 break;
12311 case 'O': /* "OK"? */
12312 if (reply[1] == 'K' && reply[2] == '\0')
12313 reply += 2;
12314 else
12315 error (_("Bogus reply from target: %s"), reply);
12316 break;
12317 default:
12318 error (_("Bogus reply from target: %s"), reply);
12319 }
12320 if (tpp)
12321 *tpp = target_tracept;
12322
12323 rs->remote_traceframe_number = target_frameno;
12324 return target_frameno;
12325 }
12326
12327 static int
12328 remote_get_trace_state_variable_value (struct target_ops *self,
12329 int tsvnum, LONGEST *val)
12330 {
12331 struct remote_state *rs = get_remote_state ();
12332 char *reply;
12333 ULONGEST uval;
12334
12335 set_remote_traceframe ();
12336
12337 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12338 putpkt (rs->buf);
12339 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12340 if (reply && *reply)
12341 {
12342 if (*reply == 'V')
12343 {
12344 unpack_varlen_hex (reply + 1, &uval);
12345 *val = (LONGEST) uval;
12346 return 1;
12347 }
12348 }
12349 return 0;
12350 }
12351
12352 static int
12353 remote_save_trace_data (struct target_ops *self, const char *filename)
12354 {
12355 struct remote_state *rs = get_remote_state ();
12356 char *p, *reply;
12357
12358 p = rs->buf;
12359 strcpy (p, "QTSave:");
12360 p += strlen (p);
12361 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12362 error (_("Remote file name too long for trace save packet"));
12363 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12364 *p++ = '\0';
12365 putpkt (rs->buf);
12366 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12367 if (*reply == '\0')
12368 error (_("Target does not support this command."));
12369 if (strcmp (reply, "OK") != 0)
12370 error (_("Bogus reply from target: %s"), reply);
12371 return 0;
12372 }
12373
12374 /* This is basically a memory transfer, but needs to be its own packet
12375 because we don't know how the target actually organizes its trace
12376 memory, plus we want to be able to ask for as much as possible, but
12377 not be unhappy if we don't get as much as we ask for. */
12378
12379 static LONGEST
12380 remote_get_raw_trace_data (struct target_ops *self,
12381 gdb_byte *buf, ULONGEST offset, LONGEST len)
12382 {
12383 struct remote_state *rs = get_remote_state ();
12384 char *reply;
12385 char *p;
12386 int rslt;
12387
12388 p = rs->buf;
12389 strcpy (p, "qTBuffer:");
12390 p += strlen (p);
12391 p += hexnumstr (p, offset);
12392 *p++ = ',';
12393 p += hexnumstr (p, len);
12394 *p++ = '\0';
12395
12396 putpkt (rs->buf);
12397 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12398 if (reply && *reply)
12399 {
12400 /* 'l' by itself means we're at the end of the buffer and
12401 there is nothing more to get. */
12402 if (*reply == 'l')
12403 return 0;
12404
12405 /* Convert the reply into binary. Limit the number of bytes to
12406 convert according to our passed-in buffer size, rather than
12407 what was returned in the packet; if the target is
12408 unexpectedly generous and gives us a bigger reply than we
12409 asked for, we don't want to crash. */
12410 rslt = hex2bin (target_buf, buf, len);
12411 return rslt;
12412 }
12413
12414 /* Something went wrong, flag as an error. */
12415 return -1;
12416 }
12417
12418 static void
12419 remote_set_disconnected_tracing (struct target_ops *self, int val)
12420 {
12421 struct remote_state *rs = get_remote_state ();
12422
12423 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12424 {
12425 char *reply;
12426
12427 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12428 putpkt (rs->buf);
12429 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12430 if (*reply == '\0')
12431 error (_("Target does not support this command."));
12432 if (strcmp (reply, "OK") != 0)
12433 error (_("Bogus reply from target: %s"), reply);
12434 }
12435 else if (val)
12436 warning (_("Target does not support disconnected tracing."));
12437 }
12438
12439 static int
12440 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12441 {
12442 struct thread_info *info = find_thread_ptid (ptid);
12443
12444 if (info && info->priv)
12445 return info->priv->core;
12446 return -1;
12447 }
12448
12449 static void
12450 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12451 {
12452 struct remote_state *rs = get_remote_state ();
12453 char *reply;
12454
12455 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12456 putpkt (rs->buf);
12457 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12458 if (*reply == '\0')
12459 error (_("Target does not support this command."));
12460 if (strcmp (reply, "OK") != 0)
12461 error (_("Bogus reply from target: %s"), reply);
12462 }
12463
12464 static struct traceframe_info *
12465 remote_traceframe_info (struct target_ops *self)
12466 {
12467 char *text;
12468
12469 text = target_read_stralloc (&current_target,
12470 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12471 if (text != NULL)
12472 {
12473 struct traceframe_info *info;
12474 struct cleanup *back_to = make_cleanup (xfree, text);
12475
12476 info = parse_traceframe_info (text);
12477 do_cleanups (back_to);
12478 return info;
12479 }
12480
12481 return NULL;
12482 }
12483
12484 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12485 instruction on which a fast tracepoint may be placed. Returns -1
12486 if the packet is not supported, and 0 if the minimum instruction
12487 length is unknown. */
12488
12489 static int
12490 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12491 {
12492 struct remote_state *rs = get_remote_state ();
12493 char *reply;
12494
12495 /* If we're not debugging a process yet, the IPA can't be
12496 loaded. */
12497 if (!target_has_execution)
12498 return 0;
12499
12500 /* Make sure the remote is pointing at the right process. */
12501 set_general_process ();
12502
12503 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12504 putpkt (rs->buf);
12505 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12506 if (*reply == '\0')
12507 return -1;
12508 else
12509 {
12510 ULONGEST min_insn_len;
12511
12512 unpack_varlen_hex (reply, &min_insn_len);
12513
12514 return (int) min_insn_len;
12515 }
12516 }
12517
12518 static void
12519 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12520 {
12521 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12522 {
12523 struct remote_state *rs = get_remote_state ();
12524 char *buf = rs->buf;
12525 char *endbuf = rs->buf + get_remote_packet_size ();
12526 enum packet_result result;
12527
12528 gdb_assert (val >= 0 || val == -1);
12529 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12530 /* Send -1 as literal "-1" to avoid host size dependency. */
12531 if (val < 0)
12532 {
12533 *buf++ = '-';
12534 buf += hexnumstr (buf, (ULONGEST) -val);
12535 }
12536 else
12537 buf += hexnumstr (buf, (ULONGEST) val);
12538
12539 putpkt (rs->buf);
12540 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12541 result = packet_ok (rs->buf,
12542 &remote_protocol_packets[PACKET_QTBuffer_size]);
12543
12544 if (result != PACKET_OK)
12545 warning (_("Bogus reply from target: %s"), rs->buf);
12546 }
12547 }
12548
12549 static int
12550 remote_set_trace_notes (struct target_ops *self,
12551 const char *user, const char *notes,
12552 const char *stop_notes)
12553 {
12554 struct remote_state *rs = get_remote_state ();
12555 char *reply;
12556 char *buf = rs->buf;
12557 char *endbuf = rs->buf + get_remote_packet_size ();
12558 int nbytes;
12559
12560 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12561 if (user)
12562 {
12563 buf += xsnprintf (buf, endbuf - buf, "user:");
12564 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12565 buf += 2 * nbytes;
12566 *buf++ = ';';
12567 }
12568 if (notes)
12569 {
12570 buf += xsnprintf (buf, endbuf - buf, "notes:");
12571 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12572 buf += 2 * nbytes;
12573 *buf++ = ';';
12574 }
12575 if (stop_notes)
12576 {
12577 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12578 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12579 buf += 2 * nbytes;
12580 *buf++ = ';';
12581 }
12582 /* Ensure the buffer is terminated. */
12583 *buf = '\0';
12584
12585 putpkt (rs->buf);
12586 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12587 if (*reply == '\0')
12588 return 0;
12589
12590 if (strcmp (reply, "OK") != 0)
12591 error (_("Bogus reply from target: %s"), reply);
12592
12593 return 1;
12594 }
12595
12596 static int
12597 remote_use_agent (struct target_ops *self, int use)
12598 {
12599 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12600 {
12601 struct remote_state *rs = get_remote_state ();
12602
12603 /* If the stub supports QAgent. */
12604 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12605 putpkt (rs->buf);
12606 getpkt (&rs->buf, &rs->buf_size, 0);
12607
12608 if (strcmp (rs->buf, "OK") == 0)
12609 {
12610 use_agent = use;
12611 return 1;
12612 }
12613 }
12614
12615 return 0;
12616 }
12617
12618 static int
12619 remote_can_use_agent (struct target_ops *self)
12620 {
12621 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12622 }
12623
12624 struct btrace_target_info
12625 {
12626 /* The ptid of the traced thread. */
12627 ptid_t ptid;
12628
12629 /* The obtained branch trace configuration. */
12630 struct btrace_config conf;
12631 };
12632
12633 /* Reset our idea of our target's btrace configuration. */
12634
12635 static void
12636 remote_btrace_reset (void)
12637 {
12638 struct remote_state *rs = get_remote_state ();
12639
12640 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12641 }
12642
12643 /* Check whether the target supports branch tracing. */
12644
12645 static int
12646 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12647 {
12648 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12649 return 0;
12650 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12651 return 0;
12652
12653 switch (format)
12654 {
12655 case BTRACE_FORMAT_NONE:
12656 return 0;
12657
12658 case BTRACE_FORMAT_BTS:
12659 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12660
12661 case BTRACE_FORMAT_PT:
12662 /* The trace is decoded on the host. Even if our target supports it,
12663 we still need to have libipt to decode the trace. */
12664 #if defined (HAVE_LIBIPT)
12665 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12666 #else /* !defined (HAVE_LIBIPT) */
12667 return 0;
12668 #endif /* !defined (HAVE_LIBIPT) */
12669 }
12670
12671 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12672 }
12673
12674 /* Synchronize the configuration with the target. */
12675
12676 static void
12677 btrace_sync_conf (const struct btrace_config *conf)
12678 {
12679 struct packet_config *packet;
12680 struct remote_state *rs;
12681 char *buf, *pos, *endbuf;
12682
12683 rs = get_remote_state ();
12684 buf = rs->buf;
12685 endbuf = buf + get_remote_packet_size ();
12686
12687 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12688 if (packet_config_support (packet) == PACKET_ENABLE
12689 && conf->bts.size != rs->btrace_config.bts.size)
12690 {
12691 pos = buf;
12692 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12693 conf->bts.size);
12694
12695 putpkt (buf);
12696 getpkt (&buf, &rs->buf_size, 0);
12697
12698 if (packet_ok (buf, packet) == PACKET_ERROR)
12699 {
12700 if (buf[0] == 'E' && buf[1] == '.')
12701 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12702 else
12703 error (_("Failed to configure the BTS buffer size."));
12704 }
12705
12706 rs->btrace_config.bts.size = conf->bts.size;
12707 }
12708
12709 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12710 if (packet_config_support (packet) == PACKET_ENABLE
12711 && conf->pt.size != rs->btrace_config.pt.size)
12712 {
12713 pos = buf;
12714 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12715 conf->pt.size);
12716
12717 putpkt (buf);
12718 getpkt (&buf, &rs->buf_size, 0);
12719
12720 if (packet_ok (buf, packet) == PACKET_ERROR)
12721 {
12722 if (buf[0] == 'E' && buf[1] == '.')
12723 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12724 else
12725 error (_("Failed to configure the trace buffer size."));
12726 }
12727
12728 rs->btrace_config.pt.size = conf->pt.size;
12729 }
12730 }
12731
12732 /* Read the current thread's btrace configuration from the target and
12733 store it into CONF. */
12734
12735 static void
12736 btrace_read_config (struct btrace_config *conf)
12737 {
12738 char *xml;
12739
12740 xml = target_read_stralloc (&current_target,
12741 TARGET_OBJECT_BTRACE_CONF, "");
12742 if (xml != NULL)
12743 {
12744 struct cleanup *cleanup;
12745
12746 cleanup = make_cleanup (xfree, xml);
12747 parse_xml_btrace_conf (conf, xml);
12748 do_cleanups (cleanup);
12749 }
12750 }
12751
12752 /* Enable branch tracing. */
12753
12754 static struct btrace_target_info *
12755 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12756 const struct btrace_config *conf)
12757 {
12758 struct btrace_target_info *tinfo = NULL;
12759 struct packet_config *packet = NULL;
12760 struct remote_state *rs = get_remote_state ();
12761 char *buf = rs->buf;
12762 char *endbuf = rs->buf + get_remote_packet_size ();
12763
12764 switch (conf->format)
12765 {
12766 case BTRACE_FORMAT_BTS:
12767 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12768 break;
12769
12770 case BTRACE_FORMAT_PT:
12771 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12772 break;
12773 }
12774
12775 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12776 error (_("Target does not support branch tracing."));
12777
12778 btrace_sync_conf (conf);
12779
12780 set_general_thread (ptid);
12781
12782 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12783 putpkt (rs->buf);
12784 getpkt (&rs->buf, &rs->buf_size, 0);
12785
12786 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12787 {
12788 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12789 error (_("Could not enable branch tracing for %s: %s"),
12790 target_pid_to_str (ptid), rs->buf + 2);
12791 else
12792 error (_("Could not enable branch tracing for %s."),
12793 target_pid_to_str (ptid));
12794 }
12795
12796 tinfo = XCNEW (struct btrace_target_info);
12797 tinfo->ptid = ptid;
12798
12799 /* If we fail to read the configuration, we lose some information, but the
12800 tracing itself is not impacted. */
12801 TRY
12802 {
12803 btrace_read_config (&tinfo->conf);
12804 }
12805 CATCH (err, RETURN_MASK_ERROR)
12806 {
12807 if (err.message != NULL)
12808 warning ("%s", err.message);
12809 }
12810 END_CATCH
12811
12812 return tinfo;
12813 }
12814
12815 /* Disable branch tracing. */
12816
12817 static void
12818 remote_disable_btrace (struct target_ops *self,
12819 struct btrace_target_info *tinfo)
12820 {
12821 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12822 struct remote_state *rs = get_remote_state ();
12823 char *buf = rs->buf;
12824 char *endbuf = rs->buf + get_remote_packet_size ();
12825
12826 if (packet_config_support (packet) != PACKET_ENABLE)
12827 error (_("Target does not support branch tracing."));
12828
12829 set_general_thread (tinfo->ptid);
12830
12831 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12832 putpkt (rs->buf);
12833 getpkt (&rs->buf, &rs->buf_size, 0);
12834
12835 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12836 {
12837 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12838 error (_("Could not disable branch tracing for %s: %s"),
12839 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12840 else
12841 error (_("Could not disable branch tracing for %s."),
12842 target_pid_to_str (tinfo->ptid));
12843 }
12844
12845 xfree (tinfo);
12846 }
12847
12848 /* Teardown branch tracing. */
12849
12850 static void
12851 remote_teardown_btrace (struct target_ops *self,
12852 struct btrace_target_info *tinfo)
12853 {
12854 /* We must not talk to the target during teardown. */
12855 xfree (tinfo);
12856 }
12857
12858 /* Read the branch trace. */
12859
12860 static enum btrace_error
12861 remote_read_btrace (struct target_ops *self,
12862 struct btrace_data *btrace,
12863 struct btrace_target_info *tinfo,
12864 enum btrace_read_type type)
12865 {
12866 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12867 struct cleanup *cleanup;
12868 const char *annex;
12869 char *xml;
12870
12871 if (packet_config_support (packet) != PACKET_ENABLE)
12872 error (_("Target does not support branch tracing."));
12873
12874 #if !defined(HAVE_LIBEXPAT)
12875 error (_("Cannot process branch tracing result. XML parsing not supported."));
12876 #endif
12877
12878 switch (type)
12879 {
12880 case BTRACE_READ_ALL:
12881 annex = "all";
12882 break;
12883 case BTRACE_READ_NEW:
12884 annex = "new";
12885 break;
12886 case BTRACE_READ_DELTA:
12887 annex = "delta";
12888 break;
12889 default:
12890 internal_error (__FILE__, __LINE__,
12891 _("Bad branch tracing read type: %u."),
12892 (unsigned int) type);
12893 }
12894
12895 xml = target_read_stralloc (&current_target,
12896 TARGET_OBJECT_BTRACE, annex);
12897 if (xml == NULL)
12898 return BTRACE_ERR_UNKNOWN;
12899
12900 cleanup = make_cleanup (xfree, xml);
12901 parse_xml_btrace (btrace, xml);
12902 do_cleanups (cleanup);
12903
12904 return BTRACE_ERR_NONE;
12905 }
12906
12907 static const struct btrace_config *
12908 remote_btrace_conf (struct target_ops *self,
12909 const struct btrace_target_info *tinfo)
12910 {
12911 return &tinfo->conf;
12912 }
12913
12914 static int
12915 remote_augmented_libraries_svr4_read (struct target_ops *self)
12916 {
12917 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12918 == PACKET_ENABLE);
12919 }
12920
12921 /* Implementation of to_load. */
12922
12923 static void
12924 remote_load (struct target_ops *self, const char *name, int from_tty)
12925 {
12926 generic_load (name, from_tty);
12927 }
12928
12929 /* Accepts an integer PID; returns a string representing a file that
12930 can be opened on the remote side to get the symbols for the child
12931 process. Returns NULL if the operation is not supported. */
12932
12933 static char *
12934 remote_pid_to_exec_file (struct target_ops *self, int pid)
12935 {
12936 static char *filename = NULL;
12937 struct inferior *inf;
12938 char *annex = NULL;
12939
12940 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12941 return NULL;
12942
12943 if (filename != NULL)
12944 xfree (filename);
12945
12946 inf = find_inferior_pid (pid);
12947 if (inf == NULL)
12948 internal_error (__FILE__, __LINE__,
12949 _("not currently attached to process %d"), pid);
12950
12951 if (!inf->fake_pid_p)
12952 {
12953 const int annex_size = 9;
12954
12955 annex = (char *) alloca (annex_size);
12956 xsnprintf (annex, annex_size, "%x", pid);
12957 }
12958
12959 filename = target_read_stralloc (&current_target,
12960 TARGET_OBJECT_EXEC_FILE, annex);
12961
12962 return filename;
12963 }
12964
12965 /* Implement the to_can_do_single_step target_ops method. */
12966
12967 static int
12968 remote_can_do_single_step (struct target_ops *ops)
12969 {
12970 /* We can only tell whether target supports single step or not by
12971 supported s and S vCont actions if the stub supports vContSupported
12972 feature. If the stub doesn't support vContSupported feature,
12973 we have conservatively to think target doesn't supports single
12974 step. */
12975 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12976 {
12977 struct remote_state *rs = get_remote_state ();
12978
12979 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12980 remote_vcont_probe (rs);
12981
12982 return rs->supports_vCont.s && rs->supports_vCont.S;
12983 }
12984 else
12985 return 0;
12986 }
12987
12988 static void
12989 init_remote_ops (void)
12990 {
12991 remote_ops.to_shortname = "remote";
12992 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12993 remote_ops.to_doc =
12994 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12995 Specify the serial device it is connected to\n\
12996 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12997 remote_ops.to_open = remote_open;
12998 remote_ops.to_close = remote_close;
12999 remote_ops.to_detach = remote_detach;
13000 remote_ops.to_disconnect = remote_disconnect;
13001 remote_ops.to_resume = remote_resume;
13002 remote_ops.to_wait = remote_wait;
13003 remote_ops.to_fetch_registers = remote_fetch_registers;
13004 remote_ops.to_store_registers = remote_store_registers;
13005 remote_ops.to_prepare_to_store = remote_prepare_to_store;
13006 remote_ops.to_files_info = remote_files_info;
13007 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13008 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13009 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13010 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13011 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13012 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13013 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13014 remote_ops.to_stopped_data_address = remote_stopped_data_address;
13015 remote_ops.to_watchpoint_addr_within_range =
13016 remote_watchpoint_addr_within_range;
13017 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13018 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13019 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13020 remote_ops.to_region_ok_for_hw_watchpoint
13021 = remote_region_ok_for_hw_watchpoint;
13022 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13023 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13024 remote_ops.to_kill = remote_kill;
13025 remote_ops.to_load = remote_load;
13026 remote_ops.to_mourn_inferior = remote_mourn;
13027 remote_ops.to_pass_signals = remote_pass_signals;
13028 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13029 remote_ops.to_program_signals = remote_program_signals;
13030 remote_ops.to_thread_alive = remote_thread_alive;
13031 remote_ops.to_thread_name = remote_thread_name;
13032 remote_ops.to_update_thread_list = remote_update_thread_list;
13033 remote_ops.to_pid_to_str = remote_pid_to_str;
13034 remote_ops.to_extra_thread_info = remote_threads_extra_info;
13035 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13036 remote_ops.to_stop = remote_stop;
13037 remote_ops.to_interrupt = remote_interrupt;
13038 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13039 remote_ops.to_xfer_partial = remote_xfer_partial;
13040 remote_ops.to_rcmd = remote_rcmd;
13041 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13042 remote_ops.to_log_command = serial_log_command;
13043 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13044 remote_ops.to_stratum = process_stratum;
13045 remote_ops.to_has_all_memory = default_child_has_all_memory;
13046 remote_ops.to_has_memory = default_child_has_memory;
13047 remote_ops.to_has_stack = default_child_has_stack;
13048 remote_ops.to_has_registers = default_child_has_registers;
13049 remote_ops.to_has_execution = default_child_has_execution;
13050 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
13051 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13052 remote_ops.to_magic = OPS_MAGIC;
13053 remote_ops.to_memory_map = remote_memory_map;
13054 remote_ops.to_flash_erase = remote_flash_erase;
13055 remote_ops.to_flash_done = remote_flash_done;
13056 remote_ops.to_read_description = remote_read_description;
13057 remote_ops.to_search_memory = remote_search_memory;
13058 remote_ops.to_can_async_p = remote_can_async_p;
13059 remote_ops.to_is_async_p = remote_is_async_p;
13060 remote_ops.to_async = remote_async;
13061 remote_ops.to_thread_events = remote_thread_events;
13062 remote_ops.to_can_do_single_step = remote_can_do_single_step;
13063 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13064 remote_ops.to_terminal_ours = remote_terminal_ours;
13065 remote_ops.to_supports_non_stop = remote_supports_non_stop;
13066 remote_ops.to_supports_multi_process = remote_supports_multi_process;
13067 remote_ops.to_supports_disable_randomization
13068 = remote_supports_disable_randomization;
13069 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13070 remote_ops.to_fileio_open = remote_hostio_open;
13071 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13072 remote_ops.to_fileio_pread = remote_hostio_pread;
13073 remote_ops.to_fileio_fstat = remote_hostio_fstat;
13074 remote_ops.to_fileio_close = remote_hostio_close;
13075 remote_ops.to_fileio_unlink = remote_hostio_unlink;
13076 remote_ops.to_fileio_readlink = remote_hostio_readlink;
13077 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13078 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13079 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13080 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13081 remote_ops.to_trace_init = remote_trace_init;
13082 remote_ops.to_download_tracepoint = remote_download_tracepoint;
13083 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13084 remote_ops.to_download_trace_state_variable
13085 = remote_download_trace_state_variable;
13086 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13087 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13088 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13089 remote_ops.to_trace_start = remote_trace_start;
13090 remote_ops.to_get_trace_status = remote_get_trace_status;
13091 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13092 remote_ops.to_trace_stop = remote_trace_stop;
13093 remote_ops.to_trace_find = remote_trace_find;
13094 remote_ops.to_get_trace_state_variable_value
13095 = remote_get_trace_state_variable_value;
13096 remote_ops.to_save_trace_data = remote_save_trace_data;
13097 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13098 remote_ops.to_upload_trace_state_variables
13099 = remote_upload_trace_state_variables;
13100 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13101 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13102 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13103 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13104 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13105 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13106 remote_ops.to_core_of_thread = remote_core_of_thread;
13107 remote_ops.to_verify_memory = remote_verify_memory;
13108 remote_ops.to_get_tib_address = remote_get_tib_address;
13109 remote_ops.to_set_permissions = remote_set_permissions;
13110 remote_ops.to_static_tracepoint_marker_at
13111 = remote_static_tracepoint_marker_at;
13112 remote_ops.to_static_tracepoint_markers_by_strid
13113 = remote_static_tracepoint_markers_by_strid;
13114 remote_ops.to_traceframe_info = remote_traceframe_info;
13115 remote_ops.to_use_agent = remote_use_agent;
13116 remote_ops.to_can_use_agent = remote_can_use_agent;
13117 remote_ops.to_supports_btrace = remote_supports_btrace;
13118 remote_ops.to_enable_btrace = remote_enable_btrace;
13119 remote_ops.to_disable_btrace = remote_disable_btrace;
13120 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13121 remote_ops.to_read_btrace = remote_read_btrace;
13122 remote_ops.to_btrace_conf = remote_btrace_conf;
13123 remote_ops.to_augmented_libraries_svr4_read =
13124 remote_augmented_libraries_svr4_read;
13125 remote_ops.to_follow_fork = remote_follow_fork;
13126 remote_ops.to_follow_exec = remote_follow_exec;
13127 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13128 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13129 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13130 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13131 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13132 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13133 }
13134
13135 /* Set up the extended remote vector by making a copy of the standard
13136 remote vector and adding to it. */
13137
13138 static void
13139 init_extended_remote_ops (void)
13140 {
13141 extended_remote_ops = remote_ops;
13142
13143 extended_remote_ops.to_shortname = "extended-remote";
13144 extended_remote_ops.to_longname =
13145 "Extended remote serial target in gdb-specific protocol";
13146 extended_remote_ops.to_doc =
13147 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13148 Specify the serial device it is connected to (e.g. /dev/ttya).";
13149 extended_remote_ops.to_open = extended_remote_open;
13150 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13151 extended_remote_ops.to_detach = extended_remote_detach;
13152 extended_remote_ops.to_attach = extended_remote_attach;
13153 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13154 extended_remote_ops.to_supports_disable_randomization
13155 = extended_remote_supports_disable_randomization;
13156 }
13157
13158 static int
13159 remote_can_async_p (struct target_ops *ops)
13160 {
13161 struct remote_state *rs = get_remote_state ();
13162
13163 if (!target_async_permitted)
13164 /* We only enable async when the user specifically asks for it. */
13165 return 0;
13166
13167 /* We're async whenever the serial device is. */
13168 return serial_can_async_p (rs->remote_desc);
13169 }
13170
13171 static int
13172 remote_is_async_p (struct target_ops *ops)
13173 {
13174 struct remote_state *rs = get_remote_state ();
13175
13176 if (!target_async_permitted)
13177 /* We only enable async when the user specifically asks for it. */
13178 return 0;
13179
13180 /* We're async whenever the serial device is. */
13181 return serial_is_async_p (rs->remote_desc);
13182 }
13183
13184 /* Pass the SERIAL event on and up to the client. One day this code
13185 will be able to delay notifying the client of an event until the
13186 point where an entire packet has been received. */
13187
13188 static serial_event_ftype remote_async_serial_handler;
13189
13190 static void
13191 remote_async_serial_handler (struct serial *scb, void *context)
13192 {
13193 /* Don't propogate error information up to the client. Instead let
13194 the client find out about the error by querying the target. */
13195 inferior_event_handler (INF_REG_EVENT, NULL);
13196 }
13197
13198 static void
13199 remote_async_inferior_event_handler (gdb_client_data data)
13200 {
13201 inferior_event_handler (INF_REG_EVENT, NULL);
13202 }
13203
13204 static void
13205 remote_async (struct target_ops *ops, int enable)
13206 {
13207 struct remote_state *rs = get_remote_state ();
13208
13209 if (enable)
13210 {
13211 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13212
13213 /* If there are pending events in the stop reply queue tell the
13214 event loop to process them. */
13215 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13216 mark_async_event_handler (remote_async_inferior_event_token);
13217 /* For simplicity, below we clear the pending events token
13218 without remembering whether it is marked, so here we always
13219 mark it. If there's actually no pending notification to
13220 process, this ends up being a no-op (other than a spurious
13221 event-loop wakeup). */
13222 if (target_is_non_stop_p ())
13223 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13224 }
13225 else
13226 {
13227 serial_async (rs->remote_desc, NULL, NULL);
13228 /* If the core is disabling async, it doesn't want to be
13229 disturbed with target events. Clear all async event sources
13230 too. */
13231 clear_async_event_handler (remote_async_inferior_event_token);
13232 if (target_is_non_stop_p ())
13233 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13234 }
13235 }
13236
13237 /* Implementation of the to_thread_events method. */
13238
13239 static void
13240 remote_thread_events (struct target_ops *ops, int enable)
13241 {
13242 struct remote_state *rs = get_remote_state ();
13243 size_t size = get_remote_packet_size ();
13244
13245 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13246 return;
13247
13248 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13249 putpkt (rs->buf);
13250 getpkt (&rs->buf, &rs->buf_size, 0);
13251
13252 switch (packet_ok (rs->buf,
13253 &remote_protocol_packets[PACKET_QThreadEvents]))
13254 {
13255 case PACKET_OK:
13256 if (strcmp (rs->buf, "OK") != 0)
13257 error (_("Remote refused setting thread events: %s"), rs->buf);
13258 break;
13259 case PACKET_ERROR:
13260 warning (_("Remote failure reply: %s"), rs->buf);
13261 break;
13262 case PACKET_UNKNOWN:
13263 break;
13264 }
13265 }
13266
13267 static void
13268 set_remote_cmd (char *args, int from_tty)
13269 {
13270 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13271 }
13272
13273 static void
13274 show_remote_cmd (char *args, int from_tty)
13275 {
13276 /* We can't just use cmd_show_list here, because we want to skip
13277 the redundant "show remote Z-packet" and the legacy aliases. */
13278 struct cleanup *showlist_chain;
13279 struct cmd_list_element *list = remote_show_cmdlist;
13280 struct ui_out *uiout = current_uiout;
13281
13282 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13283 for (; list != NULL; list = list->next)
13284 if (strcmp (list->name, "Z-packet") == 0)
13285 continue;
13286 else if (list->type == not_set_cmd)
13287 /* Alias commands are exactly like the original, except they
13288 don't have the normal type. */
13289 continue;
13290 else
13291 {
13292 struct cleanup *option_chain
13293 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13294
13295 ui_out_field_string (uiout, "name", list->name);
13296 ui_out_text (uiout, ": ");
13297 if (list->type == show_cmd)
13298 do_show_command ((char *) NULL, from_tty, list);
13299 else
13300 cmd_func (list, NULL, from_tty);
13301 /* Close the tuple. */
13302 do_cleanups (option_chain);
13303 }
13304
13305 /* Close the tuple. */
13306 do_cleanups (showlist_chain);
13307 }
13308
13309
13310 /* Function to be called whenever a new objfile (shlib) is detected. */
13311 static void
13312 remote_new_objfile (struct objfile *objfile)
13313 {
13314 struct remote_state *rs = get_remote_state ();
13315
13316 if (rs->remote_desc != 0) /* Have a remote connection. */
13317 remote_check_symbols ();
13318 }
13319
13320 /* Pull all the tracepoints defined on the target and create local
13321 data structures representing them. We don't want to create real
13322 tracepoints yet, we don't want to mess up the user's existing
13323 collection. */
13324
13325 static int
13326 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13327 {
13328 struct remote_state *rs = get_remote_state ();
13329 char *p;
13330
13331 /* Ask for a first packet of tracepoint definition. */
13332 putpkt ("qTfP");
13333 getpkt (&rs->buf, &rs->buf_size, 0);
13334 p = rs->buf;
13335 while (*p && *p != 'l')
13336 {
13337 parse_tracepoint_definition (p, utpp);
13338 /* Ask for another packet of tracepoint definition. */
13339 putpkt ("qTsP");
13340 getpkt (&rs->buf, &rs->buf_size, 0);
13341 p = rs->buf;
13342 }
13343 return 0;
13344 }
13345
13346 static int
13347 remote_upload_trace_state_variables (struct target_ops *self,
13348 struct uploaded_tsv **utsvp)
13349 {
13350 struct remote_state *rs = get_remote_state ();
13351 char *p;
13352
13353 /* Ask for a first packet of variable definition. */
13354 putpkt ("qTfV");
13355 getpkt (&rs->buf, &rs->buf_size, 0);
13356 p = rs->buf;
13357 while (*p && *p != 'l')
13358 {
13359 parse_tsv_definition (p, utsvp);
13360 /* Ask for another packet of variable definition. */
13361 putpkt ("qTsV");
13362 getpkt (&rs->buf, &rs->buf_size, 0);
13363 p = rs->buf;
13364 }
13365 return 0;
13366 }
13367
13368 /* The "set/show range-stepping" show hook. */
13369
13370 static void
13371 show_range_stepping (struct ui_file *file, int from_tty,
13372 struct cmd_list_element *c,
13373 const char *value)
13374 {
13375 fprintf_filtered (file,
13376 _("Debugger's willingness to use range stepping "
13377 "is %s.\n"), value);
13378 }
13379
13380 /* The "set/show range-stepping" set hook. */
13381
13382 static void
13383 set_range_stepping (char *ignore_args, int from_tty,
13384 struct cmd_list_element *c)
13385 {
13386 struct remote_state *rs = get_remote_state ();
13387
13388 /* Whene enabling, check whether range stepping is actually
13389 supported by the target, and warn if not. */
13390 if (use_range_stepping)
13391 {
13392 if (rs->remote_desc != NULL)
13393 {
13394 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13395 remote_vcont_probe (rs);
13396
13397 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13398 && rs->supports_vCont.r)
13399 return;
13400 }
13401
13402 warning (_("Range stepping is not supported by the current target"));
13403 }
13404 }
13405
13406 void
13407 _initialize_remote (void)
13408 {
13409 struct cmd_list_element *cmd;
13410 const char *cmd_name;
13411
13412 /* architecture specific data */
13413 remote_gdbarch_data_handle =
13414 gdbarch_data_register_post_init (init_remote_state);
13415 remote_g_packet_data_handle =
13416 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13417
13418 remote_pspace_data
13419 = register_program_space_data_with_cleanup (NULL,
13420 remote_pspace_data_cleanup);
13421
13422 /* Initialize the per-target state. At the moment there is only one
13423 of these, not one per target. Only one target is active at a
13424 time. */
13425 remote_state = new_remote_state ();
13426
13427 init_remote_ops ();
13428 add_target (&remote_ops);
13429
13430 init_extended_remote_ops ();
13431 add_target (&extended_remote_ops);
13432
13433 /* Hook into new objfile notification. */
13434 observer_attach_new_objfile (remote_new_objfile);
13435 /* We're no longer interested in notification events of an inferior
13436 when it exits. */
13437 observer_attach_inferior_exit (discard_pending_stop_replies);
13438
13439 #if 0
13440 init_remote_threadtests ();
13441 #endif
13442
13443 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13444 /* set/show remote ... */
13445
13446 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13447 Remote protocol specific variables\n\
13448 Configure various remote-protocol specific variables such as\n\
13449 the packets being used"),
13450 &remote_set_cmdlist, "set remote ",
13451 0 /* allow-unknown */, &setlist);
13452 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13453 Remote protocol specific variables\n\
13454 Configure various remote-protocol specific variables such as\n\
13455 the packets being used"),
13456 &remote_show_cmdlist, "show remote ",
13457 0 /* allow-unknown */, &showlist);
13458
13459 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13460 Compare section data on target to the exec file.\n\
13461 Argument is a single section name (default: all loaded sections).\n\
13462 To compare only read-only loaded sections, specify the -r option."),
13463 &cmdlist);
13464
13465 add_cmd ("packet", class_maintenance, packet_command, _("\
13466 Send an arbitrary packet to a remote target.\n\
13467 maintenance packet TEXT\n\
13468 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13469 this command sends the string TEXT to the inferior, and displays the\n\
13470 response packet. GDB supplies the initial `$' character, and the\n\
13471 terminating `#' character and checksum."),
13472 &maintenancelist);
13473
13474 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13475 Set whether to send break if interrupted."), _("\
13476 Show whether to send break if interrupted."), _("\
13477 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13478 set_remotebreak, show_remotebreak,
13479 &setlist, &showlist);
13480 cmd_name = "remotebreak";
13481 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13482 deprecate_cmd (cmd, "set remote interrupt-sequence");
13483 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13484 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13485 deprecate_cmd (cmd, "show remote interrupt-sequence");
13486
13487 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13488 interrupt_sequence_modes, &interrupt_sequence_mode,
13489 _("\
13490 Set interrupt sequence to remote target."), _("\
13491 Show interrupt sequence to remote target."), _("\
13492 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13493 NULL, show_interrupt_sequence,
13494 &remote_set_cmdlist,
13495 &remote_show_cmdlist);
13496
13497 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13498 &interrupt_on_connect, _("\
13499 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13500 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13501 If set, interrupt sequence is sent to remote target."),
13502 NULL, NULL,
13503 &remote_set_cmdlist, &remote_show_cmdlist);
13504
13505 /* Install commands for configuring memory read/write packets. */
13506
13507 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13508 Set the maximum number of bytes per memory write packet (deprecated)."),
13509 &setlist);
13510 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13511 Show the maximum number of bytes per memory write packet (deprecated)."),
13512 &showlist);
13513 add_cmd ("memory-write-packet-size", no_class,
13514 set_memory_write_packet_size, _("\
13515 Set the maximum number of bytes per memory-write packet.\n\
13516 Specify the number of bytes in a packet or 0 (zero) for the\n\
13517 default packet size. The actual limit is further reduced\n\
13518 dependent on the target. Specify ``fixed'' to disable the\n\
13519 further restriction and ``limit'' to enable that restriction."),
13520 &remote_set_cmdlist);
13521 add_cmd ("memory-read-packet-size", no_class,
13522 set_memory_read_packet_size, _("\
13523 Set the maximum number of bytes per memory-read packet.\n\
13524 Specify the number of bytes in a packet or 0 (zero) for the\n\
13525 default packet size. The actual limit is further reduced\n\
13526 dependent on the target. Specify ``fixed'' to disable the\n\
13527 further restriction and ``limit'' to enable that restriction."),
13528 &remote_set_cmdlist);
13529 add_cmd ("memory-write-packet-size", no_class,
13530 show_memory_write_packet_size,
13531 _("Show the maximum number of bytes per memory-write packet."),
13532 &remote_show_cmdlist);
13533 add_cmd ("memory-read-packet-size", no_class,
13534 show_memory_read_packet_size,
13535 _("Show the maximum number of bytes per memory-read packet."),
13536 &remote_show_cmdlist);
13537
13538 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13539 &remote_hw_watchpoint_limit, _("\
13540 Set the maximum number of target hardware watchpoints."), _("\
13541 Show the maximum number of target hardware watchpoints."), _("\
13542 Specify a negative limit for unlimited."),
13543 NULL, NULL, /* FIXME: i18n: The maximum
13544 number of target hardware
13545 watchpoints is %s. */
13546 &remote_set_cmdlist, &remote_show_cmdlist);
13547 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13548 &remote_hw_watchpoint_length_limit, _("\
13549 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13550 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13551 Specify a negative limit for unlimited."),
13552 NULL, NULL, /* FIXME: i18n: The maximum
13553 length (in bytes) of a target
13554 hardware watchpoint is %s. */
13555 &remote_set_cmdlist, &remote_show_cmdlist);
13556 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13557 &remote_hw_breakpoint_limit, _("\
13558 Set the maximum number of target hardware breakpoints."), _("\
13559 Show the maximum number of target hardware breakpoints."), _("\
13560 Specify a negative limit for unlimited."),
13561 NULL, NULL, /* FIXME: i18n: The maximum
13562 number of target hardware
13563 breakpoints is %s. */
13564 &remote_set_cmdlist, &remote_show_cmdlist);
13565
13566 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13567 &remote_address_size, _("\
13568 Set the maximum size of the address (in bits) in a memory packet."), _("\
13569 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13570 NULL,
13571 NULL, /* FIXME: i18n: */
13572 &setlist, &showlist);
13573
13574 init_all_packet_configs ();
13575
13576 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13577 "X", "binary-download", 1);
13578
13579 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13580 "vCont", "verbose-resume", 0);
13581
13582 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13583 "QPassSignals", "pass-signals", 0);
13584
13585 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13586 "QCatchSyscalls", "catch-syscalls", 0);
13587
13588 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13589 "QProgramSignals", "program-signals", 0);
13590
13591 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13592 "qSymbol", "symbol-lookup", 0);
13593
13594 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13595 "P", "set-register", 1);
13596
13597 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13598 "p", "fetch-register", 1);
13599
13600 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13601 "Z0", "software-breakpoint", 0);
13602
13603 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13604 "Z1", "hardware-breakpoint", 0);
13605
13606 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13607 "Z2", "write-watchpoint", 0);
13608
13609 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13610 "Z3", "read-watchpoint", 0);
13611
13612 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13613 "Z4", "access-watchpoint", 0);
13614
13615 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13616 "qXfer:auxv:read", "read-aux-vector", 0);
13617
13618 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13619 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13620
13621 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13622 "qXfer:features:read", "target-features", 0);
13623
13624 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13625 "qXfer:libraries:read", "library-info", 0);
13626
13627 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13628 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13629
13630 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13631 "qXfer:memory-map:read", "memory-map", 0);
13632
13633 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13634 "qXfer:spu:read", "read-spu-object", 0);
13635
13636 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13637 "qXfer:spu:write", "write-spu-object", 0);
13638
13639 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13640 "qXfer:osdata:read", "osdata", 0);
13641
13642 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13643 "qXfer:threads:read", "threads", 0);
13644
13645 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13646 "qXfer:siginfo:read", "read-siginfo-object", 0);
13647
13648 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13649 "qXfer:siginfo:write", "write-siginfo-object", 0);
13650
13651 add_packet_config_cmd
13652 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13653 "qXfer:traceframe-info:read", "traceframe-info", 0);
13654
13655 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13656 "qXfer:uib:read", "unwind-info-block", 0);
13657
13658 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13659 "qGetTLSAddr", "get-thread-local-storage-address",
13660 0);
13661
13662 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13663 "qGetTIBAddr", "get-thread-information-block-address",
13664 0);
13665
13666 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13667 "bc", "reverse-continue", 0);
13668
13669 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13670 "bs", "reverse-step", 0);
13671
13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13673 "qSupported", "supported-packets", 0);
13674
13675 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13676 "qSearch:memory", "search-memory", 0);
13677
13678 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13679 "qTStatus", "trace-status", 0);
13680
13681 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13682 "vFile:setfs", "hostio-setfs", 0);
13683
13684 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13685 "vFile:open", "hostio-open", 0);
13686
13687 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13688 "vFile:pread", "hostio-pread", 0);
13689
13690 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13691 "vFile:pwrite", "hostio-pwrite", 0);
13692
13693 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13694 "vFile:close", "hostio-close", 0);
13695
13696 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13697 "vFile:unlink", "hostio-unlink", 0);
13698
13699 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13700 "vFile:readlink", "hostio-readlink", 0);
13701
13702 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13703 "vFile:fstat", "hostio-fstat", 0);
13704
13705 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13706 "vAttach", "attach", 0);
13707
13708 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13709 "vRun", "run", 0);
13710
13711 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13712 "QStartNoAckMode", "noack", 0);
13713
13714 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13715 "vKill", "kill", 0);
13716
13717 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13718 "qAttached", "query-attached", 0);
13719
13720 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13721 "ConditionalTracepoints",
13722 "conditional-tracepoints", 0);
13723
13724 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13725 "ConditionalBreakpoints",
13726 "conditional-breakpoints", 0);
13727
13728 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13729 "BreakpointCommands",
13730 "breakpoint-commands", 0);
13731
13732 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13733 "FastTracepoints", "fast-tracepoints", 0);
13734
13735 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13736 "TracepointSource", "TracepointSource", 0);
13737
13738 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13739 "QAllow", "allow", 0);
13740
13741 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13742 "StaticTracepoints", "static-tracepoints", 0);
13743
13744 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13745 "InstallInTrace", "install-in-trace", 0);
13746
13747 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13748 "qXfer:statictrace:read", "read-sdata-object", 0);
13749
13750 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13751 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13752
13753 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13754 "QDisableRandomization", "disable-randomization", 0);
13755
13756 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13757 "QAgent", "agent", 0);
13758
13759 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13760 "QTBuffer:size", "trace-buffer-size", 0);
13761
13762 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13763 "Qbtrace:off", "disable-btrace", 0);
13764
13765 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13766 "Qbtrace:bts", "enable-btrace-bts", 0);
13767
13768 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13769 "Qbtrace:pt", "enable-btrace-pt", 0);
13770
13771 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13772 "qXfer:btrace", "read-btrace", 0);
13773
13774 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13775 "qXfer:btrace-conf", "read-btrace-conf", 0);
13776
13777 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13778 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13779
13780 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13781 "multiprocess-feature", "multiprocess-feature", 0);
13782
13783 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13784 "swbreak-feature", "swbreak-feature", 0);
13785
13786 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13787 "hwbreak-feature", "hwbreak-feature", 0);
13788
13789 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13790 "fork-event-feature", "fork-event-feature", 0);
13791
13792 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13793 "vfork-event-feature", "vfork-event-feature", 0);
13794
13795 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13796 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13797
13798 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13799 "vContSupported", "verbose-resume-supported", 0);
13800
13801 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13802 "exec-event-feature", "exec-event-feature", 0);
13803
13804 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13805 "vCtrlC", "ctrl-c", 0);
13806
13807 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13808 "QThreadEvents", "thread-events", 0);
13809
13810 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13811 "N stop reply", "no-resumed-stop-reply", 0);
13812
13813 /* Assert that we've registered "set remote foo-packet" commands
13814 for all packet configs. */
13815 {
13816 int i;
13817
13818 for (i = 0; i < PACKET_MAX; i++)
13819 {
13820 /* Ideally all configs would have a command associated. Some
13821 still don't though. */
13822 int excepted;
13823
13824 switch (i)
13825 {
13826 case PACKET_QNonStop:
13827 case PACKET_EnableDisableTracepoints_feature:
13828 case PACKET_tracenz_feature:
13829 case PACKET_DisconnectedTracing_feature:
13830 case PACKET_augmented_libraries_svr4_read_feature:
13831 case PACKET_qCRC:
13832 /* Additions to this list need to be well justified:
13833 pre-existing packets are OK; new packets are not. */
13834 excepted = 1;
13835 break;
13836 default:
13837 excepted = 0;
13838 break;
13839 }
13840
13841 /* This catches both forgetting to add a config command, and
13842 forgetting to remove a packet from the exception list. */
13843 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13844 }
13845 }
13846
13847 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13848 Z sub-packet has its own set and show commands, but users may
13849 have sets to this variable in their .gdbinit files (or in their
13850 documentation). */
13851 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13852 &remote_Z_packet_detect, _("\
13853 Set use of remote protocol `Z' packets"), _("\
13854 Show use of remote protocol `Z' packets "), _("\
13855 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13856 packets."),
13857 set_remote_protocol_Z_packet_cmd,
13858 show_remote_protocol_Z_packet_cmd,
13859 /* FIXME: i18n: Use of remote protocol
13860 `Z' packets is %s. */
13861 &remote_set_cmdlist, &remote_show_cmdlist);
13862
13863 add_prefix_cmd ("remote", class_files, remote_command, _("\
13864 Manipulate files on the remote system\n\
13865 Transfer files to and from the remote target system."),
13866 &remote_cmdlist, "remote ",
13867 0 /* allow-unknown */, &cmdlist);
13868
13869 add_cmd ("put", class_files, remote_put_command,
13870 _("Copy a local file to the remote system."),
13871 &remote_cmdlist);
13872
13873 add_cmd ("get", class_files, remote_get_command,
13874 _("Copy a remote file to the local system."),
13875 &remote_cmdlist);
13876
13877 add_cmd ("delete", class_files, remote_delete_command,
13878 _("Delete a remote file."),
13879 &remote_cmdlist);
13880
13881 add_setshow_string_noescape_cmd ("exec-file", class_files,
13882 &remote_exec_file_var, _("\
13883 Set the remote pathname for \"run\""), _("\
13884 Show the remote pathname for \"run\""), NULL,
13885 set_remote_exec_file,
13886 show_remote_exec_file,
13887 &remote_set_cmdlist,
13888 &remote_show_cmdlist);
13889
13890 add_setshow_boolean_cmd ("range-stepping", class_run,
13891 &use_range_stepping, _("\
13892 Enable or disable range stepping."), _("\
13893 Show whether target-assisted range stepping is enabled."), _("\
13894 If on, and the target supports it, when stepping a source line, GDB\n\
13895 tells the target to step the corresponding range of addresses itself instead\n\
13896 of issuing multiple single-steps. This speeds up source level\n\
13897 stepping. If off, GDB always issues single-steps, even if range\n\
13898 stepping is supported by the target. The default is on."),
13899 set_range_stepping,
13900 show_range_stepping,
13901 &setlist,
13902 &showlist);
13903
13904 /* Eventually initialize fileio. See fileio.c */
13905 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13906
13907 /* Take advantage of the fact that the TID field is not used, to tag
13908 special ptids with it set to != 0. */
13909 magic_null_ptid = ptid_build (42000, -1, 1);
13910 not_sent_ptid = ptid_build (42000, -2, 1);
13911 any_thread_ptid = ptid_build (42000, 0, 1);
13912
13913 target_buf_size = 2048;
13914 target_buf = (char *) xmalloc (target_buf_size);
13915 }
13916
This page took 0.327897 seconds and 4 git commands to generate.