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