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