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