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