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