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