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