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