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