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