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