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