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