Move notif_queue and remote_async_get_pending_events_token to remote_state
[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 (struct inferior *);
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 /* Stop replies may from inferiors which are still unknown to GDB.
3071 We are closing the remote target, so we should discard
3072 everything, including the stop replies from GDB-unknown
3073 inferiors. */
3074 discard_pending_stop_replies (NULL);
3075
3076 if (remote_async_inferior_event_token)
3077 delete_async_event_handler (&remote_async_inferior_event_token);
3078
3079 remote_notif_state_xfree (rs->notif_state);
3080
3081 trace_reset_local_state ();
3082 }
3083
3084 /* Query the remote side for the text, data and bss offsets. */
3085
3086 static void
3087 get_offsets (void)
3088 {
3089 struct remote_state *rs = get_remote_state ();
3090 char *buf;
3091 char *ptr;
3092 int lose, num_segments = 0, do_sections, do_segments;
3093 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3094 struct section_offsets *offs;
3095 struct symfile_segment_data *data;
3096
3097 if (symfile_objfile == NULL)
3098 return;
3099
3100 putpkt ("qOffsets");
3101 getpkt (&rs->buf, &rs->buf_size, 0);
3102 buf = rs->buf;
3103
3104 if (buf[0] == '\000')
3105 return; /* Return silently. Stub doesn't support
3106 this command. */
3107 if (buf[0] == 'E')
3108 {
3109 warning (_("Remote failure reply: %s"), buf);
3110 return;
3111 }
3112
3113 /* Pick up each field in turn. This used to be done with scanf, but
3114 scanf will make trouble if CORE_ADDR size doesn't match
3115 conversion directives correctly. The following code will work
3116 with any size of CORE_ADDR. */
3117 text_addr = data_addr = bss_addr = 0;
3118 ptr = buf;
3119 lose = 0;
3120
3121 if (strncmp (ptr, "Text=", 5) == 0)
3122 {
3123 ptr += 5;
3124 /* Don't use strtol, could lose on big values. */
3125 while (*ptr && *ptr != ';')
3126 text_addr = (text_addr << 4) + fromhex (*ptr++);
3127
3128 if (strncmp (ptr, ";Data=", 6) == 0)
3129 {
3130 ptr += 6;
3131 while (*ptr && *ptr != ';')
3132 data_addr = (data_addr << 4) + fromhex (*ptr++);
3133 }
3134 else
3135 lose = 1;
3136
3137 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3138 {
3139 ptr += 5;
3140 while (*ptr && *ptr != ';')
3141 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3142
3143 if (bss_addr != data_addr)
3144 warning (_("Target reported unsupported offsets: %s"), buf);
3145 }
3146 else
3147 lose = 1;
3148 }
3149 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3150 {
3151 ptr += 8;
3152 /* Don't use strtol, could lose on big values. */
3153 while (*ptr && *ptr != ';')
3154 text_addr = (text_addr << 4) + fromhex (*ptr++);
3155 num_segments = 1;
3156
3157 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3158 {
3159 ptr += 9;
3160 while (*ptr && *ptr != ';')
3161 data_addr = (data_addr << 4) + fromhex (*ptr++);
3162 num_segments++;
3163 }
3164 }
3165 else
3166 lose = 1;
3167
3168 if (lose)
3169 error (_("Malformed response to offset query, %s"), buf);
3170 else if (*ptr != '\0')
3171 warning (_("Target reported unsupported offsets: %s"), buf);
3172
3173 offs = ((struct section_offsets *)
3174 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3175 memcpy (offs, symfile_objfile->section_offsets,
3176 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3177
3178 data = get_symfile_segment_data (symfile_objfile->obfd);
3179 do_segments = (data != NULL);
3180 do_sections = num_segments == 0;
3181
3182 if (num_segments > 0)
3183 {
3184 segments[0] = text_addr;
3185 segments[1] = data_addr;
3186 }
3187 /* If we have two segments, we can still try to relocate everything
3188 by assuming that the .text and .data offsets apply to the whole
3189 text and data segments. Convert the offsets given in the packet
3190 to base addresses for symfile_map_offsets_to_segments. */
3191 else if (data && data->num_segments == 2)
3192 {
3193 segments[0] = data->segment_bases[0] + text_addr;
3194 segments[1] = data->segment_bases[1] + data_addr;
3195 num_segments = 2;
3196 }
3197 /* If the object file has only one segment, assume that it is text
3198 rather than data; main programs with no writable data are rare,
3199 but programs with no code are useless. Of course the code might
3200 have ended up in the data segment... to detect that we would need
3201 the permissions here. */
3202 else if (data && data->num_segments == 1)
3203 {
3204 segments[0] = data->segment_bases[0] + text_addr;
3205 num_segments = 1;
3206 }
3207 /* There's no way to relocate by segment. */
3208 else
3209 do_segments = 0;
3210
3211 if (do_segments)
3212 {
3213 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3214 offs, num_segments, segments);
3215
3216 if (ret == 0 && !do_sections)
3217 error (_("Can not handle qOffsets TextSeg "
3218 "response with this symbol file"));
3219
3220 if (ret > 0)
3221 do_sections = 0;
3222 }
3223
3224 if (data)
3225 free_symfile_segment_data (data);
3226
3227 if (do_sections)
3228 {
3229 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3230
3231 /* This is a temporary kludge to force data and bss to use the
3232 same offsets because that's what nlmconv does now. The real
3233 solution requires changes to the stub and remote.c that I
3234 don't have time to do right now. */
3235
3236 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3237 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3238 }
3239
3240 objfile_relocate (symfile_objfile, offs);
3241 }
3242
3243 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3244 threads we know are stopped already. This is used during the
3245 initial remote connection in non-stop mode --- threads that are
3246 reported as already being stopped are left stopped. */
3247
3248 static int
3249 set_stop_requested_callback (struct thread_info *thread, void *data)
3250 {
3251 /* If we have a stop reply for this thread, it must be stopped. */
3252 if (peek_stop_reply (thread->ptid))
3253 set_stop_requested (thread->ptid, 1);
3254
3255 return 0;
3256 }
3257
3258 /* Send interrupt_sequence to remote target. */
3259 static void
3260 send_interrupt_sequence (void)
3261 {
3262 struct remote_state *rs = get_remote_state ();
3263
3264 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3265 remote_serial_write ("\x03", 1);
3266 else if (interrupt_sequence_mode == interrupt_sequence_break)
3267 serial_send_break (rs->remote_desc);
3268 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3269 {
3270 serial_send_break (rs->remote_desc);
3271 remote_serial_write ("g", 1);
3272 }
3273 else
3274 internal_error (__FILE__, __LINE__,
3275 _("Invalid value for interrupt_sequence_mode: %s."),
3276 interrupt_sequence_mode);
3277 }
3278
3279
3280 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3281 and extract the PTID. Returns NULL_PTID if not found. */
3282
3283 static ptid_t
3284 stop_reply_extract_thread (char *stop_reply)
3285 {
3286 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3287 {
3288 char *p;
3289
3290 /* Txx r:val ; r:val (...) */
3291 p = &stop_reply[3];
3292
3293 /* Look for "register" named "thread". */
3294 while (*p != '\0')
3295 {
3296 char *p1;
3297
3298 p1 = strchr (p, ':');
3299 if (p1 == NULL)
3300 return null_ptid;
3301
3302 if (strncmp (p, "thread", p1 - p) == 0)
3303 return read_ptid (++p1, &p);
3304
3305 p1 = strchr (p, ';');
3306 if (p1 == NULL)
3307 return null_ptid;
3308 p1++;
3309
3310 p = p1;
3311 }
3312 }
3313
3314 return null_ptid;
3315 }
3316
3317 /* Query the remote target for which is the current thread/process,
3318 add it to our tables, and update INFERIOR_PTID. The caller is
3319 responsible for setting the state such that the remote end is ready
3320 to return the current thread.
3321
3322 This function is called after handling the '?' or 'vRun' packets,
3323 whose response is a stop reply from which we can also try
3324 extracting the thread. If the target doesn't support the explicit
3325 qC query, we infer the current thread from that stop reply, passed
3326 in in WAIT_STATUS, which may be NULL. */
3327
3328 static void
3329 add_current_inferior_and_thread (char *wait_status)
3330 {
3331 struct remote_state *rs = get_remote_state ();
3332 int fake_pid_p = 0;
3333 ptid_t ptid = null_ptid;
3334
3335 inferior_ptid = null_ptid;
3336
3337 /* Now, if we have thread information, update inferior_ptid. First
3338 if we have a stop reply handy, maybe it's a T stop reply with a
3339 "thread" register we can extract the current thread from. If
3340 not, ask the remote which is the current thread, with qC. The
3341 former method avoids a roundtrip. Note we don't use
3342 remote_parse_stop_reply as that makes use of the target
3343 architecture, which we haven't yet fully determined at this
3344 point. */
3345 if (wait_status != NULL)
3346 ptid = stop_reply_extract_thread (wait_status);
3347 if (ptid_equal (ptid, null_ptid))
3348 ptid = remote_current_thread (inferior_ptid);
3349
3350 if (!ptid_equal (ptid, null_ptid))
3351 {
3352 if (!remote_multi_process_p (rs))
3353 fake_pid_p = 1;
3354
3355 inferior_ptid = ptid;
3356 }
3357 else
3358 {
3359 /* Without this, some commands which require an active target
3360 (such as kill) won't work. This variable serves (at least)
3361 double duty as both the pid of the target process (if it has
3362 such), and as a flag indicating that a target is active. */
3363 inferior_ptid = magic_null_ptid;
3364 fake_pid_p = 1;
3365 }
3366
3367 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3368
3369 /* Add the main thread. */
3370 add_thread_silent (inferior_ptid);
3371 }
3372
3373 static void
3374 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3375 {
3376 struct remote_state *rs = get_remote_state ();
3377 struct packet_config *noack_config;
3378 char *wait_status = NULL;
3379
3380 immediate_quit++; /* Allow user to interrupt it. */
3381 QUIT;
3382
3383 if (interrupt_on_connect)
3384 send_interrupt_sequence ();
3385
3386 /* Ack any packet which the remote side has already sent. */
3387 serial_write (rs->remote_desc, "+", 1);
3388
3389 /* Signal other parts that we're going through the initial setup,
3390 and so things may not be stable yet. */
3391 rs->starting_up = 1;
3392
3393 /* The first packet we send to the target is the optional "supported
3394 packets" request. If the target can answer this, it will tell us
3395 which later probes to skip. */
3396 remote_query_supported ();
3397
3398 /* If the stub wants to get a QAllow, compose one and send it. */
3399 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3400 remote_set_permissions ();
3401
3402 /* Next, we possibly activate noack mode.
3403
3404 If the QStartNoAckMode packet configuration is set to AUTO,
3405 enable noack mode if the stub reported a wish for it with
3406 qSupported.
3407
3408 If set to TRUE, then enable noack mode even if the stub didn't
3409 report it in qSupported. If the stub doesn't reply OK, the
3410 session ends with an error.
3411
3412 If FALSE, then don't activate noack mode, regardless of what the
3413 stub claimed should be the default with qSupported. */
3414
3415 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3416
3417 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3418 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3419 && noack_config->support == PACKET_ENABLE))
3420 {
3421 putpkt ("QStartNoAckMode");
3422 getpkt (&rs->buf, &rs->buf_size, 0);
3423 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3424 rs->noack_mode = 1;
3425 }
3426
3427 if (extended_p)
3428 {
3429 /* Tell the remote that we are using the extended protocol. */
3430 putpkt ("!");
3431 getpkt (&rs->buf, &rs->buf_size, 0);
3432 }
3433
3434 /* Let the target know which signals it is allowed to pass down to
3435 the program. */
3436 update_signals_program_target ();
3437
3438 /* Next, if the target can specify a description, read it. We do
3439 this before anything involving memory or registers. */
3440 target_find_description ();
3441
3442 /* Next, now that we know something about the target, update the
3443 address spaces in the program spaces. */
3444 update_address_spaces ();
3445
3446 /* On OSs where the list of libraries is global to all
3447 processes, we fetch them early. */
3448 if (gdbarch_has_global_solist (target_gdbarch ()))
3449 solib_add (NULL, from_tty, target, auto_solib_add);
3450
3451 if (non_stop)
3452 {
3453 if (!rs->non_stop_aware)
3454 error (_("Non-stop mode requested, but remote "
3455 "does not support non-stop"));
3456
3457 putpkt ("QNonStop:1");
3458 getpkt (&rs->buf, &rs->buf_size, 0);
3459
3460 if (strcmp (rs->buf, "OK") != 0)
3461 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3462
3463 /* Find about threads and processes the stub is already
3464 controlling. We default to adding them in the running state.
3465 The '?' query below will then tell us about which threads are
3466 stopped. */
3467 remote_threads_info (target);
3468 }
3469 else if (rs->non_stop_aware)
3470 {
3471 /* Don't assume that the stub can operate in all-stop mode.
3472 Request it explicitly. */
3473 putpkt ("QNonStop:0");
3474 getpkt (&rs->buf, &rs->buf_size, 0);
3475
3476 if (strcmp (rs->buf, "OK") != 0)
3477 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3478 }
3479
3480 /* Upload TSVs regardless of whether the target is running or not. The
3481 remote stub, such as GDBserver, may have some predefined or builtin
3482 TSVs, even if the target is not running. */
3483 if (remote_get_trace_status (current_trace_status ()) != -1)
3484 {
3485 struct uploaded_tsv *uploaded_tsvs = NULL;
3486
3487 remote_upload_trace_state_variables (&uploaded_tsvs);
3488 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3489 }
3490
3491 /* Check whether the target is running now. */
3492 putpkt ("?");
3493 getpkt (&rs->buf, &rs->buf_size, 0);
3494
3495 if (!non_stop)
3496 {
3497 ptid_t ptid;
3498 int fake_pid_p = 0;
3499 struct inferior *inf;
3500
3501 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3502 {
3503 if (!extended_p)
3504 error (_("The target is not running (try extended-remote?)"));
3505
3506 /* We're connected, but not running. Drop out before we
3507 call start_remote. */
3508 rs->starting_up = 0;
3509 return;
3510 }
3511 else
3512 {
3513 /* Save the reply for later. */
3514 wait_status = alloca (strlen (rs->buf) + 1);
3515 strcpy (wait_status, rs->buf);
3516 }
3517
3518 /* Let the stub know that we want it to return the thread. */
3519 set_continue_thread (minus_one_ptid);
3520
3521 add_current_inferior_and_thread (wait_status);
3522
3523 /* init_wait_for_inferior should be called before get_offsets in order
3524 to manage `inserted' flag in bp loc in a correct state.
3525 breakpoint_init_inferior, called from init_wait_for_inferior, set
3526 `inserted' flag to 0, while before breakpoint_re_set, called from
3527 start_remote, set `inserted' flag to 1. In the initialization of
3528 inferior, breakpoint_init_inferior should be called first, and then
3529 breakpoint_re_set can be called. If this order is broken, state of
3530 `inserted' flag is wrong, and cause some problems on breakpoint
3531 manipulation. */
3532 init_wait_for_inferior ();
3533
3534 get_offsets (); /* Get text, data & bss offsets. */
3535
3536 /* If we could not find a description using qXfer, and we know
3537 how to do it some other way, try again. This is not
3538 supported for non-stop; it could be, but it is tricky if
3539 there are no stopped threads when we connect. */
3540 if (remote_read_description_p (target)
3541 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3542 {
3543 target_clear_description ();
3544 target_find_description ();
3545 }
3546
3547 /* Use the previously fetched status. */
3548 gdb_assert (wait_status != NULL);
3549 strcpy (rs->buf, wait_status);
3550 rs->cached_wait_status = 1;
3551
3552 immediate_quit--;
3553 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3554 }
3555 else
3556 {
3557 /* Clear WFI global state. Do this before finding about new
3558 threads and inferiors, and setting the current inferior.
3559 Otherwise we would clear the proceed status of the current
3560 inferior when we want its stop_soon state to be preserved
3561 (see notice_new_inferior). */
3562 init_wait_for_inferior ();
3563
3564 /* In non-stop, we will either get an "OK", meaning that there
3565 are no stopped threads at this time; or, a regular stop
3566 reply. In the latter case, there may be more than one thread
3567 stopped --- we pull them all out using the vStopped
3568 mechanism. */
3569 if (strcmp (rs->buf, "OK") != 0)
3570 {
3571 struct notif_client *notif = &notif_client_stop;
3572
3573 /* remote_notif_get_pending_replies acks this one, and gets
3574 the rest out. */
3575 notif_client_stop.pending_event
3576 = remote_notif_parse (notif, rs->buf);
3577 remote_notif_get_pending_events (notif);
3578
3579 /* Make sure that threads that were stopped remain
3580 stopped. */
3581 iterate_over_threads (set_stop_requested_callback, NULL);
3582 }
3583
3584 if (target_can_async_p ())
3585 target_async (inferior_event_handler, 0);
3586
3587 if (thread_count () == 0)
3588 {
3589 if (!extended_p)
3590 error (_("The target is not running (try extended-remote?)"));
3591
3592 /* We're connected, but not running. Drop out before we
3593 call start_remote. */
3594 rs->starting_up = 0;
3595 return;
3596 }
3597
3598 /* Let the stub know that we want it to return the thread. */
3599
3600 /* Force the stub to choose a thread. */
3601 set_general_thread (null_ptid);
3602
3603 /* Query it. */
3604 inferior_ptid = remote_current_thread (minus_one_ptid);
3605 if (ptid_equal (inferior_ptid, minus_one_ptid))
3606 error (_("remote didn't report the current thread in non-stop mode"));
3607
3608 get_offsets (); /* Get text, data & bss offsets. */
3609
3610 /* In non-stop mode, any cached wait status will be stored in
3611 the stop reply queue. */
3612 gdb_assert (wait_status == NULL);
3613
3614 /* Report all signals during attach/startup. */
3615 remote_pass_signals (0, NULL);
3616 }
3617
3618 /* If we connected to a live target, do some additional setup. */
3619 if (target_has_execution)
3620 {
3621 if (exec_bfd) /* No use without an exec file. */
3622 remote_check_symbols ();
3623 }
3624
3625 /* Possibly the target has been engaged in a trace run started
3626 previously; find out where things are at. */
3627 if (remote_get_trace_status (current_trace_status ()) != -1)
3628 {
3629 struct uploaded_tp *uploaded_tps = NULL;
3630
3631 if (current_trace_status ()->running)
3632 printf_filtered (_("Trace is already running on the target.\n"));
3633
3634 remote_upload_tracepoints (&uploaded_tps);
3635
3636 merge_uploaded_tracepoints (&uploaded_tps);
3637 }
3638
3639 /* The thread and inferior lists are now synchronized with the
3640 target, our symbols have been relocated, and we're merged the
3641 target's tracepoints with ours. We're done with basic start
3642 up. */
3643 rs->starting_up = 0;
3644
3645 /* If breakpoints are global, insert them now. */
3646 if (gdbarch_has_global_breakpoints (target_gdbarch ())
3647 && breakpoints_always_inserted_mode ())
3648 insert_breakpoints ();
3649 }
3650
3651 /* Open a connection to a remote debugger.
3652 NAME is the filename used for communication. */
3653
3654 static void
3655 remote_open (char *name, int from_tty)
3656 {
3657 remote_open_1 (name, from_tty, &remote_ops, 0);
3658 }
3659
3660 /* Open a connection to a remote debugger using the extended
3661 remote gdb protocol. NAME is the filename used for communication. */
3662
3663 static void
3664 extended_remote_open (char *name, int from_tty)
3665 {
3666 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3667 }
3668
3669 /* Generic code for opening a connection to a remote target. */
3670
3671 static void
3672 init_all_packet_configs (void)
3673 {
3674 int i;
3675
3676 for (i = 0; i < PACKET_MAX; i++)
3677 update_packet_config (&remote_protocol_packets[i]);
3678 }
3679
3680 /* Symbol look-up. */
3681
3682 static void
3683 remote_check_symbols (void)
3684 {
3685 struct remote_state *rs = get_remote_state ();
3686 char *msg, *reply, *tmp;
3687 struct minimal_symbol *sym;
3688 int end;
3689
3690 /* The remote side has no concept of inferiors that aren't running
3691 yet, it only knows about running processes. If we're connected
3692 but our current inferior is not running, we should not invite the
3693 remote target to request symbol lookups related to its
3694 (unrelated) current process. */
3695 if (!target_has_execution)
3696 return;
3697
3698 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3699 return;
3700
3701 /* Make sure the remote is pointing at the right process. Note
3702 there's no way to select "no process". */
3703 set_general_process ();
3704
3705 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3706 because we need both at the same time. */
3707 msg = alloca (get_remote_packet_size ());
3708
3709 /* Invite target to request symbol lookups. */
3710
3711 putpkt ("qSymbol::");
3712 getpkt (&rs->buf, &rs->buf_size, 0);
3713 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3714 reply = rs->buf;
3715
3716 while (strncmp (reply, "qSymbol:", 8) == 0)
3717 {
3718 tmp = &reply[8];
3719 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3720 msg[end] = '\0';
3721 sym = lookup_minimal_symbol (msg, NULL, NULL);
3722 if (sym == NULL)
3723 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3724 else
3725 {
3726 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3727 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3728
3729 /* If this is a function address, return the start of code
3730 instead of any data function descriptor. */
3731 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3732 sym_addr,
3733 &current_target);
3734
3735 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3736 phex_nz (sym_addr, addr_size), &reply[8]);
3737 }
3738
3739 putpkt (msg);
3740 getpkt (&rs->buf, &rs->buf_size, 0);
3741 reply = rs->buf;
3742 }
3743 }
3744
3745 static struct serial *
3746 remote_serial_open (char *name)
3747 {
3748 static int udp_warning = 0;
3749
3750 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3751 of in ser-tcp.c, because it is the remote protocol assuming that the
3752 serial connection is reliable and not the serial connection promising
3753 to be. */
3754 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3755 {
3756 warning (_("The remote protocol may be unreliable over UDP.\n"
3757 "Some events may be lost, rendering further debugging "
3758 "impossible."));
3759 udp_warning = 1;
3760 }
3761
3762 return serial_open (name);
3763 }
3764
3765 /* Inform the target of our permission settings. The permission flags
3766 work without this, but if the target knows the settings, it can do
3767 a couple things. First, it can add its own check, to catch cases
3768 that somehow manage to get by the permissions checks in target
3769 methods. Second, if the target is wired to disallow particular
3770 settings (for instance, a system in the field that is not set up to
3771 be able to stop at a breakpoint), it can object to any unavailable
3772 permissions. */
3773
3774 void
3775 remote_set_permissions (void)
3776 {
3777 struct remote_state *rs = get_remote_state ();
3778
3779 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3780 "WriteReg:%x;WriteMem:%x;"
3781 "InsertBreak:%x;InsertTrace:%x;"
3782 "InsertFastTrace:%x;Stop:%x",
3783 may_write_registers, may_write_memory,
3784 may_insert_breakpoints, may_insert_tracepoints,
3785 may_insert_fast_tracepoints, may_stop);
3786 putpkt (rs->buf);
3787 getpkt (&rs->buf, &rs->buf_size, 0);
3788
3789 /* If the target didn't like the packet, warn the user. Do not try
3790 to undo the user's settings, that would just be maddening. */
3791 if (strcmp (rs->buf, "OK") != 0)
3792 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3793 }
3794
3795 /* This type describes each known response to the qSupported
3796 packet. */
3797 struct protocol_feature
3798 {
3799 /* The name of this protocol feature. */
3800 const char *name;
3801
3802 /* The default for this protocol feature. */
3803 enum packet_support default_support;
3804
3805 /* The function to call when this feature is reported, or after
3806 qSupported processing if the feature is not supported.
3807 The first argument points to this structure. The second
3808 argument indicates whether the packet requested support be
3809 enabled, disabled, or probed (or the default, if this function
3810 is being called at the end of processing and this feature was
3811 not reported). The third argument may be NULL; if not NULL, it
3812 is a NUL-terminated string taken from the packet following
3813 this feature's name and an equals sign. */
3814 void (*func) (const struct protocol_feature *, enum packet_support,
3815 const char *);
3816
3817 /* The corresponding packet for this feature. Only used if
3818 FUNC is remote_supported_packet. */
3819 int packet;
3820 };
3821
3822 static void
3823 remote_supported_packet (const struct protocol_feature *feature,
3824 enum packet_support support,
3825 const char *argument)
3826 {
3827 if (argument)
3828 {
3829 warning (_("Remote qSupported response supplied an unexpected value for"
3830 " \"%s\"."), feature->name);
3831 return;
3832 }
3833
3834 if (remote_protocol_packets[feature->packet].support
3835 == PACKET_SUPPORT_UNKNOWN)
3836 remote_protocol_packets[feature->packet].support = support;
3837 }
3838
3839 static void
3840 remote_packet_size (const struct protocol_feature *feature,
3841 enum packet_support support, const char *value)
3842 {
3843 struct remote_state *rs = get_remote_state ();
3844
3845 int packet_size;
3846 char *value_end;
3847
3848 if (support != PACKET_ENABLE)
3849 return;
3850
3851 if (value == NULL || *value == '\0')
3852 {
3853 warning (_("Remote target reported \"%s\" without a size."),
3854 feature->name);
3855 return;
3856 }
3857
3858 errno = 0;
3859 packet_size = strtol (value, &value_end, 16);
3860 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3861 {
3862 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3863 feature->name, value);
3864 return;
3865 }
3866
3867 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3868 {
3869 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3870 packet_size, MAX_REMOTE_PACKET_SIZE);
3871 packet_size = MAX_REMOTE_PACKET_SIZE;
3872 }
3873
3874 /* Record the new maximum packet size. */
3875 rs->explicit_packet_size = packet_size;
3876 }
3877
3878 static void
3879 remote_multi_process_feature (const struct protocol_feature *feature,
3880 enum packet_support support, const char *value)
3881 {
3882 struct remote_state *rs = get_remote_state ();
3883
3884 rs->multi_process_aware = (support == PACKET_ENABLE);
3885 }
3886
3887 static void
3888 remote_non_stop_feature (const struct protocol_feature *feature,
3889 enum packet_support support, const char *value)
3890 {
3891 struct remote_state *rs = get_remote_state ();
3892
3893 rs->non_stop_aware = (support == PACKET_ENABLE);
3894 }
3895
3896 static void
3897 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3898 enum packet_support support,
3899 const char *value)
3900 {
3901 struct remote_state *rs = get_remote_state ();
3902
3903 rs->cond_tracepoints = (support == PACKET_ENABLE);
3904 }
3905
3906 static void
3907 remote_cond_breakpoint_feature (const struct protocol_feature *feature,
3908 enum packet_support support,
3909 const char *value)
3910 {
3911 struct remote_state *rs = get_remote_state ();
3912
3913 rs->cond_breakpoints = (support == PACKET_ENABLE);
3914 }
3915
3916 static void
3917 remote_breakpoint_commands_feature (const struct protocol_feature *feature,
3918 enum packet_support support,
3919 const char *value)
3920 {
3921 struct remote_state *rs = get_remote_state ();
3922
3923 rs->breakpoint_commands = (support == PACKET_ENABLE);
3924 }
3925
3926 static void
3927 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3928 enum packet_support support,
3929 const char *value)
3930 {
3931 struct remote_state *rs = get_remote_state ();
3932
3933 rs->fast_tracepoints = (support == PACKET_ENABLE);
3934 }
3935
3936 static void
3937 remote_static_tracepoint_feature (const struct protocol_feature *feature,
3938 enum packet_support support,
3939 const char *value)
3940 {
3941 struct remote_state *rs = get_remote_state ();
3942
3943 rs->static_tracepoints = (support == PACKET_ENABLE);
3944 }
3945
3946 static void
3947 remote_install_in_trace_feature (const struct protocol_feature *feature,
3948 enum packet_support support,
3949 const char *value)
3950 {
3951 struct remote_state *rs = get_remote_state ();
3952
3953 rs->install_in_trace = (support == PACKET_ENABLE);
3954 }
3955
3956 static void
3957 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3958 enum packet_support support,
3959 const char *value)
3960 {
3961 struct remote_state *rs = get_remote_state ();
3962
3963 rs->disconnected_tracing = (support == PACKET_ENABLE);
3964 }
3965
3966 static void
3967 remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3968 enum packet_support support,
3969 const char *value)
3970 {
3971 struct remote_state *rs = get_remote_state ();
3972
3973 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3974 }
3975
3976 static void
3977 remote_string_tracing_feature (const struct protocol_feature *feature,
3978 enum packet_support support,
3979 const char *value)
3980 {
3981 struct remote_state *rs = get_remote_state ();
3982
3983 rs->string_tracing = (support == PACKET_ENABLE);
3984 }
3985
3986 static void
3987 remote_augmented_libraries_svr4_read_feature
3988 (const struct protocol_feature *feature,
3989 enum packet_support support, const char *value)
3990 {
3991 struct remote_state *rs = get_remote_state ();
3992
3993 rs->augmented_libraries_svr4_read = (support == PACKET_ENABLE);
3994 }
3995
3996 static const struct protocol_feature remote_protocol_features[] = {
3997 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3998 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3999 PACKET_qXfer_auxv },
4000 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4001 PACKET_qXfer_features },
4002 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4003 PACKET_qXfer_libraries },
4004 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4005 PACKET_qXfer_libraries_svr4 },
4006 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4007 remote_augmented_libraries_svr4_read_feature, -1 },
4008 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4009 PACKET_qXfer_memory_map },
4010 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4011 PACKET_qXfer_spu_read },
4012 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4013 PACKET_qXfer_spu_write },
4014 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4015 PACKET_qXfer_osdata },
4016 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4017 PACKET_qXfer_threads },
4018 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4019 PACKET_qXfer_traceframe_info },
4020 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4021 PACKET_QPassSignals },
4022 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4023 PACKET_QProgramSignals },
4024 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4025 PACKET_QStartNoAckMode },
4026 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
4027 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
4028 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4029 PACKET_qXfer_siginfo_read },
4030 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4031 PACKET_qXfer_siginfo_write },
4032 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
4033 PACKET_ConditionalTracepoints },
4034 { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
4035 PACKET_ConditionalBreakpoints },
4036 { "BreakpointCommands", PACKET_DISABLE, remote_breakpoint_commands_feature,
4037 PACKET_BreakpointCommands },
4038 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
4039 PACKET_FastTracepoints },
4040 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
4041 PACKET_StaticTracepoints },
4042 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
4043 PACKET_InstallInTrace},
4044 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
4045 -1 },
4046 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4047 PACKET_bc },
4048 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4049 PACKET_bs },
4050 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4051 PACKET_TracepointSource },
4052 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4053 PACKET_QAllow },
4054 { "EnableDisableTracepoints", PACKET_DISABLE,
4055 remote_enable_disable_tracepoint_feature, -1 },
4056 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4057 PACKET_qXfer_fdpic },
4058 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4059 PACKET_qXfer_uib },
4060 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4061 PACKET_QDisableRandomization },
4062 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4063 { "QTBuffer:size", PACKET_DISABLE,
4064 remote_supported_packet, PACKET_QTBuffer_size},
4065 { "tracenz", PACKET_DISABLE,
4066 remote_string_tracing_feature, -1 },
4067 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4068 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4069 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4070 PACKET_qXfer_btrace }
4071 };
4072
4073 static char *remote_support_xml;
4074
4075 /* Register string appended to "xmlRegisters=" in qSupported query. */
4076
4077 void
4078 register_remote_support_xml (const char *xml)
4079 {
4080 #if defined(HAVE_LIBEXPAT)
4081 if (remote_support_xml == NULL)
4082 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4083 else
4084 {
4085 char *copy = xstrdup (remote_support_xml + 13);
4086 char *p = strtok (copy, ",");
4087
4088 do
4089 {
4090 if (strcmp (p, xml) == 0)
4091 {
4092 /* already there */
4093 xfree (copy);
4094 return;
4095 }
4096 }
4097 while ((p = strtok (NULL, ",")) != NULL);
4098 xfree (copy);
4099
4100 remote_support_xml = reconcat (remote_support_xml,
4101 remote_support_xml, ",", xml,
4102 (char *) NULL);
4103 }
4104 #endif
4105 }
4106
4107 static char *
4108 remote_query_supported_append (char *msg, const char *append)
4109 {
4110 if (msg)
4111 return reconcat (msg, msg, ";", append, (char *) NULL);
4112 else
4113 return xstrdup (append);
4114 }
4115
4116 static void
4117 remote_query_supported (void)
4118 {
4119 struct remote_state *rs = get_remote_state ();
4120 char *next;
4121 int i;
4122 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4123
4124 /* The packet support flags are handled differently for this packet
4125 than for most others. We treat an error, a disabled packet, and
4126 an empty response identically: any features which must be reported
4127 to be used will be automatically disabled. An empty buffer
4128 accomplishes this, since that is also the representation for a list
4129 containing no features. */
4130
4131 rs->buf[0] = 0;
4132 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
4133 {
4134 char *q = NULL;
4135 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4136
4137 q = remote_query_supported_append (q, "multiprocess+");
4138
4139 if (remote_support_xml)
4140 q = remote_query_supported_append (q, remote_support_xml);
4141
4142 q = remote_query_supported_append (q, "qRelocInsn+");
4143
4144 q = reconcat (q, "qSupported:", q, (char *) NULL);
4145 putpkt (q);
4146
4147 do_cleanups (old_chain);
4148
4149 getpkt (&rs->buf, &rs->buf_size, 0);
4150
4151 /* If an error occured, warn, but do not return - just reset the
4152 buffer to empty and go on to disable features. */
4153 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4154 == PACKET_ERROR)
4155 {
4156 warning (_("Remote failure reply: %s"), rs->buf);
4157 rs->buf[0] = 0;
4158 }
4159 }
4160
4161 memset (seen, 0, sizeof (seen));
4162
4163 next = rs->buf;
4164 while (*next)
4165 {
4166 enum packet_support is_supported;
4167 char *p, *end, *name_end, *value;
4168
4169 /* First separate out this item from the rest of the packet. If
4170 there's another item after this, we overwrite the separator
4171 (terminated strings are much easier to work with). */
4172 p = next;
4173 end = strchr (p, ';');
4174 if (end == NULL)
4175 {
4176 end = p + strlen (p);
4177 next = end;
4178 }
4179 else
4180 {
4181 *end = '\0';
4182 next = end + 1;
4183
4184 if (end == p)
4185 {
4186 warning (_("empty item in \"qSupported\" response"));
4187 continue;
4188 }
4189 }
4190
4191 name_end = strchr (p, '=');
4192 if (name_end)
4193 {
4194 /* This is a name=value entry. */
4195 is_supported = PACKET_ENABLE;
4196 value = name_end + 1;
4197 *name_end = '\0';
4198 }
4199 else
4200 {
4201 value = NULL;
4202 switch (end[-1])
4203 {
4204 case '+':
4205 is_supported = PACKET_ENABLE;
4206 break;
4207
4208 case '-':
4209 is_supported = PACKET_DISABLE;
4210 break;
4211
4212 case '?':
4213 is_supported = PACKET_SUPPORT_UNKNOWN;
4214 break;
4215
4216 default:
4217 warning (_("unrecognized item \"%s\" "
4218 "in \"qSupported\" response"), p);
4219 continue;
4220 }
4221 end[-1] = '\0';
4222 }
4223
4224 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4225 if (strcmp (remote_protocol_features[i].name, p) == 0)
4226 {
4227 const struct protocol_feature *feature;
4228
4229 seen[i] = 1;
4230 feature = &remote_protocol_features[i];
4231 feature->func (feature, is_supported, value);
4232 break;
4233 }
4234 }
4235
4236 /* If we increased the packet size, make sure to increase the global
4237 buffer size also. We delay this until after parsing the entire
4238 qSupported packet, because this is the same buffer we were
4239 parsing. */
4240 if (rs->buf_size < rs->explicit_packet_size)
4241 {
4242 rs->buf_size = rs->explicit_packet_size;
4243 rs->buf = xrealloc (rs->buf, rs->buf_size);
4244 }
4245
4246 /* Handle the defaults for unmentioned features. */
4247 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4248 if (!seen[i])
4249 {
4250 const struct protocol_feature *feature;
4251
4252 feature = &remote_protocol_features[i];
4253 feature->func (feature, feature->default_support, NULL);
4254 }
4255 }
4256
4257 /* Remove any of the remote.c targets from target stack. Upper targets depend
4258 on it so remove them first. */
4259
4260 static void
4261 remote_unpush_target (void)
4262 {
4263 pop_all_targets_above (process_stratum - 1);
4264 }
4265
4266 static void
4267 remote_open_1 (char *name, int from_tty,
4268 struct target_ops *target, int extended_p)
4269 {
4270 struct remote_state *rs = get_remote_state ();
4271
4272 if (name == 0)
4273 error (_("To open a remote debug connection, you need to specify what\n"
4274 "serial device is attached to the remote system\n"
4275 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4276
4277 /* See FIXME above. */
4278 if (!target_async_permitted)
4279 wait_forever_enabled_p = 1;
4280
4281 /* If we're connected to a running target, target_preopen will kill it.
4282 Ask this question first, before target_preopen has a chance to kill
4283 anything. */
4284 if (rs->remote_desc != NULL && !have_inferiors ())
4285 {
4286 if (from_tty
4287 && !query (_("Already connected to a remote target. Disconnect? ")))
4288 error (_("Still connected."));
4289 }
4290
4291 /* Here the possibly existing remote target gets unpushed. */
4292 target_preopen (from_tty);
4293
4294 /* Make sure we send the passed signals list the next time we resume. */
4295 xfree (rs->last_pass_packet);
4296 rs->last_pass_packet = NULL;
4297
4298 /* Make sure we send the program signals list the next time we
4299 resume. */
4300 xfree (rs->last_program_signals_packet);
4301 rs->last_program_signals_packet = NULL;
4302
4303 remote_fileio_reset ();
4304 reopen_exec_file ();
4305 reread_symbols ();
4306
4307 rs->remote_desc = remote_serial_open (name);
4308 if (!rs->remote_desc)
4309 perror_with_name (name);
4310
4311 if (baud_rate != -1)
4312 {
4313 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4314 {
4315 /* The requested speed could not be set. Error out to
4316 top level after closing remote_desc. Take care to
4317 set remote_desc to NULL to avoid closing remote_desc
4318 more than once. */
4319 serial_close (rs->remote_desc);
4320 rs->remote_desc = NULL;
4321 perror_with_name (name);
4322 }
4323 }
4324
4325 serial_raw (rs->remote_desc);
4326
4327 /* If there is something sitting in the buffer we might take it as a
4328 response to a command, which would be bad. */
4329 serial_flush_input (rs->remote_desc);
4330
4331 if (from_tty)
4332 {
4333 puts_filtered ("Remote debugging using ");
4334 puts_filtered (name);
4335 puts_filtered ("\n");
4336 }
4337 push_target (target); /* Switch to using remote target now. */
4338
4339 /* Register extra event sources in the event loop. */
4340 remote_async_inferior_event_token
4341 = create_async_event_handler (remote_async_inferior_event_handler,
4342 NULL);
4343 rs->notif_state = remote_notif_state_allocate ();
4344
4345 /* Reset the target state; these things will be queried either by
4346 remote_query_supported or as they are needed. */
4347 init_all_packet_configs ();
4348 rs->cached_wait_status = 0;
4349 rs->explicit_packet_size = 0;
4350 rs->noack_mode = 0;
4351 rs->multi_process_aware = 0;
4352 rs->extended = extended_p;
4353 rs->non_stop_aware = 0;
4354 rs->waiting_for_stop_reply = 0;
4355 rs->ctrlc_pending_p = 0;
4356
4357 rs->general_thread = not_sent_ptid;
4358 rs->continue_thread = not_sent_ptid;
4359 rs->remote_traceframe_number = -1;
4360
4361 /* Probe for ability to use "ThreadInfo" query, as required. */
4362 rs->use_threadinfo_query = 1;
4363 rs->use_threadextra_query = 1;
4364
4365 if (target_async_permitted)
4366 {
4367 /* With this target we start out by owning the terminal. */
4368 remote_async_terminal_ours_p = 1;
4369
4370 /* FIXME: cagney/1999-09-23: During the initial connection it is
4371 assumed that the target is already ready and able to respond to
4372 requests. Unfortunately remote_start_remote() eventually calls
4373 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4374 around this. Eventually a mechanism that allows
4375 wait_for_inferior() to expect/get timeouts will be
4376 implemented. */
4377 wait_forever_enabled_p = 0;
4378 }
4379
4380 /* First delete any symbols previously loaded from shared libraries. */
4381 no_shared_libraries (NULL, 0);
4382
4383 /* Start afresh. */
4384 init_thread_list ();
4385
4386 /* Start the remote connection. If error() or QUIT, discard this
4387 target (we'd otherwise be in an inconsistent state) and then
4388 propogate the error on up the exception chain. This ensures that
4389 the caller doesn't stumble along blindly assuming that the
4390 function succeeded. The CLI doesn't have this problem but other
4391 UI's, such as MI do.
4392
4393 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4394 this function should return an error indication letting the
4395 caller restore the previous state. Unfortunately the command
4396 ``target remote'' is directly wired to this function making that
4397 impossible. On a positive note, the CLI side of this problem has
4398 been fixed - the function set_cmd_context() makes it possible for
4399 all the ``target ....'' commands to share a common callback
4400 function. See cli-dump.c. */
4401 {
4402 volatile struct gdb_exception ex;
4403
4404 TRY_CATCH (ex, RETURN_MASK_ALL)
4405 {
4406 remote_start_remote (from_tty, target, extended_p);
4407 }
4408 if (ex.reason < 0)
4409 {
4410 /* Pop the partially set up target - unless something else did
4411 already before throwing the exception. */
4412 if (rs->remote_desc != NULL)
4413 remote_unpush_target ();
4414 if (target_async_permitted)
4415 wait_forever_enabled_p = 1;
4416 throw_exception (ex);
4417 }
4418 }
4419
4420 if (target_async_permitted)
4421 wait_forever_enabled_p = 1;
4422 }
4423
4424 /* This takes a program previously attached to and detaches it. After
4425 this is done, GDB can be used to debug some other program. We
4426 better not have left any breakpoints in the target program or it'll
4427 die when it hits one. */
4428
4429 static void
4430 remote_detach_1 (char *args, int from_tty, int extended)
4431 {
4432 int pid = ptid_get_pid (inferior_ptid);
4433 struct remote_state *rs = get_remote_state ();
4434
4435 if (args)
4436 error (_("Argument given to \"detach\" when remotely debugging."));
4437
4438 if (!target_has_execution)
4439 error (_("No process to detach from."));
4440
4441 if (from_tty)
4442 {
4443 char *exec_file = get_exec_file (0);
4444 if (exec_file == NULL)
4445 exec_file = "";
4446 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4447 target_pid_to_str (pid_to_ptid (pid)));
4448 gdb_flush (gdb_stdout);
4449 }
4450
4451 /* Tell the remote target to detach. */
4452 if (remote_multi_process_p (rs))
4453 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4454 else
4455 strcpy (rs->buf, "D");
4456
4457 putpkt (rs->buf);
4458 getpkt (&rs->buf, &rs->buf_size, 0);
4459
4460 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4461 ;
4462 else if (rs->buf[0] == '\0')
4463 error (_("Remote doesn't know how to detach"));
4464 else
4465 error (_("Can't detach process."));
4466
4467 if (from_tty && !extended)
4468 puts_filtered (_("Ending remote debugging.\n"));
4469
4470 target_mourn_inferior ();
4471 }
4472
4473 static void
4474 remote_detach (struct target_ops *ops, char *args, int from_tty)
4475 {
4476 remote_detach_1 (args, from_tty, 0);
4477 }
4478
4479 static void
4480 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
4481 {
4482 remote_detach_1 (args, from_tty, 1);
4483 }
4484
4485 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4486
4487 static void
4488 remote_disconnect (struct target_ops *target, char *args, int from_tty)
4489 {
4490 if (args)
4491 error (_("Argument given to \"disconnect\" when remotely debugging."));
4492
4493 /* Make sure we unpush even the extended remote targets; mourn
4494 won't do it. So call remote_mourn_1 directly instead of
4495 target_mourn_inferior. */
4496 remote_mourn_1 (target);
4497
4498 if (from_tty)
4499 puts_filtered ("Ending remote debugging.\n");
4500 }
4501
4502 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4503 be chatty about it. */
4504
4505 static void
4506 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4507 {
4508 struct remote_state *rs = get_remote_state ();
4509 int pid;
4510 char *wait_status = NULL;
4511
4512 pid = parse_pid_to_attach (args);
4513
4514 /* Remote PID can be freely equal to getpid, do not check it here the same
4515 way as in other targets. */
4516
4517 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4518 error (_("This target does not support attaching to a process"));
4519
4520 if (from_tty)
4521 {
4522 char *exec_file = get_exec_file (0);
4523
4524 if (exec_file)
4525 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4526 target_pid_to_str (pid_to_ptid (pid)));
4527 else
4528 printf_unfiltered (_("Attaching to %s\n"),
4529 target_pid_to_str (pid_to_ptid (pid)));
4530
4531 gdb_flush (gdb_stdout);
4532 }
4533
4534 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4535 putpkt (rs->buf);
4536 getpkt (&rs->buf, &rs->buf_size, 0);
4537
4538 if (packet_ok (rs->buf,
4539 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
4540 {
4541 if (!non_stop)
4542 {
4543 /* Save the reply for later. */
4544 wait_status = alloca (strlen (rs->buf) + 1);
4545 strcpy (wait_status, rs->buf);
4546 }
4547 else if (strcmp (rs->buf, "OK") != 0)
4548 error (_("Attaching to %s failed with: %s"),
4549 target_pid_to_str (pid_to_ptid (pid)),
4550 rs->buf);
4551 }
4552 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4553 error (_("This target does not support attaching to a process"));
4554 else
4555 error (_("Attaching to %s failed"),
4556 target_pid_to_str (pid_to_ptid (pid)));
4557
4558 set_current_inferior (remote_add_inferior (0, pid, 1));
4559
4560 inferior_ptid = pid_to_ptid (pid);
4561
4562 if (non_stop)
4563 {
4564 struct thread_info *thread;
4565
4566 /* Get list of threads. */
4567 remote_threads_info (target);
4568
4569 thread = first_thread_of_process (pid);
4570 if (thread)
4571 inferior_ptid = thread->ptid;
4572 else
4573 inferior_ptid = pid_to_ptid (pid);
4574
4575 /* Invalidate our notion of the remote current thread. */
4576 record_currthread (rs, minus_one_ptid);
4577 }
4578 else
4579 {
4580 /* Now, if we have thread information, update inferior_ptid. */
4581 inferior_ptid = remote_current_thread (inferior_ptid);
4582
4583 /* Add the main thread to the thread list. */
4584 add_thread_silent (inferior_ptid);
4585 }
4586
4587 /* Next, if the target can specify a description, read it. We do
4588 this before anything involving memory or registers. */
4589 target_find_description ();
4590
4591 if (!non_stop)
4592 {
4593 /* Use the previously fetched status. */
4594 gdb_assert (wait_status != NULL);
4595
4596 if (target_can_async_p ())
4597 {
4598 struct notif_event *reply
4599 = remote_notif_parse (&notif_client_stop, wait_status);
4600
4601 push_stop_reply ((struct stop_reply *) reply);
4602
4603 target_async (inferior_event_handler, 0);
4604 }
4605 else
4606 {
4607 gdb_assert (wait_status != NULL);
4608 strcpy (rs->buf, wait_status);
4609 rs->cached_wait_status = 1;
4610 }
4611 }
4612 else
4613 gdb_assert (wait_status == NULL);
4614 }
4615
4616 static void
4617 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4618 {
4619 extended_remote_attach_1 (ops, args, from_tty);
4620 }
4621
4622 /* Convert hex digit A to a number. */
4623
4624 static int
4625 fromhex (int a)
4626 {
4627 if (a >= '0' && a <= '9')
4628 return a - '0';
4629 else if (a >= 'a' && a <= 'f')
4630 return a - 'a' + 10;
4631 else if (a >= 'A' && a <= 'F')
4632 return a - 'A' + 10;
4633 else
4634 error (_("Reply contains invalid hex digit %d"), a);
4635 }
4636
4637 int
4638 hex2bin (const char *hex, gdb_byte *bin, int count)
4639 {
4640 int i;
4641
4642 for (i = 0; i < count; i++)
4643 {
4644 if (hex[0] == 0 || hex[1] == 0)
4645 {
4646 /* Hex string is short, or of uneven length.
4647 Return the count that has been converted so far. */
4648 return i;
4649 }
4650 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4651 hex += 2;
4652 }
4653 return i;
4654 }
4655
4656 /* Convert number NIB to a hex digit. */
4657
4658 static int
4659 tohex (int nib)
4660 {
4661 if (nib < 10)
4662 return '0' + nib;
4663 else
4664 return 'a' + nib - 10;
4665 }
4666
4667 int
4668 bin2hex (const gdb_byte *bin, char *hex, int count)
4669 {
4670 int i;
4671
4672 /* May use a length, or a nul-terminated string as input. */
4673 if (count == 0)
4674 count = strlen ((char *) bin);
4675
4676 for (i = 0; i < count; i++)
4677 {
4678 *hex++ = tohex ((*bin >> 4) & 0xf);
4679 *hex++ = tohex (*bin++ & 0xf);
4680 }
4681 *hex = 0;
4682 return i;
4683 }
4684 \f
4685 /* Check for the availability of vCont. This function should also check
4686 the response. */
4687
4688 static void
4689 remote_vcont_probe (struct remote_state *rs)
4690 {
4691 char *buf;
4692
4693 strcpy (rs->buf, "vCont?");
4694 putpkt (rs->buf);
4695 getpkt (&rs->buf, &rs->buf_size, 0);
4696 buf = rs->buf;
4697
4698 /* Make sure that the features we assume are supported. */
4699 if (strncmp (buf, "vCont", 5) == 0)
4700 {
4701 char *p = &buf[5];
4702 int support_s, support_S, support_c, support_C;
4703
4704 support_s = 0;
4705 support_S = 0;
4706 support_c = 0;
4707 support_C = 0;
4708 rs->supports_vCont.t = 0;
4709 rs->supports_vCont.r = 0;
4710 while (p && *p == ';')
4711 {
4712 p++;
4713 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4714 support_s = 1;
4715 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4716 support_S = 1;
4717 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4718 support_c = 1;
4719 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4720 support_C = 1;
4721 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4722 rs->supports_vCont.t = 1;
4723 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4724 rs->supports_vCont.r = 1;
4725
4726 p = strchr (p, ';');
4727 }
4728
4729 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4730 BUF will make packet_ok disable the packet. */
4731 if (!support_s || !support_S || !support_c || !support_C)
4732 buf[0] = 0;
4733 }
4734
4735 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4736 }
4737
4738 /* Helper function for building "vCont" resumptions. Write a
4739 resumption to P. ENDP points to one-passed-the-end of the buffer
4740 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4741 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4742 resumed thread should be single-stepped and/or signalled. If PTID
4743 equals minus_one_ptid, then all threads are resumed; if PTID
4744 represents a process, then all threads of the process are resumed;
4745 the thread to be stepped and/or signalled is given in the global
4746 INFERIOR_PTID. */
4747
4748 static char *
4749 append_resumption (char *p, char *endp,
4750 ptid_t ptid, int step, enum gdb_signal siggnal)
4751 {
4752 struct remote_state *rs = get_remote_state ();
4753
4754 if (step && siggnal != GDB_SIGNAL_0)
4755 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4756 else if (step
4757 /* GDB is willing to range step. */
4758 && use_range_stepping
4759 /* Target supports range stepping. */
4760 && rs->supports_vCont.r
4761 /* We don't currently support range stepping multiple
4762 threads with a wildcard (though the protocol allows it,
4763 so stubs shouldn't make an active effort to forbid
4764 it). */
4765 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4766 {
4767 struct thread_info *tp;
4768
4769 if (ptid_equal (ptid, minus_one_ptid))
4770 {
4771 /* If we don't know about the target thread's tid, then
4772 we're resuming magic_null_ptid (see caller). */
4773 tp = find_thread_ptid (magic_null_ptid);
4774 }
4775 else
4776 tp = find_thread_ptid (ptid);
4777 gdb_assert (tp != NULL);
4778
4779 if (tp->control.may_range_step)
4780 {
4781 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4782
4783 p += xsnprintf (p, endp - p, ";r%s,%s",
4784 phex_nz (tp->control.step_range_start,
4785 addr_size),
4786 phex_nz (tp->control.step_range_end,
4787 addr_size));
4788 }
4789 else
4790 p += xsnprintf (p, endp - p, ";s");
4791 }
4792 else if (step)
4793 p += xsnprintf (p, endp - p, ";s");
4794 else if (siggnal != GDB_SIGNAL_0)
4795 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4796 else
4797 p += xsnprintf (p, endp - p, ";c");
4798
4799 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4800 {
4801 ptid_t nptid;
4802
4803 /* All (-1) threads of process. */
4804 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4805
4806 p += xsnprintf (p, endp - p, ":");
4807 p = write_ptid (p, endp, nptid);
4808 }
4809 else if (!ptid_equal (ptid, minus_one_ptid))
4810 {
4811 p += xsnprintf (p, endp - p, ":");
4812 p = write_ptid (p, endp, ptid);
4813 }
4814
4815 return p;
4816 }
4817
4818 /* Append a vCont continue-with-signal action for threads that have a
4819 non-zero stop signal. */
4820
4821 static char *
4822 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4823 {
4824 struct thread_info *thread;
4825
4826 ALL_THREADS (thread)
4827 if (ptid_match (thread->ptid, ptid)
4828 && !ptid_equal (inferior_ptid, thread->ptid)
4829 && thread->suspend.stop_signal != GDB_SIGNAL_0
4830 && signal_pass_state (thread->suspend.stop_signal))
4831 {
4832 p = append_resumption (p, endp, thread->ptid,
4833 0, thread->suspend.stop_signal);
4834 thread->suspend.stop_signal = GDB_SIGNAL_0;
4835 }
4836
4837 return p;
4838 }
4839
4840 /* Resume the remote inferior by using a "vCont" packet. The thread
4841 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4842 resumed thread should be single-stepped and/or signalled. If PTID
4843 equals minus_one_ptid, then all threads are resumed; the thread to
4844 be stepped and/or signalled is given in the global INFERIOR_PTID.
4845 This function returns non-zero iff it resumes the inferior.
4846
4847 This function issues a strict subset of all possible vCont commands at the
4848 moment. */
4849
4850 static int
4851 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4852 {
4853 struct remote_state *rs = get_remote_state ();
4854 char *p;
4855 char *endp;
4856
4857 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4858 remote_vcont_probe (rs);
4859
4860 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4861 return 0;
4862
4863 p = rs->buf;
4864 endp = rs->buf + get_remote_packet_size ();
4865
4866 /* If we could generate a wider range of packets, we'd have to worry
4867 about overflowing BUF. Should there be a generic
4868 "multi-part-packet" packet? */
4869
4870 p += xsnprintf (p, endp - p, "vCont");
4871
4872 if (ptid_equal (ptid, magic_null_ptid))
4873 {
4874 /* MAGIC_NULL_PTID means that we don't have any active threads,
4875 so we don't have any TID numbers the inferior will
4876 understand. Make sure to only send forms that do not specify
4877 a TID. */
4878 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4879 }
4880 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4881 {
4882 /* Resume all threads (of all processes, or of a single
4883 process), with preference for INFERIOR_PTID. This assumes
4884 inferior_ptid belongs to the set of all threads we are about
4885 to resume. */
4886 if (step || siggnal != GDB_SIGNAL_0)
4887 {
4888 /* Step inferior_ptid, with or without signal. */
4889 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4890 }
4891
4892 /* Also pass down any pending signaled resumption for other
4893 threads not the current. */
4894 p = append_pending_thread_resumptions (p, endp, ptid);
4895
4896 /* And continue others without a signal. */
4897 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4898 }
4899 else
4900 {
4901 /* Scheduler locking; resume only PTID. */
4902 append_resumption (p, endp, ptid, step, siggnal);
4903 }
4904
4905 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4906 putpkt (rs->buf);
4907
4908 if (non_stop)
4909 {
4910 /* In non-stop, the stub replies to vCont with "OK". The stop
4911 reply will be reported asynchronously by means of a `%Stop'
4912 notification. */
4913 getpkt (&rs->buf, &rs->buf_size, 0);
4914 if (strcmp (rs->buf, "OK") != 0)
4915 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4916 }
4917
4918 return 1;
4919 }
4920
4921 /* Tell the remote machine to resume. */
4922
4923 static void
4924 remote_resume (struct target_ops *ops,
4925 ptid_t ptid, int step, enum gdb_signal siggnal)
4926 {
4927 struct remote_state *rs = get_remote_state ();
4928 char *buf;
4929
4930 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4931 (explained in remote-notif.c:handle_notification) so
4932 remote_notif_process is not called. We need find a place where
4933 it is safe to start a 'vNotif' sequence. It is good to do it
4934 before resuming inferior, because inferior was stopped and no RSP
4935 traffic at that moment. */
4936 if (!non_stop)
4937 remote_notif_process (rs->notif_state, &notif_client_stop);
4938
4939 rs->last_sent_signal = siggnal;
4940 rs->last_sent_step = step;
4941
4942 /* The vCont packet doesn't need to specify threads via Hc. */
4943 /* No reverse support (yet) for vCont. */
4944 if (execution_direction != EXEC_REVERSE)
4945 if (remote_vcont_resume (ptid, step, siggnal))
4946 goto done;
4947
4948 /* All other supported resume packets do use Hc, so set the continue
4949 thread. */
4950 if (ptid_equal (ptid, minus_one_ptid))
4951 set_continue_thread (any_thread_ptid);
4952 else
4953 set_continue_thread (ptid);
4954
4955 buf = rs->buf;
4956 if (execution_direction == EXEC_REVERSE)
4957 {
4958 /* We don't pass signals to the target in reverse exec mode. */
4959 if (info_verbose && siggnal != GDB_SIGNAL_0)
4960 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4961 siggnal);
4962
4963 if (step
4964 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4965 error (_("Remote reverse-step not supported."));
4966 if (!step
4967 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4968 error (_("Remote reverse-continue not supported."));
4969
4970 strcpy (buf, step ? "bs" : "bc");
4971 }
4972 else if (siggnal != GDB_SIGNAL_0)
4973 {
4974 buf[0] = step ? 'S' : 'C';
4975 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4976 buf[2] = tohex (((int) siggnal) & 0xf);
4977 buf[3] = '\0';
4978 }
4979 else
4980 strcpy (buf, step ? "s" : "c");
4981
4982 putpkt (buf);
4983
4984 done:
4985 /* We are about to start executing the inferior, let's register it
4986 with the event loop. NOTE: this is the one place where all the
4987 execution commands end up. We could alternatively do this in each
4988 of the execution commands in infcmd.c. */
4989 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4990 into infcmd.c in order to allow inferior function calls to work
4991 NOT asynchronously. */
4992 if (target_can_async_p ())
4993 target_async (inferior_event_handler, 0);
4994
4995 /* We've just told the target to resume. The remote server will
4996 wait for the inferior to stop, and then send a stop reply. In
4997 the mean time, we can't start another command/query ourselves
4998 because the stub wouldn't be ready to process it. This applies
4999 only to the base all-stop protocol, however. In non-stop (which
5000 only supports vCont), the stub replies with an "OK", and is
5001 immediate able to process further serial input. */
5002 if (!non_stop)
5003 rs->waiting_for_stop_reply = 1;
5004 }
5005 \f
5006
5007 /* Set up the signal handler for SIGINT, while the target is
5008 executing, ovewriting the 'regular' SIGINT signal handler. */
5009 static void
5010 async_initialize_sigint_signal_handler (void)
5011 {
5012 signal (SIGINT, async_handle_remote_sigint);
5013 }
5014
5015 /* Signal handler for SIGINT, while the target is executing. */
5016 static void
5017 async_handle_remote_sigint (int sig)
5018 {
5019 signal (sig, async_handle_remote_sigint_twice);
5020 mark_async_signal_handler (async_sigint_remote_token);
5021 }
5022
5023 /* Signal handler for SIGINT, installed after SIGINT has already been
5024 sent once. It will take effect the second time that the user sends
5025 a ^C. */
5026 static void
5027 async_handle_remote_sigint_twice (int sig)
5028 {
5029 signal (sig, async_handle_remote_sigint);
5030 mark_async_signal_handler (async_sigint_remote_twice_token);
5031 }
5032
5033 /* Perform the real interruption of the target execution, in response
5034 to a ^C. */
5035 static void
5036 async_remote_interrupt (gdb_client_data arg)
5037 {
5038 if (remote_debug)
5039 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5040
5041 target_stop (inferior_ptid);
5042 }
5043
5044 /* Perform interrupt, if the first attempt did not succeed. Just give
5045 up on the target alltogether. */
5046 static void
5047 async_remote_interrupt_twice (gdb_client_data arg)
5048 {
5049 if (remote_debug)
5050 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5051
5052 interrupt_query ();
5053 }
5054
5055 /* Reinstall the usual SIGINT handlers, after the target has
5056 stopped. */
5057 static void
5058 async_cleanup_sigint_signal_handler (void *dummy)
5059 {
5060 signal (SIGINT, handle_sigint);
5061 }
5062
5063 /* Send ^C to target to halt it. Target will respond, and send us a
5064 packet. */
5065 static void (*ofunc) (int);
5066
5067 /* The command line interface's stop routine. This function is installed
5068 as a signal handler for SIGINT. The first time a user requests a
5069 stop, we call remote_stop to send a break or ^C. If there is no
5070 response from the target (it didn't stop when the user requested it),
5071 we ask the user if he'd like to detach from the target. */
5072 static void
5073 sync_remote_interrupt (int signo)
5074 {
5075 /* If this doesn't work, try more severe steps. */
5076 signal (signo, sync_remote_interrupt_twice);
5077
5078 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5079 }
5080
5081 /* The user typed ^C twice. */
5082
5083 static void
5084 sync_remote_interrupt_twice (int signo)
5085 {
5086 signal (signo, ofunc);
5087 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5088 signal (signo, sync_remote_interrupt);
5089 }
5090
5091 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5092 thread, all threads of a remote process, or all threads of all
5093 processes. */
5094
5095 static void
5096 remote_stop_ns (ptid_t ptid)
5097 {
5098 struct remote_state *rs = get_remote_state ();
5099 char *p = rs->buf;
5100 char *endp = rs->buf + get_remote_packet_size ();
5101
5102 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
5103 remote_vcont_probe (rs);
5104
5105 if (!rs->supports_vCont.t)
5106 error (_("Remote server does not support stopping threads"));
5107
5108 if (ptid_equal (ptid, minus_one_ptid)
5109 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5110 p += xsnprintf (p, endp - p, "vCont;t");
5111 else
5112 {
5113 ptid_t nptid;
5114
5115 p += xsnprintf (p, endp - p, "vCont;t:");
5116
5117 if (ptid_is_pid (ptid))
5118 /* All (-1) threads of process. */
5119 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
5120 else
5121 {
5122 /* Small optimization: if we already have a stop reply for
5123 this thread, no use in telling the stub we want this
5124 stopped. */
5125 if (peek_stop_reply (ptid))
5126 return;
5127
5128 nptid = ptid;
5129 }
5130
5131 write_ptid (p, endp, nptid);
5132 }
5133
5134 /* In non-stop, we get an immediate OK reply. The stop reply will
5135 come in asynchronously by notification. */
5136 putpkt (rs->buf);
5137 getpkt (&rs->buf, &rs->buf_size, 0);
5138 if (strcmp (rs->buf, "OK") != 0)
5139 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5140 }
5141
5142 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5143 remote target. It is undefined which thread of which process
5144 reports the stop. */
5145
5146 static void
5147 remote_stop_as (ptid_t ptid)
5148 {
5149 struct remote_state *rs = get_remote_state ();
5150
5151 rs->ctrlc_pending_p = 1;
5152
5153 /* If the inferior is stopped already, but the core didn't know
5154 about it yet, just ignore the request. The cached wait status
5155 will be collected in remote_wait. */
5156 if (rs->cached_wait_status)
5157 return;
5158
5159 /* Send interrupt_sequence to remote target. */
5160 send_interrupt_sequence ();
5161 }
5162
5163 /* This is the generic stop called via the target vector. When a target
5164 interrupt is requested, either by the command line or the GUI, we
5165 will eventually end up here. */
5166
5167 static void
5168 remote_stop (ptid_t ptid)
5169 {
5170 if (remote_debug)
5171 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5172
5173 if (non_stop)
5174 remote_stop_ns (ptid);
5175 else
5176 remote_stop_as (ptid);
5177 }
5178
5179 /* Ask the user what to do when an interrupt is received. */
5180
5181 static void
5182 interrupt_query (void)
5183 {
5184 target_terminal_ours ();
5185
5186 if (target_can_async_p ())
5187 {
5188 signal (SIGINT, handle_sigint);
5189 quit ();
5190 }
5191 else
5192 {
5193 if (query (_("Interrupted while waiting for the program.\n\
5194 Give up (and stop debugging it)? ")))
5195 {
5196 remote_unpush_target ();
5197 quit ();
5198 }
5199 }
5200
5201 target_terminal_inferior ();
5202 }
5203
5204 /* Enable/disable target terminal ownership. Most targets can use
5205 terminal groups to control terminal ownership. Remote targets are
5206 different in that explicit transfer of ownership to/from GDB/target
5207 is required. */
5208
5209 static void
5210 remote_terminal_inferior (void)
5211 {
5212 if (!target_async_permitted)
5213 /* Nothing to do. */
5214 return;
5215
5216 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5217 idempotent. The event-loop GDB talking to an asynchronous target
5218 with a synchronous command calls this function from both
5219 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5220 transfer the terminal to the target when it shouldn't this guard
5221 can go away. */
5222 if (!remote_async_terminal_ours_p)
5223 return;
5224 delete_file_handler (input_fd);
5225 remote_async_terminal_ours_p = 0;
5226 async_initialize_sigint_signal_handler ();
5227 /* NOTE: At this point we could also register our selves as the
5228 recipient of all input. Any characters typed could then be
5229 passed on down to the target. */
5230 }
5231
5232 static void
5233 remote_terminal_ours (void)
5234 {
5235 if (!target_async_permitted)
5236 /* Nothing to do. */
5237 return;
5238
5239 /* See FIXME in remote_terminal_inferior. */
5240 if (remote_async_terminal_ours_p)
5241 return;
5242 async_cleanup_sigint_signal_handler (NULL);
5243 add_file_handler (input_fd, stdin_event_handler, 0);
5244 remote_async_terminal_ours_p = 1;
5245 }
5246
5247 static void
5248 remote_console_output (char *msg)
5249 {
5250 char *p;
5251
5252 for (p = msg; p[0] && p[1]; p += 2)
5253 {
5254 char tb[2];
5255 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5256
5257 tb[0] = c;
5258 tb[1] = 0;
5259 fputs_unfiltered (tb, gdb_stdtarg);
5260 }
5261 gdb_flush (gdb_stdtarg);
5262 }
5263
5264 typedef struct cached_reg
5265 {
5266 int num;
5267 gdb_byte data[MAX_REGISTER_SIZE];
5268 } cached_reg_t;
5269
5270 DEF_VEC_O(cached_reg_t);
5271
5272 typedef struct stop_reply
5273 {
5274 struct notif_event base;
5275
5276 /* The identifier of the thread about this event */
5277 ptid_t ptid;
5278
5279 struct target_waitstatus ws;
5280
5281 /* Expedited registers. This makes remote debugging a bit more
5282 efficient for those targets that provide critical registers as
5283 part of their normal status mechanism (as another roundtrip to
5284 fetch them is avoided). */
5285 VEC(cached_reg_t) *regcache;
5286
5287 int stopped_by_watchpoint_p;
5288 CORE_ADDR watch_data_address;
5289
5290 int core;
5291 } *stop_reply_p;
5292
5293 DECLARE_QUEUE_P (stop_reply_p);
5294 DEFINE_QUEUE_P (stop_reply_p);
5295 /* The list of already fetched and acknowledged stop events. This
5296 queue is used for notification Stop, and other notifications
5297 don't need queue for their events, because the notification events
5298 of Stop can't be consumed immediately, so that events should be
5299 queued first, and be consumed by remote_wait_{ns,as} one per
5300 time. Other notifications can consume their events immediately,
5301 so queue is not needed for them. */
5302 static QUEUE (stop_reply_p) *stop_reply_queue;
5303
5304 static void
5305 stop_reply_xfree (struct stop_reply *r)
5306 {
5307 if (r != NULL)
5308 {
5309 VEC_free (cached_reg_t, r->regcache);
5310 xfree (r);
5311 }
5312 }
5313
5314 static void
5315 remote_notif_stop_parse (struct notif_client *self, char *buf,
5316 struct notif_event *event)
5317 {
5318 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5319 }
5320
5321 static void
5322 remote_notif_stop_ack (struct notif_client *self, char *buf,
5323 struct notif_event *event)
5324 {
5325 struct stop_reply *stop_reply = (struct stop_reply *) event;
5326
5327 /* acknowledge */
5328 putpkt ((char *) self->ack_command);
5329
5330 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5331 /* We got an unknown stop reply. */
5332 error (_("Unknown stop reply"));
5333
5334 push_stop_reply (stop_reply);
5335 }
5336
5337 static int
5338 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5339 {
5340 /* We can't get pending events in remote_notif_process for
5341 notification stop, and we have to do this in remote_wait_ns
5342 instead. If we fetch all queued events from stub, remote stub
5343 may exit and we have no chance to process them back in
5344 remote_wait_ns. */
5345 mark_async_event_handler (remote_async_inferior_event_token);
5346 return 0;
5347 }
5348
5349 static void
5350 stop_reply_dtr (struct notif_event *event)
5351 {
5352 struct stop_reply *r = (struct stop_reply *) event;
5353
5354 VEC_free (cached_reg_t, r->regcache);
5355 }
5356
5357 static struct notif_event *
5358 remote_notif_stop_alloc_reply (void)
5359 {
5360 struct notif_event *r
5361 = (struct notif_event *) XMALLOC (struct stop_reply);
5362
5363 r->dtr = stop_reply_dtr;
5364
5365 return r;
5366 }
5367
5368 /* A client of notification Stop. */
5369
5370 struct notif_client notif_client_stop =
5371 {
5372 "Stop",
5373 "vStopped",
5374 remote_notif_stop_parse,
5375 remote_notif_stop_ack,
5376 remote_notif_stop_can_get_pending_events,
5377 remote_notif_stop_alloc_reply,
5378 NULL,
5379 };
5380
5381 /* A parameter to pass data in and out. */
5382
5383 struct queue_iter_param
5384 {
5385 void *input;
5386 struct stop_reply *output;
5387 };
5388
5389 /* Remove all queue elements meet the condition it checks. */
5390
5391 static int
5392 remote_notif_remove_all (QUEUE (stop_reply_p) *q,
5393 QUEUE_ITER (stop_reply_p) *iter,
5394 stop_reply_p event,
5395 void *data)
5396 {
5397 struct queue_iter_param *param = data;
5398 struct inferior *inf = param->input;
5399
5400 if (inf == NULL || ptid_get_pid (event->ptid) == inf->pid)
5401 {
5402 stop_reply_xfree (event);
5403 QUEUE_remove_elem (stop_reply_p, q, iter);
5404 }
5405
5406 return 1;
5407 }
5408
5409 /* Discard all pending stop replies of inferior INF. If INF is NULL,
5410 discard everything. */
5411
5412 static void
5413 discard_pending_stop_replies (struct inferior *inf)
5414 {
5415 int i;
5416 struct queue_iter_param param;
5417 struct stop_reply *reply
5418 = (struct stop_reply *) notif_client_stop.pending_event;
5419
5420 /* Discard the in-flight notification. */
5421 if (reply != NULL
5422 && (inf == NULL
5423 || ptid_get_pid (reply->ptid) == inf->pid))
5424 {
5425 stop_reply_xfree (reply);
5426 notif_client_stop.pending_event = 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 remote_notif_remove_all, &param);
5435 }
5436
5437 /* A parameter to pass data in and out. */
5438
5439 static int
5440 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5441 QUEUE_ITER (stop_reply_p) *iter,
5442 stop_reply_p event,
5443 void *data)
5444 {
5445 struct queue_iter_param *param = data;
5446 ptid_t *ptid = param->input;
5447
5448 if (ptid_match (event->ptid, *ptid))
5449 {
5450 param->output = event;
5451 QUEUE_remove_elem (stop_reply_p, q, iter);
5452 return 0;
5453 }
5454
5455 return 1;
5456 }
5457
5458 /* Remove the first reply in 'stop_reply_queue' which matches
5459 PTID. */
5460
5461 static struct stop_reply *
5462 remote_notif_remove_queued_reply (ptid_t ptid)
5463 {
5464 struct queue_iter_param param;
5465
5466 param.input = &ptid;
5467 param.output = NULL;
5468
5469 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5470 remote_notif_remove_once_on_match, &param);
5471 if (notif_debug)
5472 fprintf_unfiltered (gdb_stdlog,
5473 "notif: discard queued event: 'Stop' in %s\n",
5474 target_pid_to_str (ptid));
5475
5476 return param.output;
5477 }
5478
5479 /* Look for a queued stop reply belonging to PTID. If one is found,
5480 remove it from the queue, and return it. Returns NULL if none is
5481 found. If there are still queued events left to process, tell the
5482 event loop to get back to target_wait soon. */
5483
5484 static struct stop_reply *
5485 queued_stop_reply (ptid_t ptid)
5486 {
5487 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5488
5489 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5490 /* There's still at least an event left. */
5491 mark_async_event_handler (remote_async_inferior_event_token);
5492
5493 return r;
5494 }
5495
5496 /* Push a fully parsed stop reply in the stop reply queue. Since we
5497 know that we now have at least one queued event left to pass to the
5498 core side, tell the event loop to get back to target_wait soon. */
5499
5500 static void
5501 push_stop_reply (struct stop_reply *new_event)
5502 {
5503 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5504
5505 if (notif_debug)
5506 fprintf_unfiltered (gdb_stdlog,
5507 "notif: push 'Stop' %s to queue %d\n",
5508 target_pid_to_str (new_event->ptid),
5509 QUEUE_length (stop_reply_p,
5510 stop_reply_queue));
5511
5512 mark_async_event_handler (remote_async_inferior_event_token);
5513 }
5514
5515 static int
5516 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5517 QUEUE_ITER (stop_reply_p) *iter,
5518 struct stop_reply *event,
5519 void *data)
5520 {
5521 ptid_t *ptid = data;
5522
5523 return !(ptid_equal (*ptid, event->ptid)
5524 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5525 }
5526
5527 /* Returns true if we have a stop reply for PTID. */
5528
5529 static int
5530 peek_stop_reply (ptid_t ptid)
5531 {
5532 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5533 stop_reply_match_ptid_and_ws, &ptid);
5534 }
5535
5536 /* Parse the stop reply in BUF. Either the function succeeds, and the
5537 result is stored in EVENT, or throws an error. */
5538
5539 static void
5540 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5541 {
5542 struct remote_arch_state *rsa = get_remote_arch_state ();
5543 ULONGEST addr;
5544 char *p;
5545
5546 event->ptid = null_ptid;
5547 event->ws.kind = TARGET_WAITKIND_IGNORE;
5548 event->ws.value.integer = 0;
5549 event->stopped_by_watchpoint_p = 0;
5550 event->regcache = NULL;
5551 event->core = -1;
5552
5553 switch (buf[0])
5554 {
5555 case 'T': /* Status with PC, SP, FP, ... */
5556 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5557 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5558 ss = signal number
5559 n... = register number
5560 r... = register contents
5561 */
5562
5563 p = &buf[3]; /* after Txx */
5564 while (*p)
5565 {
5566 char *p1;
5567 char *p_temp;
5568 int fieldsize;
5569 LONGEST pnum = 0;
5570
5571 /* If the packet contains a register number, save it in
5572 pnum and set p1 to point to the character following it.
5573 Otherwise p1 points to p. */
5574
5575 /* If this packet is an awatch packet, don't parse the 'a'
5576 as a register number. */
5577
5578 if (strncmp (p, "awatch", strlen("awatch")) != 0
5579 && strncmp (p, "core", strlen ("core") != 0))
5580 {
5581 /* Read the ``P'' register number. */
5582 pnum = strtol (p, &p_temp, 16);
5583 p1 = p_temp;
5584 }
5585 else
5586 p1 = p;
5587
5588 if (p1 == p) /* No register number present here. */
5589 {
5590 p1 = strchr (p, ':');
5591 if (p1 == NULL)
5592 error (_("Malformed packet(a) (missing colon): %s\n\
5593 Packet: '%s'\n"),
5594 p, buf);
5595 if (strncmp (p, "thread", p1 - p) == 0)
5596 event->ptid = read_ptid (++p1, &p);
5597 else if ((strncmp (p, "watch", p1 - p) == 0)
5598 || (strncmp (p, "rwatch", p1 - p) == 0)
5599 || (strncmp (p, "awatch", p1 - p) == 0))
5600 {
5601 event->stopped_by_watchpoint_p = 1;
5602 p = unpack_varlen_hex (++p1, &addr);
5603 event->watch_data_address = (CORE_ADDR) addr;
5604 }
5605 else if (strncmp (p, "library", p1 - p) == 0)
5606 {
5607 p1++;
5608 p_temp = p1;
5609 while (*p_temp && *p_temp != ';')
5610 p_temp++;
5611
5612 event->ws.kind = TARGET_WAITKIND_LOADED;
5613 p = p_temp;
5614 }
5615 else if (strncmp (p, "replaylog", p1 - p) == 0)
5616 {
5617 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5618 /* p1 will indicate "begin" or "end", but it makes
5619 no difference for now, so ignore it. */
5620 p_temp = strchr (p1 + 1, ';');
5621 if (p_temp)
5622 p = p_temp;
5623 }
5624 else if (strncmp (p, "core", p1 - p) == 0)
5625 {
5626 ULONGEST c;
5627
5628 p = unpack_varlen_hex (++p1, &c);
5629 event->core = c;
5630 }
5631 else
5632 {
5633 /* Silently skip unknown optional info. */
5634 p_temp = strchr (p1 + 1, ';');
5635 if (p_temp)
5636 p = p_temp;
5637 }
5638 }
5639 else
5640 {
5641 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5642 cached_reg_t cached_reg;
5643
5644 p = p1;
5645
5646 if (*p != ':')
5647 error (_("Malformed packet(b) (missing colon): %s\n\
5648 Packet: '%s'\n"),
5649 p, buf);
5650 ++p;
5651
5652 if (reg == NULL)
5653 error (_("Remote sent bad register number %s: %s\n\
5654 Packet: '%s'\n"),
5655 hex_string (pnum), p, buf);
5656
5657 cached_reg.num = reg->regnum;
5658
5659 fieldsize = hex2bin (p, cached_reg.data,
5660 register_size (target_gdbarch (),
5661 reg->regnum));
5662 p += 2 * fieldsize;
5663 if (fieldsize < register_size (target_gdbarch (),
5664 reg->regnum))
5665 warning (_("Remote reply is too short: %s"), buf);
5666
5667 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5668 }
5669
5670 if (*p != ';')
5671 error (_("Remote register badly formatted: %s\nhere: %s"),
5672 buf, p);
5673 ++p;
5674 }
5675
5676 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5677 break;
5678
5679 /* fall through */
5680 case 'S': /* Old style status, just signal only. */
5681 event->ws.kind = TARGET_WAITKIND_STOPPED;
5682 event->ws.value.sig = (enum gdb_signal)
5683 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5684 break;
5685 case 'W': /* Target exited. */
5686 case 'X':
5687 {
5688 char *p;
5689 int pid;
5690 ULONGEST value;
5691
5692 /* GDB used to accept only 2 hex chars here. Stubs should
5693 only send more if they detect GDB supports multi-process
5694 support. */
5695 p = unpack_varlen_hex (&buf[1], &value);
5696
5697 if (buf[0] == 'W')
5698 {
5699 /* The remote process exited. */
5700 event->ws.kind = TARGET_WAITKIND_EXITED;
5701 event->ws.value.integer = value;
5702 }
5703 else
5704 {
5705 /* The remote process exited with a signal. */
5706 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5707 event->ws.value.sig = (enum gdb_signal) value;
5708 }
5709
5710 /* If no process is specified, assume inferior_ptid. */
5711 pid = ptid_get_pid (inferior_ptid);
5712 if (*p == '\0')
5713 ;
5714 else if (*p == ';')
5715 {
5716 p++;
5717
5718 if (p == '\0')
5719 ;
5720 else if (strncmp (p,
5721 "process:", sizeof ("process:") - 1) == 0)
5722 {
5723 ULONGEST upid;
5724
5725 p += sizeof ("process:") - 1;
5726 unpack_varlen_hex (p, &upid);
5727 pid = upid;
5728 }
5729 else
5730 error (_("unknown stop reply packet: %s"), buf);
5731 }
5732 else
5733 error (_("unknown stop reply packet: %s"), buf);
5734 event->ptid = pid_to_ptid (pid);
5735 }
5736 break;
5737 }
5738
5739 if (non_stop && ptid_equal (event->ptid, null_ptid))
5740 error (_("No process or thread specified in stop reply: %s"), buf);
5741 }
5742
5743 /* When the stub wants to tell GDB about a new notification reply, it
5744 sends a notification (%Stop, for example). Those can come it at
5745 any time, hence, we have to make sure that any pending
5746 putpkt/getpkt sequence we're making is finished, before querying
5747 the stub for more events with the corresponding ack command
5748 (vStopped, for example). E.g., if we started a vStopped sequence
5749 immediately upon receiving the notification, something like this
5750 could happen:
5751
5752 1.1) --> Hg 1
5753 1.2) <-- OK
5754 1.3) --> g
5755 1.4) <-- %Stop
5756 1.5) --> vStopped
5757 1.6) <-- (registers reply to step #1.3)
5758
5759 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5760 query.
5761
5762 To solve this, whenever we parse a %Stop notification successfully,
5763 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5764 doing whatever we were doing:
5765
5766 2.1) --> Hg 1
5767 2.2) <-- OK
5768 2.3) --> g
5769 2.4) <-- %Stop
5770 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5771 2.5) <-- (registers reply to step #2.3)
5772
5773 Eventualy after step #2.5, we return to the event loop, which
5774 notices there's an event on the
5775 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5776 associated callback --- the function below. At this point, we're
5777 always safe to start a vStopped sequence. :
5778
5779 2.6) --> vStopped
5780 2.7) <-- T05 thread:2
5781 2.8) --> vStopped
5782 2.9) --> OK
5783 */
5784
5785 void
5786 remote_notif_get_pending_events (struct notif_client *nc)
5787 {
5788 struct remote_state *rs = get_remote_state ();
5789
5790 if (nc->pending_event)
5791 {
5792 if (notif_debug)
5793 fprintf_unfiltered (gdb_stdlog,
5794 "notif: process: '%s' ack pending event\n",
5795 nc->name);
5796
5797 /* acknowledge */
5798 nc->ack (nc, rs->buf, nc->pending_event);
5799 nc->pending_event = NULL;
5800
5801 while (1)
5802 {
5803 getpkt (&rs->buf, &rs->buf_size, 0);
5804 if (strcmp (rs->buf, "OK") == 0)
5805 break;
5806 else
5807 remote_notif_ack (nc, rs->buf);
5808 }
5809 }
5810 else
5811 {
5812 if (notif_debug)
5813 fprintf_unfiltered (gdb_stdlog,
5814 "notif: process: '%s' no pending reply\n",
5815 nc->name);
5816 }
5817 }
5818
5819 /* Called when it is decided that STOP_REPLY holds the info of the
5820 event that is to be returned to the core. This function always
5821 destroys STOP_REPLY. */
5822
5823 static ptid_t
5824 process_stop_reply (struct stop_reply *stop_reply,
5825 struct target_waitstatus *status)
5826 {
5827 ptid_t ptid;
5828
5829 *status = stop_reply->ws;
5830 ptid = stop_reply->ptid;
5831
5832 /* If no thread/process was reported by the stub, assume the current
5833 inferior. */
5834 if (ptid_equal (ptid, null_ptid))
5835 ptid = inferior_ptid;
5836
5837 if (status->kind != TARGET_WAITKIND_EXITED
5838 && status->kind != TARGET_WAITKIND_SIGNALLED)
5839 {
5840 struct remote_state *rs = get_remote_state ();
5841
5842 /* Expedited registers. */
5843 if (stop_reply->regcache)
5844 {
5845 struct regcache *regcache
5846 = get_thread_arch_regcache (ptid, target_gdbarch ());
5847 cached_reg_t *reg;
5848 int ix;
5849
5850 for (ix = 0;
5851 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5852 ix++)
5853 regcache_raw_supply (regcache, reg->num, reg->data);
5854 VEC_free (cached_reg_t, stop_reply->regcache);
5855 }
5856
5857 rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5858 rs->remote_watch_data_address = stop_reply->watch_data_address;
5859
5860 remote_notice_new_inferior (ptid, 0);
5861 demand_private_info (ptid)->core = stop_reply->core;
5862 }
5863
5864 stop_reply_xfree (stop_reply);
5865 return ptid;
5866 }
5867
5868 /* The non-stop mode version of target_wait. */
5869
5870 static ptid_t
5871 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5872 {
5873 struct remote_state *rs = get_remote_state ();
5874 struct stop_reply *stop_reply;
5875 int ret;
5876 int is_notif = 0;
5877
5878 /* If in non-stop mode, get out of getpkt even if a
5879 notification is received. */
5880
5881 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5882 0 /* forever */, &is_notif);
5883 while (1)
5884 {
5885 if (ret != -1 && !is_notif)
5886 switch (rs->buf[0])
5887 {
5888 case 'E': /* Error of some sort. */
5889 /* We're out of sync with the target now. Did it continue
5890 or not? We can't tell which thread it was in non-stop,
5891 so just ignore this. */
5892 warning (_("Remote failure reply: %s"), rs->buf);
5893 break;
5894 case 'O': /* Console output. */
5895 remote_console_output (rs->buf + 1);
5896 break;
5897 default:
5898 warning (_("Invalid remote reply: %s"), rs->buf);
5899 break;
5900 }
5901
5902 /* Acknowledge a pending stop reply that may have arrived in the
5903 mean time. */
5904 if (notif_client_stop.pending_event != NULL)
5905 remote_notif_get_pending_events (&notif_client_stop);
5906
5907 /* If indeed we noticed a stop reply, we're done. */
5908 stop_reply = queued_stop_reply (ptid);
5909 if (stop_reply != NULL)
5910 return process_stop_reply (stop_reply, status);
5911
5912 /* Still no event. If we're just polling for an event, then
5913 return to the event loop. */
5914 if (options & TARGET_WNOHANG)
5915 {
5916 status->kind = TARGET_WAITKIND_IGNORE;
5917 return minus_one_ptid;
5918 }
5919
5920 /* Otherwise do a blocking wait. */
5921 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5922 1 /* forever */, &is_notif);
5923 }
5924 }
5925
5926 /* Wait until the remote machine stops, then return, storing status in
5927 STATUS just as `wait' would. */
5928
5929 static ptid_t
5930 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5931 {
5932 struct remote_state *rs = get_remote_state ();
5933 ptid_t event_ptid = null_ptid;
5934 char *buf;
5935 struct stop_reply *stop_reply;
5936
5937 again:
5938
5939 status->kind = TARGET_WAITKIND_IGNORE;
5940 status->value.integer = 0;
5941
5942 stop_reply = queued_stop_reply (ptid);
5943 if (stop_reply != NULL)
5944 return process_stop_reply (stop_reply, status);
5945
5946 if (rs->cached_wait_status)
5947 /* Use the cached wait status, but only once. */
5948 rs->cached_wait_status = 0;
5949 else
5950 {
5951 int ret;
5952 int is_notif;
5953
5954 if (!target_is_async_p ())
5955 {
5956 ofunc = signal (SIGINT, sync_remote_interrupt);
5957 /* If the user hit C-c before this packet, or between packets,
5958 pretend that it was hit right here. */
5959 if (check_quit_flag ())
5960 {
5961 clear_quit_flag ();
5962 sync_remote_interrupt (SIGINT);
5963 }
5964 }
5965
5966 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5967 _never_ wait for ever -> test on target_is_async_p().
5968 However, before we do that we need to ensure that the caller
5969 knows how to take the target into/out of async mode. */
5970 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5971 wait_forever_enabled_p, &is_notif);
5972
5973 if (!target_is_async_p ())
5974 signal (SIGINT, ofunc);
5975
5976 /* GDB gets a notification. Return to core as this event is
5977 not interesting. */
5978 if (ret != -1 && is_notif)
5979 return minus_one_ptid;
5980 }
5981
5982 buf = rs->buf;
5983
5984 rs->remote_stopped_by_watchpoint_p = 0;
5985
5986 /* We got something. */
5987 rs->waiting_for_stop_reply = 0;
5988
5989 /* Assume that the target has acknowledged Ctrl-C unless we receive
5990 an 'F' or 'O' packet. */
5991 if (buf[0] != 'F' && buf[0] != 'O')
5992 rs->ctrlc_pending_p = 0;
5993
5994 switch (buf[0])
5995 {
5996 case 'E': /* Error of some sort. */
5997 /* We're out of sync with the target now. Did it continue or
5998 not? Not is more likely, so report a stop. */
5999 warning (_("Remote failure reply: %s"), buf);
6000 status->kind = TARGET_WAITKIND_STOPPED;
6001 status->value.sig = GDB_SIGNAL_0;
6002 break;
6003 case 'F': /* File-I/O request. */
6004 remote_fileio_request (buf, rs->ctrlc_pending_p);
6005 rs->ctrlc_pending_p = 0;
6006 break;
6007 case 'T': case 'S': case 'X': case 'W':
6008 {
6009 struct stop_reply *stop_reply
6010 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6011 rs->buf);
6012
6013 event_ptid = process_stop_reply (stop_reply, status);
6014 break;
6015 }
6016 case 'O': /* Console output. */
6017 remote_console_output (buf + 1);
6018
6019 /* The target didn't really stop; keep waiting. */
6020 rs->waiting_for_stop_reply = 1;
6021
6022 break;
6023 case '\0':
6024 if (rs->last_sent_signal != GDB_SIGNAL_0)
6025 {
6026 /* Zero length reply means that we tried 'S' or 'C' and the
6027 remote system doesn't support it. */
6028 target_terminal_ours_for_output ();
6029 printf_filtered
6030 ("Can't send signals to this remote system. %s not sent.\n",
6031 gdb_signal_to_name (rs->last_sent_signal));
6032 rs->last_sent_signal = GDB_SIGNAL_0;
6033 target_terminal_inferior ();
6034
6035 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6036 putpkt ((char *) buf);
6037
6038 /* We just told the target to resume, so a stop reply is in
6039 order. */
6040 rs->waiting_for_stop_reply = 1;
6041 break;
6042 }
6043 /* else fallthrough */
6044 default:
6045 warning (_("Invalid remote reply: %s"), buf);
6046 /* Keep waiting. */
6047 rs->waiting_for_stop_reply = 1;
6048 break;
6049 }
6050
6051 if (status->kind == TARGET_WAITKIND_IGNORE)
6052 {
6053 /* Nothing interesting happened. If we're doing a non-blocking
6054 poll, we're done. Otherwise, go back to waiting. */
6055 if (options & TARGET_WNOHANG)
6056 return minus_one_ptid;
6057 else
6058 goto again;
6059 }
6060 else if (status->kind != TARGET_WAITKIND_EXITED
6061 && status->kind != TARGET_WAITKIND_SIGNALLED)
6062 {
6063 if (!ptid_equal (event_ptid, null_ptid))
6064 record_currthread (rs, event_ptid);
6065 else
6066 event_ptid = inferior_ptid;
6067 }
6068 else
6069 /* A process exit. Invalidate our notion of current thread. */
6070 record_currthread (rs, minus_one_ptid);
6071
6072 return event_ptid;
6073 }
6074
6075 /* Wait until the remote machine stops, then return, storing status in
6076 STATUS just as `wait' would. */
6077
6078 static ptid_t
6079 remote_wait (struct target_ops *ops,
6080 ptid_t ptid, struct target_waitstatus *status, int options)
6081 {
6082 ptid_t event_ptid;
6083
6084 if (non_stop)
6085 event_ptid = remote_wait_ns (ptid, status, options);
6086 else
6087 event_ptid = remote_wait_as (ptid, status, options);
6088
6089 if (target_can_async_p ())
6090 {
6091 /* If there are are events left in the queue tell the event loop
6092 to return here. */
6093 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6094 mark_async_event_handler (remote_async_inferior_event_token);
6095 }
6096
6097 return event_ptid;
6098 }
6099
6100 /* Fetch a single register using a 'p' packet. */
6101
6102 static int
6103 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6104 {
6105 struct remote_state *rs = get_remote_state ();
6106 char *buf, *p;
6107 char regp[MAX_REGISTER_SIZE];
6108 int i;
6109
6110 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
6111 return 0;
6112
6113 if (reg->pnum == -1)
6114 return 0;
6115
6116 p = rs->buf;
6117 *p++ = 'p';
6118 p += hexnumstr (p, reg->pnum);
6119 *p++ = '\0';
6120 putpkt (rs->buf);
6121 getpkt (&rs->buf, &rs->buf_size, 0);
6122
6123 buf = rs->buf;
6124
6125 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6126 {
6127 case PACKET_OK:
6128 break;
6129 case PACKET_UNKNOWN:
6130 return 0;
6131 case PACKET_ERROR:
6132 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6133 gdbarch_register_name (get_regcache_arch (regcache),
6134 reg->regnum),
6135 buf);
6136 }
6137
6138 /* If this register is unfetchable, tell the regcache. */
6139 if (buf[0] == 'x')
6140 {
6141 regcache_raw_supply (regcache, reg->regnum, NULL);
6142 return 1;
6143 }
6144
6145 /* Otherwise, parse and supply the value. */
6146 p = buf;
6147 i = 0;
6148 while (p[0] != 0)
6149 {
6150 if (p[1] == 0)
6151 error (_("fetch_register_using_p: early buf termination"));
6152
6153 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6154 p += 2;
6155 }
6156 regcache_raw_supply (regcache, reg->regnum, regp);
6157 return 1;
6158 }
6159
6160 /* Fetch the registers included in the target's 'g' packet. */
6161
6162 static int
6163 send_g_packet (void)
6164 {
6165 struct remote_state *rs = get_remote_state ();
6166 int buf_len;
6167
6168 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6169 remote_send (&rs->buf, &rs->buf_size);
6170
6171 /* We can get out of synch in various cases. If the first character
6172 in the buffer is not a hex character, assume that has happened
6173 and try to fetch another packet to read. */
6174 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6175 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6176 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6177 && rs->buf[0] != 'x') /* New: unavailable register value. */
6178 {
6179 if (remote_debug)
6180 fprintf_unfiltered (gdb_stdlog,
6181 "Bad register packet; fetching a new packet\n");
6182 getpkt (&rs->buf, &rs->buf_size, 0);
6183 }
6184
6185 buf_len = strlen (rs->buf);
6186
6187 /* Sanity check the received packet. */
6188 if (buf_len % 2 != 0)
6189 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6190
6191 return buf_len / 2;
6192 }
6193
6194 static void
6195 process_g_packet (struct regcache *regcache)
6196 {
6197 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6198 struct remote_state *rs = get_remote_state ();
6199 struct remote_arch_state *rsa = get_remote_arch_state ();
6200 int i, buf_len;
6201 char *p;
6202 char *regs;
6203
6204 buf_len = strlen (rs->buf);
6205
6206 /* Further sanity checks, with knowledge of the architecture. */
6207 if (buf_len > 2 * rsa->sizeof_g_packet)
6208 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6209
6210 /* Save the size of the packet sent to us by the target. It is used
6211 as a heuristic when determining the max size of packets that the
6212 target can safely receive. */
6213 if (rsa->actual_register_packet_size == 0)
6214 rsa->actual_register_packet_size = buf_len;
6215
6216 /* If this is smaller than we guessed the 'g' packet would be,
6217 update our records. A 'g' reply that doesn't include a register's
6218 value implies either that the register is not available, or that
6219 the 'p' packet must be used. */
6220 if (buf_len < 2 * rsa->sizeof_g_packet)
6221 {
6222 rsa->sizeof_g_packet = buf_len / 2;
6223
6224 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6225 {
6226 if (rsa->regs[i].pnum == -1)
6227 continue;
6228
6229 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6230 rsa->regs[i].in_g_packet = 0;
6231 else
6232 rsa->regs[i].in_g_packet = 1;
6233 }
6234 }
6235
6236 regs = alloca (rsa->sizeof_g_packet);
6237
6238 /* Unimplemented registers read as all bits zero. */
6239 memset (regs, 0, rsa->sizeof_g_packet);
6240
6241 /* Reply describes registers byte by byte, each byte encoded as two
6242 hex characters. Suck them all up, then supply them to the
6243 register cacheing/storage mechanism. */
6244
6245 p = rs->buf;
6246 for (i = 0; i < rsa->sizeof_g_packet; i++)
6247 {
6248 if (p[0] == 0 || p[1] == 0)
6249 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6250 internal_error (__FILE__, __LINE__,
6251 _("unexpected end of 'g' packet reply"));
6252
6253 if (p[0] == 'x' && p[1] == 'x')
6254 regs[i] = 0; /* 'x' */
6255 else
6256 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6257 p += 2;
6258 }
6259
6260 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6261 {
6262 struct packet_reg *r = &rsa->regs[i];
6263
6264 if (r->in_g_packet)
6265 {
6266 if (r->offset * 2 >= strlen (rs->buf))
6267 /* This shouldn't happen - we adjusted in_g_packet above. */
6268 internal_error (__FILE__, __LINE__,
6269 _("unexpected end of 'g' packet reply"));
6270 else if (rs->buf[r->offset * 2] == 'x')
6271 {
6272 gdb_assert (r->offset * 2 < strlen (rs->buf));
6273 /* The register isn't available, mark it as such (at
6274 the same time setting the value to zero). */
6275 regcache_raw_supply (regcache, r->regnum, NULL);
6276 }
6277 else
6278 regcache_raw_supply (regcache, r->regnum,
6279 regs + r->offset);
6280 }
6281 }
6282 }
6283
6284 static void
6285 fetch_registers_using_g (struct regcache *regcache)
6286 {
6287 send_g_packet ();
6288 process_g_packet (regcache);
6289 }
6290
6291 /* Make the remote selected traceframe match GDB's selected
6292 traceframe. */
6293
6294 static void
6295 set_remote_traceframe (void)
6296 {
6297 int newnum;
6298 struct remote_state *rs = get_remote_state ();
6299
6300 if (rs->remote_traceframe_number == get_traceframe_number ())
6301 return;
6302
6303 /* Avoid recursion, remote_trace_find calls us again. */
6304 rs->remote_traceframe_number = get_traceframe_number ();
6305
6306 newnum = target_trace_find (tfind_number,
6307 get_traceframe_number (), 0, 0, NULL);
6308
6309 /* Should not happen. If it does, all bets are off. */
6310 if (newnum != get_traceframe_number ())
6311 warning (_("could not set remote traceframe"));
6312 }
6313
6314 static void
6315 remote_fetch_registers (struct target_ops *ops,
6316 struct regcache *regcache, int regnum)
6317 {
6318 struct remote_arch_state *rsa = get_remote_arch_state ();
6319 int i;
6320
6321 set_remote_traceframe ();
6322 set_general_thread (inferior_ptid);
6323
6324 if (regnum >= 0)
6325 {
6326 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6327
6328 gdb_assert (reg != NULL);
6329
6330 /* If this register might be in the 'g' packet, try that first -
6331 we are likely to read more than one register. If this is the
6332 first 'g' packet, we might be overly optimistic about its
6333 contents, so fall back to 'p'. */
6334 if (reg->in_g_packet)
6335 {
6336 fetch_registers_using_g (regcache);
6337 if (reg->in_g_packet)
6338 return;
6339 }
6340
6341 if (fetch_register_using_p (regcache, reg))
6342 return;
6343
6344 /* This register is not available. */
6345 regcache_raw_supply (regcache, reg->regnum, NULL);
6346
6347 return;
6348 }
6349
6350 fetch_registers_using_g (regcache);
6351
6352 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6353 if (!rsa->regs[i].in_g_packet)
6354 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6355 {
6356 /* This register is not available. */
6357 regcache_raw_supply (regcache, i, NULL);
6358 }
6359 }
6360
6361 /* Prepare to store registers. Since we may send them all (using a
6362 'G' request), we have to read out the ones we don't want to change
6363 first. */
6364
6365 static void
6366 remote_prepare_to_store (struct regcache *regcache)
6367 {
6368 struct remote_arch_state *rsa = get_remote_arch_state ();
6369 int i;
6370 gdb_byte buf[MAX_REGISTER_SIZE];
6371
6372 /* Make sure the entire registers array is valid. */
6373 switch (remote_protocol_packets[PACKET_P].support)
6374 {
6375 case PACKET_DISABLE:
6376 case PACKET_SUPPORT_UNKNOWN:
6377 /* Make sure all the necessary registers are cached. */
6378 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6379 if (rsa->regs[i].in_g_packet)
6380 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6381 break;
6382 case PACKET_ENABLE:
6383 break;
6384 }
6385 }
6386
6387 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6388 packet was not recognized. */
6389
6390 static int
6391 store_register_using_P (const struct regcache *regcache,
6392 struct packet_reg *reg)
6393 {
6394 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6395 struct remote_state *rs = get_remote_state ();
6396 /* Try storing a single register. */
6397 char *buf = rs->buf;
6398 gdb_byte regp[MAX_REGISTER_SIZE];
6399 char *p;
6400
6401 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
6402 return 0;
6403
6404 if (reg->pnum == -1)
6405 return 0;
6406
6407 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6408 p = buf + strlen (buf);
6409 regcache_raw_collect (regcache, reg->regnum, regp);
6410 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6411 putpkt (rs->buf);
6412 getpkt (&rs->buf, &rs->buf_size, 0);
6413
6414 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6415 {
6416 case PACKET_OK:
6417 return 1;
6418 case PACKET_ERROR:
6419 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6420 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6421 case PACKET_UNKNOWN:
6422 return 0;
6423 default:
6424 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6425 }
6426 }
6427
6428 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6429 contents of the register cache buffer. FIXME: ignores errors. */
6430
6431 static void
6432 store_registers_using_G (const struct regcache *regcache)
6433 {
6434 struct remote_state *rs = get_remote_state ();
6435 struct remote_arch_state *rsa = get_remote_arch_state ();
6436 gdb_byte *regs;
6437 char *p;
6438
6439 /* Extract all the registers in the regcache copying them into a
6440 local buffer. */
6441 {
6442 int i;
6443
6444 regs = alloca (rsa->sizeof_g_packet);
6445 memset (regs, 0, rsa->sizeof_g_packet);
6446 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6447 {
6448 struct packet_reg *r = &rsa->regs[i];
6449
6450 if (r->in_g_packet)
6451 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6452 }
6453 }
6454
6455 /* Command describes registers byte by byte,
6456 each byte encoded as two hex characters. */
6457 p = rs->buf;
6458 *p++ = 'G';
6459 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6460 updated. */
6461 bin2hex (regs, p, rsa->sizeof_g_packet);
6462 putpkt (rs->buf);
6463 getpkt (&rs->buf, &rs->buf_size, 0);
6464 if (packet_check_result (rs->buf) == PACKET_ERROR)
6465 error (_("Could not write registers; remote failure reply '%s'"),
6466 rs->buf);
6467 }
6468
6469 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6470 of the register cache buffer. FIXME: ignores errors. */
6471
6472 static void
6473 remote_store_registers (struct target_ops *ops,
6474 struct regcache *regcache, int regnum)
6475 {
6476 struct remote_arch_state *rsa = get_remote_arch_state ();
6477 int i;
6478
6479 set_remote_traceframe ();
6480 set_general_thread (inferior_ptid);
6481
6482 if (regnum >= 0)
6483 {
6484 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6485
6486 gdb_assert (reg != NULL);
6487
6488 /* Always prefer to store registers using the 'P' packet if
6489 possible; we often change only a small number of registers.
6490 Sometimes we change a larger number; we'd need help from a
6491 higher layer to know to use 'G'. */
6492 if (store_register_using_P (regcache, reg))
6493 return;
6494
6495 /* For now, don't complain if we have no way to write the
6496 register. GDB loses track of unavailable registers too
6497 easily. Some day, this may be an error. We don't have
6498 any way to read the register, either... */
6499 if (!reg->in_g_packet)
6500 return;
6501
6502 store_registers_using_G (regcache);
6503 return;
6504 }
6505
6506 store_registers_using_G (regcache);
6507
6508 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6509 if (!rsa->regs[i].in_g_packet)
6510 if (!store_register_using_P (regcache, &rsa->regs[i]))
6511 /* See above for why we do not issue an error here. */
6512 continue;
6513 }
6514 \f
6515
6516 /* Return the number of hex digits in num. */
6517
6518 static int
6519 hexnumlen (ULONGEST num)
6520 {
6521 int i;
6522
6523 for (i = 0; num != 0; i++)
6524 num >>= 4;
6525
6526 return max (i, 1);
6527 }
6528
6529 /* Set BUF to the minimum number of hex digits representing NUM. */
6530
6531 static int
6532 hexnumstr (char *buf, ULONGEST num)
6533 {
6534 int len = hexnumlen (num);
6535
6536 return hexnumnstr (buf, num, len);
6537 }
6538
6539
6540 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6541
6542 static int
6543 hexnumnstr (char *buf, ULONGEST num, int width)
6544 {
6545 int i;
6546
6547 buf[width] = '\0';
6548
6549 for (i = width - 1; i >= 0; i--)
6550 {
6551 buf[i] = "0123456789abcdef"[(num & 0xf)];
6552 num >>= 4;
6553 }
6554
6555 return width;
6556 }
6557
6558 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6559
6560 static CORE_ADDR
6561 remote_address_masked (CORE_ADDR addr)
6562 {
6563 unsigned int address_size = remote_address_size;
6564
6565 /* If "remoteaddresssize" was not set, default to target address size. */
6566 if (!address_size)
6567 address_size = gdbarch_addr_bit (target_gdbarch ());
6568
6569 if (address_size > 0
6570 && address_size < (sizeof (ULONGEST) * 8))
6571 {
6572 /* Only create a mask when that mask can safely be constructed
6573 in a ULONGEST variable. */
6574 ULONGEST mask = 1;
6575
6576 mask = (mask << address_size) - 1;
6577 addr &= mask;
6578 }
6579 return addr;
6580 }
6581
6582 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
6583 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6584 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6585 (which may be more than *OUT_LEN due to escape characters). The
6586 total number of bytes in the output buffer will be at most
6587 OUT_MAXLEN. */
6588
6589 static int
6590 remote_escape_output (const gdb_byte *buffer, int len,
6591 gdb_byte *out_buf, int *out_len,
6592 int out_maxlen)
6593 {
6594 int input_index, output_index;
6595
6596 output_index = 0;
6597 for (input_index = 0; input_index < len; input_index++)
6598 {
6599 gdb_byte b = buffer[input_index];
6600
6601 if (b == '$' || b == '#' || b == '}')
6602 {
6603 /* These must be escaped. */
6604 if (output_index + 2 > out_maxlen)
6605 break;
6606 out_buf[output_index++] = '}';
6607 out_buf[output_index++] = b ^ 0x20;
6608 }
6609 else
6610 {
6611 if (output_index + 1 > out_maxlen)
6612 break;
6613 out_buf[output_index++] = b;
6614 }
6615 }
6616
6617 *out_len = input_index;
6618 return output_index;
6619 }
6620
6621 /* Convert BUFFER, escaped data LEN bytes long, into binary data
6622 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6623 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6624
6625 This function reverses remote_escape_output. It allows more
6626 escaped characters than that function does, in particular because
6627 '*' must be escaped to avoid the run-length encoding processing
6628 in reading packets. */
6629
6630 static int
6631 remote_unescape_input (const gdb_byte *buffer, int len,
6632 gdb_byte *out_buf, int out_maxlen)
6633 {
6634 int input_index, output_index;
6635 int escaped;
6636
6637 output_index = 0;
6638 escaped = 0;
6639 for (input_index = 0; input_index < len; input_index++)
6640 {
6641 gdb_byte b = buffer[input_index];
6642
6643 if (output_index + 1 > out_maxlen)
6644 {
6645 warning (_("Received too much data from remote target;"
6646 " ignoring overflow."));
6647 return output_index;
6648 }
6649
6650 if (escaped)
6651 {
6652 out_buf[output_index++] = b ^ 0x20;
6653 escaped = 0;
6654 }
6655 else if (b == '}')
6656 escaped = 1;
6657 else
6658 out_buf[output_index++] = b;
6659 }
6660
6661 if (escaped)
6662 error (_("Unmatched escape character in target response."));
6663
6664 return output_index;
6665 }
6666
6667 /* Determine whether the remote target supports binary downloading.
6668 This is accomplished by sending a no-op memory write of zero length
6669 to the target at the specified address. It does not suffice to send
6670 the whole packet, since many stubs strip the eighth bit and
6671 subsequently compute a wrong checksum, which causes real havoc with
6672 remote_write_bytes.
6673
6674 NOTE: This can still lose if the serial line is not eight-bit
6675 clean. In cases like this, the user should clear "remote
6676 X-packet". */
6677
6678 static void
6679 check_binary_download (CORE_ADDR addr)
6680 {
6681 struct remote_state *rs = get_remote_state ();
6682
6683 switch (remote_protocol_packets[PACKET_X].support)
6684 {
6685 case PACKET_DISABLE:
6686 break;
6687 case PACKET_ENABLE:
6688 break;
6689 case PACKET_SUPPORT_UNKNOWN:
6690 {
6691 char *p;
6692
6693 p = rs->buf;
6694 *p++ = 'X';
6695 p += hexnumstr (p, (ULONGEST) addr);
6696 *p++ = ',';
6697 p += hexnumstr (p, (ULONGEST) 0);
6698 *p++ = ':';
6699 *p = '\0';
6700
6701 putpkt_binary (rs->buf, (int) (p - rs->buf));
6702 getpkt (&rs->buf, &rs->buf_size, 0);
6703
6704 if (rs->buf[0] == '\0')
6705 {
6706 if (remote_debug)
6707 fprintf_unfiltered (gdb_stdlog,
6708 "binary downloading NOT "
6709 "supported by target\n");
6710 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6711 }
6712 else
6713 {
6714 if (remote_debug)
6715 fprintf_unfiltered (gdb_stdlog,
6716 "binary downloading supported by target\n");
6717 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6718 }
6719 break;
6720 }
6721 }
6722 }
6723
6724 /* Write memory data directly to the remote machine.
6725 This does not inform the data cache; the data cache uses this.
6726 HEADER is the starting part of the packet.
6727 MEMADDR is the address in the remote memory space.
6728 MYADDR is the address of the buffer in our space.
6729 LEN is the number of bytes.
6730 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6731 should send data as binary ('X'), or hex-encoded ('M').
6732
6733 The function creates packet of the form
6734 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6735
6736 where encoding of <DATA> is termined by PACKET_FORMAT.
6737
6738 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6739 are omitted.
6740
6741 Returns the number of bytes transferred, or a negative value (an
6742 'enum target_xfer_error' value) for error. Only transfer a single
6743 packet. */
6744
6745 static LONGEST
6746 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6747 const gdb_byte *myaddr, ssize_t len,
6748 char packet_format, int use_length)
6749 {
6750 struct remote_state *rs = get_remote_state ();
6751 char *p;
6752 char *plen = NULL;
6753 int plenlen = 0;
6754 int todo;
6755 int nr_bytes;
6756 int payload_size;
6757 int payload_length;
6758 int header_length;
6759
6760 if (packet_format != 'X' && packet_format != 'M')
6761 internal_error (__FILE__, __LINE__,
6762 _("remote_write_bytes_aux: bad packet format"));
6763
6764 if (len <= 0)
6765 return 0;
6766
6767 payload_size = get_memory_write_packet_size ();
6768
6769 /* The packet buffer will be large enough for the payload;
6770 get_memory_packet_size ensures this. */
6771 rs->buf[0] = '\0';
6772
6773 /* Compute the size of the actual payload by subtracting out the
6774 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6775
6776 payload_size -= strlen ("$,:#NN");
6777 if (!use_length)
6778 /* The comma won't be used. */
6779 payload_size += 1;
6780 header_length = strlen (header);
6781 payload_size -= header_length;
6782 payload_size -= hexnumlen (memaddr);
6783
6784 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6785
6786 strcat (rs->buf, header);
6787 p = rs->buf + strlen (header);
6788
6789 /* Compute a best guess of the number of bytes actually transfered. */
6790 if (packet_format == 'X')
6791 {
6792 /* Best guess at number of bytes that will fit. */
6793 todo = min (len, payload_size);
6794 if (use_length)
6795 payload_size -= hexnumlen (todo);
6796 todo = min (todo, payload_size);
6797 }
6798 else
6799 {
6800 /* Num bytes that will fit. */
6801 todo = min (len, payload_size / 2);
6802 if (use_length)
6803 payload_size -= hexnumlen (todo);
6804 todo = min (todo, payload_size / 2);
6805 }
6806
6807 if (todo <= 0)
6808 internal_error (__FILE__, __LINE__,
6809 _("minimum packet size too small to write data"));
6810
6811 /* If we already need another packet, then try to align the end
6812 of this packet to a useful boundary. */
6813 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6814 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6815
6816 /* Append "<memaddr>". */
6817 memaddr = remote_address_masked (memaddr);
6818 p += hexnumstr (p, (ULONGEST) memaddr);
6819
6820 if (use_length)
6821 {
6822 /* Append ",". */
6823 *p++ = ',';
6824
6825 /* Append <len>. Retain the location/size of <len>. It may need to
6826 be adjusted once the packet body has been created. */
6827 plen = p;
6828 plenlen = hexnumstr (p, (ULONGEST) todo);
6829 p += plenlen;
6830 }
6831
6832 /* Append ":". */
6833 *p++ = ':';
6834 *p = '\0';
6835
6836 /* Append the packet body. */
6837 if (packet_format == 'X')
6838 {
6839 /* Binary mode. Send target system values byte by byte, in
6840 increasing byte addresses. Only escape certain critical
6841 characters. */
6842 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6843 &nr_bytes, payload_size);
6844
6845 /* If not all TODO bytes fit, then we'll need another packet. Make
6846 a second try to keep the end of the packet aligned. Don't do
6847 this if the packet is tiny. */
6848 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6849 {
6850 int new_nr_bytes;
6851
6852 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6853 - memaddr);
6854 if (new_nr_bytes != nr_bytes)
6855 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6856 (gdb_byte *) p, &nr_bytes,
6857 payload_size);
6858 }
6859
6860 p += payload_length;
6861 if (use_length && nr_bytes < todo)
6862 {
6863 /* Escape chars have filled up the buffer prematurely,
6864 and we have actually sent fewer bytes than planned.
6865 Fix-up the length field of the packet. Use the same
6866 number of characters as before. */
6867 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6868 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6869 }
6870 }
6871 else
6872 {
6873 /* Normal mode: Send target system values byte by byte, in
6874 increasing byte addresses. Each byte is encoded as a two hex
6875 value. */
6876 nr_bytes = bin2hex (myaddr, p, todo);
6877 p += 2 * nr_bytes;
6878 }
6879
6880 putpkt_binary (rs->buf, (int) (p - rs->buf));
6881 getpkt (&rs->buf, &rs->buf_size, 0);
6882
6883 if (rs->buf[0] == 'E')
6884 return TARGET_XFER_E_IO;
6885
6886 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6887 fewer bytes than we'd planned. */
6888 return nr_bytes;
6889 }
6890
6891 /* Write memory data directly to the remote machine.
6892 This does not inform the data cache; the data cache uses this.
6893 MEMADDR is the address in the remote memory space.
6894 MYADDR is the address of the buffer in our space.
6895 LEN is the number of bytes.
6896
6897 Returns number of bytes transferred, or a negative value (an 'enum
6898 target_xfer_error' value) for error. Only transfer a single
6899 packet. */
6900
6901 static LONGEST
6902 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
6903 {
6904 char *packet_format = 0;
6905
6906 /* Check whether the target supports binary download. */
6907 check_binary_download (memaddr);
6908
6909 switch (remote_protocol_packets[PACKET_X].support)
6910 {
6911 case PACKET_ENABLE:
6912 packet_format = "X";
6913 break;
6914 case PACKET_DISABLE:
6915 packet_format = "M";
6916 break;
6917 case PACKET_SUPPORT_UNKNOWN:
6918 internal_error (__FILE__, __LINE__,
6919 _("remote_write_bytes: bad internal state"));
6920 default:
6921 internal_error (__FILE__, __LINE__, _("bad switch"));
6922 }
6923
6924 return remote_write_bytes_aux (packet_format,
6925 memaddr, myaddr, len, packet_format[0], 1);
6926 }
6927
6928 /* Read memory data directly from the remote machine.
6929 This does not use the data cache; the data cache uses this.
6930 MEMADDR is the address in the remote memory space.
6931 MYADDR is the address of the buffer in our space.
6932 LEN is the number of bytes.
6933
6934 Returns number of bytes transferred, or a negative value (an 'enum
6935 target_xfer_error' value) for error. */
6936
6937 static LONGEST
6938 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6939 {
6940 struct remote_state *rs = get_remote_state ();
6941 int max_buf_size; /* Max size of packet output buffer. */
6942 char *p;
6943 int todo;
6944 int i;
6945
6946 if (len <= 0)
6947 return 0;
6948
6949 max_buf_size = get_memory_read_packet_size ();
6950 /* The packet buffer will be large enough for the payload;
6951 get_memory_packet_size ensures this. */
6952
6953 /* Number if bytes that will fit. */
6954 todo = min (len, max_buf_size / 2);
6955
6956 /* Construct "m"<memaddr>","<len>". */
6957 memaddr = remote_address_masked (memaddr);
6958 p = rs->buf;
6959 *p++ = 'm';
6960 p += hexnumstr (p, (ULONGEST) memaddr);
6961 *p++ = ',';
6962 p += hexnumstr (p, (ULONGEST) todo);
6963 *p = '\0';
6964 putpkt (rs->buf);
6965 getpkt (&rs->buf, &rs->buf_size, 0);
6966 if (rs->buf[0] == 'E'
6967 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6968 && rs->buf[3] == '\0')
6969 return TARGET_XFER_E_IO;
6970 /* Reply describes memory byte by byte, each byte encoded as two hex
6971 characters. */
6972 p = rs->buf;
6973 i = hex2bin (p, myaddr, todo);
6974 /* Return what we have. Let higher layers handle partial reads. */
6975 return i;
6976 }
6977
6978 \f
6979
6980 /* Sends a packet with content determined by the printf format string
6981 FORMAT and the remaining arguments, then gets the reply. Returns
6982 whether the packet was a success, a failure, or unknown. */
6983
6984 static enum packet_result
6985 remote_send_printf (const char *format, ...)
6986 {
6987 struct remote_state *rs = get_remote_state ();
6988 int max_size = get_remote_packet_size ();
6989 va_list ap;
6990
6991 va_start (ap, format);
6992
6993 rs->buf[0] = '\0';
6994 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6995 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
6996
6997 if (putpkt (rs->buf) < 0)
6998 error (_("Communication problem with target."));
6999
7000 rs->buf[0] = '\0';
7001 getpkt (&rs->buf, &rs->buf_size, 0);
7002
7003 return packet_check_result (rs->buf);
7004 }
7005
7006 static void
7007 restore_remote_timeout (void *p)
7008 {
7009 int value = *(int *)p;
7010
7011 remote_timeout = value;
7012 }
7013
7014 /* Flash writing can take quite some time. We'll set
7015 effectively infinite timeout for flash operations.
7016 In future, we'll need to decide on a better approach. */
7017 static const int remote_flash_timeout = 1000;
7018
7019 static void
7020 remote_flash_erase (struct target_ops *ops,
7021 ULONGEST address, LONGEST length)
7022 {
7023 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7024 int saved_remote_timeout = remote_timeout;
7025 enum packet_result ret;
7026 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7027 &saved_remote_timeout);
7028
7029 remote_timeout = remote_flash_timeout;
7030
7031 ret = remote_send_printf ("vFlashErase:%s,%s",
7032 phex (address, addr_size),
7033 phex (length, 4));
7034 switch (ret)
7035 {
7036 case PACKET_UNKNOWN:
7037 error (_("Remote target does not support flash erase"));
7038 case PACKET_ERROR:
7039 error (_("Error erasing flash with vFlashErase packet"));
7040 default:
7041 break;
7042 }
7043
7044 do_cleanups (back_to);
7045 }
7046
7047 static LONGEST
7048 remote_flash_write (struct target_ops *ops,
7049 ULONGEST address, LONGEST length,
7050 const gdb_byte *data)
7051 {
7052 int saved_remote_timeout = remote_timeout;
7053 LONGEST ret;
7054 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7055 &saved_remote_timeout);
7056
7057 remote_timeout = remote_flash_timeout;
7058 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
7059 do_cleanups (back_to);
7060
7061 return ret;
7062 }
7063
7064 static void
7065 remote_flash_done (struct target_ops *ops)
7066 {
7067 int saved_remote_timeout = remote_timeout;
7068 int 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_send_printf ("vFlashDone");
7074 do_cleanups (back_to);
7075
7076 switch (ret)
7077 {
7078 case PACKET_UNKNOWN:
7079 error (_("Remote target does not support vFlashDone"));
7080 case PACKET_ERROR:
7081 error (_("Error finishing flash operation"));
7082 default:
7083 break;
7084 }
7085 }
7086
7087 static void
7088 remote_files_info (struct target_ops *ignore)
7089 {
7090 puts_filtered ("Debugging a target over a serial line.\n");
7091 }
7092 \f
7093 /* Stuff for dealing with the packets which are part of this protocol.
7094 See comment at top of file for details. */
7095
7096 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7097 error to higher layers. Called when a serial error is detected.
7098 The exception message is STRING, followed by a colon and a blank,
7099 the system error message for errno at function entry and final dot
7100 for output compatibility with throw_perror_with_name. */
7101
7102 static void
7103 unpush_and_perror (const char *string)
7104 {
7105 int saved_errno = errno;
7106
7107 remote_unpush_target ();
7108 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7109 safe_strerror (saved_errno));
7110 }
7111
7112 /* Read a single character from the remote end. */
7113
7114 static int
7115 readchar (int timeout)
7116 {
7117 int ch;
7118 struct remote_state *rs = get_remote_state ();
7119
7120 ch = serial_readchar (rs->remote_desc, timeout);
7121
7122 if (ch >= 0)
7123 return ch;
7124
7125 switch ((enum serial_rc) ch)
7126 {
7127 case SERIAL_EOF:
7128 remote_unpush_target ();
7129 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7130 /* no return */
7131 case SERIAL_ERROR:
7132 unpush_and_perror (_("Remote communication error. "
7133 "Target disconnected."));
7134 /* no return */
7135 case SERIAL_TIMEOUT:
7136 break;
7137 }
7138 return ch;
7139 }
7140
7141 /* Wrapper for serial_write that closes the target and throws if
7142 writing fails. */
7143
7144 static void
7145 remote_serial_write (const char *str, int len)
7146 {
7147 struct remote_state *rs = get_remote_state ();
7148
7149 if (serial_write (rs->remote_desc, str, len))
7150 {
7151 unpush_and_perror (_("Remote communication error. "
7152 "Target disconnected."));
7153 }
7154 }
7155
7156 /* Send the command in *BUF to the remote machine, and read the reply
7157 into *BUF. Report an error if we get an error reply. Resize
7158 *BUF using xrealloc if necessary to hold the result, and update
7159 *SIZEOF_BUF. */
7160
7161 static void
7162 remote_send (char **buf,
7163 long *sizeof_buf)
7164 {
7165 putpkt (*buf);
7166 getpkt (buf, sizeof_buf, 0);
7167
7168 if ((*buf)[0] == 'E')
7169 error (_("Remote failure reply: %s"), *buf);
7170 }
7171
7172 /* Return a pointer to an xmalloc'ed string representing an escaped
7173 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7174 etc. The caller is responsible for releasing the returned
7175 memory. */
7176
7177 static char *
7178 escape_buffer (const char *buf, int n)
7179 {
7180 struct cleanup *old_chain;
7181 struct ui_file *stb;
7182 char *str;
7183
7184 stb = mem_fileopen ();
7185 old_chain = make_cleanup_ui_file_delete (stb);
7186
7187 fputstrn_unfiltered (buf, n, 0, stb);
7188 str = ui_file_xstrdup (stb, NULL);
7189 do_cleanups (old_chain);
7190 return str;
7191 }
7192
7193 /* Display a null-terminated packet on stdout, for debugging, using C
7194 string notation. */
7195
7196 static void
7197 print_packet (char *buf)
7198 {
7199 puts_filtered ("\"");
7200 fputstr_filtered (buf, '"', gdb_stdout);
7201 puts_filtered ("\"");
7202 }
7203
7204 int
7205 putpkt (char *buf)
7206 {
7207 return putpkt_binary (buf, strlen (buf));
7208 }
7209
7210 /* Send a packet to the remote machine, with error checking. The data
7211 of the packet is in BUF. The string in BUF can be at most
7212 get_remote_packet_size () - 5 to account for the $, # and checksum,
7213 and for a possible /0 if we are debugging (remote_debug) and want
7214 to print the sent packet as a string. */
7215
7216 static int
7217 putpkt_binary (char *buf, int cnt)
7218 {
7219 struct remote_state *rs = get_remote_state ();
7220 int i;
7221 unsigned char csum = 0;
7222 char *buf2 = alloca (cnt + 6);
7223
7224 int ch;
7225 int tcount = 0;
7226 char *p;
7227 char *message;
7228
7229 /* Catch cases like trying to read memory or listing threads while
7230 we're waiting for a stop reply. The remote server wouldn't be
7231 ready to handle this request, so we'd hang and timeout. We don't
7232 have to worry about this in synchronous mode, because in that
7233 case it's not possible to issue a command while the target is
7234 running. This is not a problem in non-stop mode, because in that
7235 case, the stub is always ready to process serial input. */
7236 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
7237 error (_("Cannot execute this command while the target is running."));
7238
7239 /* We're sending out a new packet. Make sure we don't look at a
7240 stale cached response. */
7241 rs->cached_wait_status = 0;
7242
7243 /* Copy the packet into buffer BUF2, encapsulating it
7244 and giving it a checksum. */
7245
7246 p = buf2;
7247 *p++ = '$';
7248
7249 for (i = 0; i < cnt; i++)
7250 {
7251 csum += buf[i];
7252 *p++ = buf[i];
7253 }
7254 *p++ = '#';
7255 *p++ = tohex ((csum >> 4) & 0xf);
7256 *p++ = tohex (csum & 0xf);
7257
7258 /* Send it over and over until we get a positive ack. */
7259
7260 while (1)
7261 {
7262 int started_error_output = 0;
7263
7264 if (remote_debug)
7265 {
7266 struct cleanup *old_chain;
7267 char *str;
7268
7269 *p = '\0';
7270 str = escape_buffer (buf2, p - buf2);
7271 old_chain = make_cleanup (xfree, str);
7272 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7273 gdb_flush (gdb_stdlog);
7274 do_cleanups (old_chain);
7275 }
7276 remote_serial_write (buf2, p - buf2);
7277
7278 /* If this is a no acks version of the remote protocol, send the
7279 packet and move on. */
7280 if (rs->noack_mode)
7281 break;
7282
7283 /* Read until either a timeout occurs (-2) or '+' is read.
7284 Handle any notification that arrives in the mean time. */
7285 while (1)
7286 {
7287 ch = readchar (remote_timeout);
7288
7289 if (remote_debug)
7290 {
7291 switch (ch)
7292 {
7293 case '+':
7294 case '-':
7295 case SERIAL_TIMEOUT:
7296 case '$':
7297 case '%':
7298 if (started_error_output)
7299 {
7300 putchar_unfiltered ('\n');
7301 started_error_output = 0;
7302 }
7303 }
7304 }
7305
7306 switch (ch)
7307 {
7308 case '+':
7309 if (remote_debug)
7310 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7311 return 1;
7312 case '-':
7313 if (remote_debug)
7314 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7315 /* FALLTHROUGH */
7316 case SERIAL_TIMEOUT:
7317 tcount++;
7318 if (tcount > 3)
7319 return 0;
7320 break; /* Retransmit buffer. */
7321 case '$':
7322 {
7323 if (remote_debug)
7324 fprintf_unfiltered (gdb_stdlog,
7325 "Packet instead of Ack, ignoring it\n");
7326 /* It's probably an old response sent because an ACK
7327 was lost. Gobble up the packet and ack it so it
7328 doesn't get retransmitted when we resend this
7329 packet. */
7330 skip_frame ();
7331 remote_serial_write ("+", 1);
7332 continue; /* Now, go look for +. */
7333 }
7334
7335 case '%':
7336 {
7337 int val;
7338
7339 /* If we got a notification, handle it, and go back to looking
7340 for an ack. */
7341 /* We've found the start of a notification. Now
7342 collect the data. */
7343 val = read_frame (&rs->buf, &rs->buf_size);
7344 if (val >= 0)
7345 {
7346 if (remote_debug)
7347 {
7348 struct cleanup *old_chain;
7349 char *str;
7350
7351 str = escape_buffer (rs->buf, val);
7352 old_chain = make_cleanup (xfree, str);
7353 fprintf_unfiltered (gdb_stdlog,
7354 " Notification received: %s\n",
7355 str);
7356 do_cleanups (old_chain);
7357 }
7358 handle_notification (rs->notif_state, rs->buf);
7359 /* We're in sync now, rewait for the ack. */
7360 tcount = 0;
7361 }
7362 else
7363 {
7364 if (remote_debug)
7365 {
7366 if (!started_error_output)
7367 {
7368 started_error_output = 1;
7369 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7370 }
7371 fputc_unfiltered (ch & 0177, gdb_stdlog);
7372 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7373 }
7374 }
7375 continue;
7376 }
7377 /* fall-through */
7378 default:
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 }
7388 continue;
7389 }
7390 break; /* Here to retransmit. */
7391 }
7392
7393 #if 0
7394 /* This is wrong. If doing a long backtrace, the user should be
7395 able to get out next time we call QUIT, without anything as
7396 violent as interrupt_query. If we want to provide a way out of
7397 here without getting to the next QUIT, it should be based on
7398 hitting ^C twice as in remote_wait. */
7399 if (quit_flag)
7400 {
7401 quit_flag = 0;
7402 interrupt_query ();
7403 }
7404 #endif
7405 }
7406 return 0;
7407 }
7408
7409 /* Come here after finding the start of a frame when we expected an
7410 ack. Do our best to discard the rest of this packet. */
7411
7412 static void
7413 skip_frame (void)
7414 {
7415 int c;
7416
7417 while (1)
7418 {
7419 c = readchar (remote_timeout);
7420 switch (c)
7421 {
7422 case SERIAL_TIMEOUT:
7423 /* Nothing we can do. */
7424 return;
7425 case '#':
7426 /* Discard the two bytes of checksum and stop. */
7427 c = readchar (remote_timeout);
7428 if (c >= 0)
7429 c = readchar (remote_timeout);
7430
7431 return;
7432 case '*': /* Run length encoding. */
7433 /* Discard the repeat count. */
7434 c = readchar (remote_timeout);
7435 if (c < 0)
7436 return;
7437 break;
7438 default:
7439 /* A regular character. */
7440 break;
7441 }
7442 }
7443 }
7444
7445 /* Come here after finding the start of the frame. Collect the rest
7446 into *BUF, verifying the checksum, length, and handling run-length
7447 compression. NUL terminate the buffer. If there is not enough room,
7448 expand *BUF using xrealloc.
7449
7450 Returns -1 on error, number of characters in buffer (ignoring the
7451 trailing NULL) on success. (could be extended to return one of the
7452 SERIAL status indications). */
7453
7454 static long
7455 read_frame (char **buf_p,
7456 long *sizeof_buf)
7457 {
7458 unsigned char csum;
7459 long bc;
7460 int c;
7461 char *buf = *buf_p;
7462 struct remote_state *rs = get_remote_state ();
7463
7464 csum = 0;
7465 bc = 0;
7466
7467 while (1)
7468 {
7469 c = readchar (remote_timeout);
7470 switch (c)
7471 {
7472 case SERIAL_TIMEOUT:
7473 if (remote_debug)
7474 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7475 return -1;
7476 case '$':
7477 if (remote_debug)
7478 fputs_filtered ("Saw new packet start in middle of old one\n",
7479 gdb_stdlog);
7480 return -1; /* Start a new packet, count retries. */
7481 case '#':
7482 {
7483 unsigned char pktcsum;
7484 int check_0 = 0;
7485 int check_1 = 0;
7486
7487 buf[bc] = '\0';
7488
7489 check_0 = readchar (remote_timeout);
7490 if (check_0 >= 0)
7491 check_1 = readchar (remote_timeout);
7492
7493 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7494 {
7495 if (remote_debug)
7496 fputs_filtered ("Timeout in checksum, retrying\n",
7497 gdb_stdlog);
7498 return -1;
7499 }
7500 else if (check_0 < 0 || check_1 < 0)
7501 {
7502 if (remote_debug)
7503 fputs_filtered ("Communication error in checksum\n",
7504 gdb_stdlog);
7505 return -1;
7506 }
7507
7508 /* Don't recompute the checksum; with no ack packets we
7509 don't have any way to indicate a packet retransmission
7510 is necessary. */
7511 if (rs->noack_mode)
7512 return bc;
7513
7514 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7515 if (csum == pktcsum)
7516 return bc;
7517
7518 if (remote_debug)
7519 {
7520 struct cleanup *old_chain;
7521 char *str;
7522
7523 str = escape_buffer (buf, bc);
7524 old_chain = make_cleanup (xfree, str);
7525 fprintf_unfiltered (gdb_stdlog,
7526 "Bad checksum, sentsum=0x%x, "
7527 "csum=0x%x, buf=%s\n",
7528 pktcsum, csum, str);
7529 do_cleanups (old_chain);
7530 }
7531 /* Number of characters in buffer ignoring trailing
7532 NULL. */
7533 return -1;
7534 }
7535 case '*': /* Run length encoding. */
7536 {
7537 int repeat;
7538
7539 csum += c;
7540 c = readchar (remote_timeout);
7541 csum += c;
7542 repeat = c - ' ' + 3; /* Compute repeat count. */
7543
7544 /* The character before ``*'' is repeated. */
7545
7546 if (repeat > 0 && repeat <= 255 && bc > 0)
7547 {
7548 if (bc + repeat - 1 >= *sizeof_buf - 1)
7549 {
7550 /* Make some more room in the buffer. */
7551 *sizeof_buf += repeat;
7552 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7553 buf = *buf_p;
7554 }
7555
7556 memset (&buf[bc], buf[bc - 1], repeat);
7557 bc += repeat;
7558 continue;
7559 }
7560
7561 buf[bc] = '\0';
7562 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7563 return -1;
7564 }
7565 default:
7566 if (bc >= *sizeof_buf - 1)
7567 {
7568 /* Make some more room in the buffer. */
7569 *sizeof_buf *= 2;
7570 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7571 buf = *buf_p;
7572 }
7573
7574 buf[bc++] = c;
7575 csum += c;
7576 continue;
7577 }
7578 }
7579 }
7580
7581 /* Read a packet from the remote machine, with error checking, and
7582 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7583 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7584 rather than timing out; this is used (in synchronous mode) to wait
7585 for a target that is is executing user code to stop. */
7586 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7587 don't have to change all the calls to getpkt to deal with the
7588 return value, because at the moment I don't know what the right
7589 thing to do it for those. */
7590 void
7591 getpkt (char **buf,
7592 long *sizeof_buf,
7593 int forever)
7594 {
7595 int timed_out;
7596
7597 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7598 }
7599
7600
7601 /* Read a packet from the remote machine, with error checking, and
7602 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7603 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7604 rather than timing out; this is used (in synchronous mode) to wait
7605 for a target that is is executing user code to stop. If FOREVER ==
7606 0, this function is allowed to time out gracefully and return an
7607 indication of this to the caller. Otherwise return the number of
7608 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7609 enough reason to return to the caller. *IS_NOTIF is an output
7610 boolean that indicates whether *BUF holds a notification or not
7611 (a regular packet). */
7612
7613 static int
7614 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7615 int expecting_notif, int *is_notif)
7616 {
7617 struct remote_state *rs = get_remote_state ();
7618 int c;
7619 int tries;
7620 int timeout;
7621 int val = -1;
7622
7623 /* We're reading a new response. Make sure we don't look at a
7624 previously cached response. */
7625 rs->cached_wait_status = 0;
7626
7627 strcpy (*buf, "timeout");
7628
7629 if (forever)
7630 timeout = watchdog > 0 ? watchdog : -1;
7631 else if (expecting_notif)
7632 timeout = 0; /* There should already be a char in the buffer. If
7633 not, bail out. */
7634 else
7635 timeout = remote_timeout;
7636
7637 #define MAX_TRIES 3
7638
7639 /* Process any number of notifications, and then return when
7640 we get a packet. */
7641 for (;;)
7642 {
7643 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7644 times. */
7645 for (tries = 1; tries <= MAX_TRIES; tries++)
7646 {
7647 /* This can loop forever if the remote side sends us
7648 characters continuously, but if it pauses, we'll get
7649 SERIAL_TIMEOUT from readchar because of timeout. Then
7650 we'll count that as a retry.
7651
7652 Note that even when forever is set, we will only wait
7653 forever prior to the start of a packet. After that, we
7654 expect characters to arrive at a brisk pace. They should
7655 show up within remote_timeout intervals. */
7656 do
7657 c = readchar (timeout);
7658 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7659
7660 if (c == SERIAL_TIMEOUT)
7661 {
7662 if (expecting_notif)
7663 return -1; /* Don't complain, it's normal to not get
7664 anything in this case. */
7665
7666 if (forever) /* Watchdog went off? Kill the target. */
7667 {
7668 QUIT;
7669 remote_unpush_target ();
7670 throw_error (TARGET_CLOSE_ERROR,
7671 _("Watchdog timeout has expired. "
7672 "Target detached."));
7673 }
7674 if (remote_debug)
7675 fputs_filtered ("Timed out.\n", gdb_stdlog);
7676 }
7677 else
7678 {
7679 /* We've found the start of a packet or notification.
7680 Now collect the data. */
7681 val = read_frame (buf, sizeof_buf);
7682 if (val >= 0)
7683 break;
7684 }
7685
7686 remote_serial_write ("-", 1);
7687 }
7688
7689 if (tries > MAX_TRIES)
7690 {
7691 /* We have tried hard enough, and just can't receive the
7692 packet/notification. Give up. */
7693 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7694
7695 /* Skip the ack char if we're in no-ack mode. */
7696 if (!rs->noack_mode)
7697 remote_serial_write ("+", 1);
7698 return -1;
7699 }
7700
7701 /* If we got an ordinary packet, return that to our caller. */
7702 if (c == '$')
7703 {
7704 if (remote_debug)
7705 {
7706 struct cleanup *old_chain;
7707 char *str;
7708
7709 str = escape_buffer (*buf, val);
7710 old_chain = make_cleanup (xfree, str);
7711 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7712 do_cleanups (old_chain);
7713 }
7714
7715 /* Skip the ack char if we're in no-ack mode. */
7716 if (!rs->noack_mode)
7717 remote_serial_write ("+", 1);
7718 if (is_notif != NULL)
7719 *is_notif = 0;
7720 return val;
7721 }
7722
7723 /* If we got a notification, handle it, and go back to looking
7724 for a packet. */
7725 else
7726 {
7727 gdb_assert (c == '%');
7728
7729 if (remote_debug)
7730 {
7731 struct cleanup *old_chain;
7732 char *str;
7733
7734 str = escape_buffer (*buf, val);
7735 old_chain = make_cleanup (xfree, str);
7736 fprintf_unfiltered (gdb_stdlog,
7737 " Notification received: %s\n",
7738 str);
7739 do_cleanups (old_chain);
7740 }
7741 if (is_notif != NULL)
7742 *is_notif = 1;
7743
7744 handle_notification (rs->notif_state, *buf);
7745
7746 /* Notifications require no acknowledgement. */
7747
7748 if (expecting_notif)
7749 return val;
7750 }
7751 }
7752 }
7753
7754 static int
7755 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7756 {
7757 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7758 }
7759
7760 static int
7761 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7762 int *is_notif)
7763 {
7764 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7765 is_notif);
7766 }
7767
7768 \f
7769 /* A helper function that just calls putpkt; for type correctness. */
7770
7771 static int
7772 putpkt_for_catch_errors (void *arg)
7773 {
7774 return putpkt (arg);
7775 }
7776
7777 static void
7778 remote_kill (struct target_ops *ops)
7779 {
7780 /* Use catch_errors so the user can quit from gdb even when we
7781 aren't on speaking terms with the remote system. */
7782 catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
7783
7784 /* Don't wait for it to die. I'm not really sure it matters whether
7785 we do or not. For the existing stubs, kill is a noop. */
7786 target_mourn_inferior ();
7787 }
7788
7789 static int
7790 remote_vkill (int pid, struct remote_state *rs)
7791 {
7792 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7793 return -1;
7794
7795 /* Tell the remote target to detach. */
7796 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7797 putpkt (rs->buf);
7798 getpkt (&rs->buf, &rs->buf_size, 0);
7799
7800 if (packet_ok (rs->buf,
7801 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7802 return 0;
7803 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7804 return -1;
7805 else
7806 return 1;
7807 }
7808
7809 static void
7810 extended_remote_kill (struct target_ops *ops)
7811 {
7812 int res;
7813 int pid = ptid_get_pid (inferior_ptid);
7814 struct remote_state *rs = get_remote_state ();
7815
7816 res = remote_vkill (pid, rs);
7817 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7818 {
7819 /* Don't try 'k' on a multi-process aware stub -- it has no way
7820 to specify the pid. */
7821
7822 putpkt ("k");
7823 #if 0
7824 getpkt (&rs->buf, &rs->buf_size, 0);
7825 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7826 res = 1;
7827 #else
7828 /* Don't wait for it to die. I'm not really sure it matters whether
7829 we do or not. For the existing stubs, kill is a noop. */
7830 res = 0;
7831 #endif
7832 }
7833
7834 if (res != 0)
7835 error (_("Can't kill process"));
7836
7837 target_mourn_inferior ();
7838 }
7839
7840 static void
7841 remote_mourn (struct target_ops *ops)
7842 {
7843 remote_mourn_1 (ops);
7844 }
7845
7846 /* Worker function for remote_mourn. */
7847 static void
7848 remote_mourn_1 (struct target_ops *target)
7849 {
7850 unpush_target (target);
7851
7852 /* remote_close takes care of doing most of the clean up. */
7853 generic_mourn_inferior ();
7854 }
7855
7856 static void
7857 extended_remote_mourn_1 (struct target_ops *target)
7858 {
7859 struct remote_state *rs = get_remote_state ();
7860
7861 /* In case we got here due to an error, but we're going to stay
7862 connected. */
7863 rs->waiting_for_stop_reply = 0;
7864
7865 /* If the current general thread belonged to the process we just
7866 detached from or has exited, the remote side current general
7867 thread becomes undefined. Considering a case like this:
7868
7869 - We just got here due to a detach.
7870 - The process that we're detaching from happens to immediately
7871 report a global breakpoint being hit in non-stop mode, in the
7872 same thread we had selected before.
7873 - GDB attaches to this process again.
7874 - This event happens to be the next event we handle.
7875
7876 GDB would consider that the current general thread didn't need to
7877 be set on the stub side (with Hg), since for all it knew,
7878 GENERAL_THREAD hadn't changed.
7879
7880 Notice that although in all-stop mode, the remote server always
7881 sets the current thread to the thread reporting the stop event,
7882 that doesn't happen in non-stop mode; in non-stop, the stub *must
7883 not* change the current thread when reporting a breakpoint hit,
7884 due to the decoupling of event reporting and event handling.
7885
7886 To keep things simple, we always invalidate our notion of the
7887 current thread. */
7888 record_currthread (rs, minus_one_ptid);
7889
7890 /* Unlike "target remote", we do not want to unpush the target; then
7891 the next time the user says "run", we won't be connected. */
7892
7893 /* Call common code to mark the inferior as not running. */
7894 generic_mourn_inferior ();
7895
7896 if (!have_inferiors ())
7897 {
7898 if (!remote_multi_process_p (rs))
7899 {
7900 /* Check whether the target is running now - some remote stubs
7901 automatically restart after kill. */
7902 putpkt ("?");
7903 getpkt (&rs->buf, &rs->buf_size, 0);
7904
7905 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7906 {
7907 /* Assume that the target has been restarted. Set
7908 inferior_ptid so that bits of core GDB realizes
7909 there's something here, e.g., so that the user can
7910 say "kill" again. */
7911 inferior_ptid = magic_null_ptid;
7912 }
7913 }
7914 }
7915 }
7916
7917 static void
7918 extended_remote_mourn (struct target_ops *ops)
7919 {
7920 extended_remote_mourn_1 (ops);
7921 }
7922
7923 static int
7924 extended_remote_supports_disable_randomization (void)
7925 {
7926 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7927 == PACKET_ENABLE);
7928 }
7929
7930 static void
7931 extended_remote_disable_randomization (int val)
7932 {
7933 struct remote_state *rs = get_remote_state ();
7934 char *reply;
7935
7936 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7937 val);
7938 putpkt (rs->buf);
7939 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7940 if (*reply == '\0')
7941 error (_("Target does not support QDisableRandomization."));
7942 if (strcmp (reply, "OK") != 0)
7943 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7944 }
7945
7946 static int
7947 extended_remote_run (char *args)
7948 {
7949 struct remote_state *rs = get_remote_state ();
7950 int len;
7951
7952 /* If the user has disabled vRun support, or we have detected that
7953 support is not available, do not try it. */
7954 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7955 return -1;
7956
7957 strcpy (rs->buf, "vRun;");
7958 len = strlen (rs->buf);
7959
7960 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7961 error (_("Remote file name too long for run packet"));
7962 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7963
7964 gdb_assert (args != NULL);
7965 if (*args)
7966 {
7967 struct cleanup *back_to;
7968 int i;
7969 char **argv;
7970
7971 argv = gdb_buildargv (args);
7972 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7973 for (i = 0; argv[i] != NULL; i++)
7974 {
7975 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7976 error (_("Argument list too long for run packet"));
7977 rs->buf[len++] = ';';
7978 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7979 }
7980 do_cleanups (back_to);
7981 }
7982
7983 rs->buf[len++] = '\0';
7984
7985 putpkt (rs->buf);
7986 getpkt (&rs->buf, &rs->buf_size, 0);
7987
7988 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7989 {
7990 /* We have a wait response. All is well. */
7991 return 0;
7992 }
7993 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7994 /* It wasn't disabled before, but it is now. */
7995 return -1;
7996 else
7997 {
7998 if (remote_exec_file[0] == '\0')
7999 error (_("Running the default executable on the remote target failed; "
8000 "try \"set remote exec-file\"?"));
8001 else
8002 error (_("Running \"%s\" on the remote target failed"),
8003 remote_exec_file);
8004 }
8005 }
8006
8007 /* In the extended protocol we want to be able to do things like
8008 "run" and have them basically work as expected. So we need
8009 a special create_inferior function. We support changing the
8010 executable file and the command line arguments, but not the
8011 environment. */
8012
8013 static void
8014 extended_remote_create_inferior_1 (char *exec_file, char *args,
8015 char **env, int from_tty)
8016 {
8017 int run_worked;
8018 char *stop_reply;
8019 struct remote_state *rs = get_remote_state ();
8020
8021 /* If running asynchronously, register the target file descriptor
8022 with the event loop. */
8023 if (target_can_async_p ())
8024 target_async (inferior_event_handler, 0);
8025
8026 /* Disable address space randomization if requested (and supported). */
8027 if (extended_remote_supports_disable_randomization ())
8028 extended_remote_disable_randomization (disable_randomization);
8029
8030 /* Now restart the remote server. */
8031 run_worked = extended_remote_run (args) != -1;
8032 if (!run_worked)
8033 {
8034 /* vRun was not supported. Fail if we need it to do what the
8035 user requested. */
8036 if (remote_exec_file[0])
8037 error (_("Remote target does not support \"set remote exec-file\""));
8038 if (args[0])
8039 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8040
8041 /* Fall back to "R". */
8042 extended_remote_restart ();
8043 }
8044
8045 if (!have_inferiors ())
8046 {
8047 /* Clean up from the last time we ran, before we mark the target
8048 running again. This will mark breakpoints uninserted, and
8049 get_offsets may insert breakpoints. */
8050 init_thread_list ();
8051 init_wait_for_inferior ();
8052 }
8053
8054 /* vRun's success return is a stop reply. */
8055 stop_reply = run_worked ? rs->buf : NULL;
8056 add_current_inferior_and_thread (stop_reply);
8057
8058 /* Get updated offsets, if the stub uses qOffsets. */
8059 get_offsets ();
8060 }
8061
8062 static void
8063 extended_remote_create_inferior (struct target_ops *ops,
8064 char *exec_file, char *args,
8065 char **env, int from_tty)
8066 {
8067 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
8068 }
8069 \f
8070
8071 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8072 the list of conditions (in agent expression bytecode format), if any, the
8073 target needs to evaluate. The output is placed into the packet buffer
8074 started from BUF and ended at BUF_END. */
8075
8076 static int
8077 remote_add_target_side_condition (struct gdbarch *gdbarch,
8078 struct bp_target_info *bp_tgt, char *buf,
8079 char *buf_end)
8080 {
8081 struct agent_expr *aexpr = NULL;
8082 int i, ix;
8083 char *pkt;
8084 char *buf_start = buf;
8085
8086 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8087 return 0;
8088
8089 buf += strlen (buf);
8090 xsnprintf (buf, buf_end - buf, "%s", ";");
8091 buf++;
8092
8093 /* Send conditions to the target and free the vector. */
8094 for (ix = 0;
8095 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8096 ix++)
8097 {
8098 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8099 buf += strlen (buf);
8100 for (i = 0; i < aexpr->len; ++i)
8101 buf = pack_hex_byte (buf, aexpr->buf[i]);
8102 *buf = '\0';
8103 }
8104
8105 VEC_free (agent_expr_p, bp_tgt->conditions);
8106 return 0;
8107 }
8108
8109 static void
8110 remote_add_target_side_commands (struct gdbarch *gdbarch,
8111 struct bp_target_info *bp_tgt, char *buf)
8112 {
8113 struct agent_expr *aexpr = NULL;
8114 int i, ix;
8115
8116 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8117 return;
8118
8119 buf += strlen (buf);
8120
8121 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8122 buf += strlen (buf);
8123
8124 /* Concatenate all the agent expressions that are commands into the
8125 cmds parameter. */
8126 for (ix = 0;
8127 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8128 ix++)
8129 {
8130 sprintf (buf, "X%x,", aexpr->len);
8131 buf += strlen (buf);
8132 for (i = 0; i < aexpr->len; ++i)
8133 buf = pack_hex_byte (buf, aexpr->buf[i]);
8134 *buf = '\0';
8135 }
8136
8137 VEC_free (agent_expr_p, bp_tgt->tcommands);
8138 }
8139
8140 /* Insert a breakpoint. On targets that have software breakpoint
8141 support, we ask the remote target to do the work; on targets
8142 which don't, we insert a traditional memory breakpoint. */
8143
8144 static int
8145 remote_insert_breakpoint (struct gdbarch *gdbarch,
8146 struct bp_target_info *bp_tgt)
8147 {
8148 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8149 If it succeeds, then set the support to PACKET_ENABLE. If it
8150 fails, and the user has explicitly requested the Z support then
8151 report an error, otherwise, mark it disabled and go on. */
8152
8153 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8154 {
8155 CORE_ADDR addr = bp_tgt->placed_address;
8156 struct remote_state *rs;
8157 char *p, *endbuf;
8158 int bpsize;
8159 struct condition_list *cond = NULL;
8160
8161 /* Make sure the remote is pointing at the right process, if
8162 necessary. */
8163 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8164 set_general_process ();
8165
8166 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8167
8168 rs = get_remote_state ();
8169 p = rs->buf;
8170 endbuf = rs->buf + get_remote_packet_size ();
8171
8172 *(p++) = 'Z';
8173 *(p++) = '0';
8174 *(p++) = ',';
8175 addr = (ULONGEST) remote_address_masked (addr);
8176 p += hexnumstr (p, addr);
8177 xsnprintf (p, endbuf - p, ",%d", bpsize);
8178
8179 if (remote_supports_cond_breakpoints ())
8180 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8181
8182 if (remote_can_run_breakpoint_commands ())
8183 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8184
8185 putpkt (rs->buf);
8186 getpkt (&rs->buf, &rs->buf_size, 0);
8187
8188 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8189 {
8190 case PACKET_ERROR:
8191 return -1;
8192 case PACKET_OK:
8193 bp_tgt->placed_address = addr;
8194 bp_tgt->placed_size = bpsize;
8195 return 0;
8196 case PACKET_UNKNOWN:
8197 break;
8198 }
8199 }
8200
8201 return memory_insert_breakpoint (gdbarch, bp_tgt);
8202 }
8203
8204 static int
8205 remote_remove_breakpoint (struct gdbarch *gdbarch,
8206 struct bp_target_info *bp_tgt)
8207 {
8208 CORE_ADDR addr = bp_tgt->placed_address;
8209 struct remote_state *rs = get_remote_state ();
8210
8211 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8212 {
8213 char *p = rs->buf;
8214 char *endbuf = rs->buf + get_remote_packet_size ();
8215
8216 /* Make sure the remote is pointing at the right process, if
8217 necessary. */
8218 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8219 set_general_process ();
8220
8221 *(p++) = 'z';
8222 *(p++) = '0';
8223 *(p++) = ',';
8224
8225 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8226 p += hexnumstr (p, addr);
8227 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8228
8229 putpkt (rs->buf);
8230 getpkt (&rs->buf, &rs->buf_size, 0);
8231
8232 return (rs->buf[0] == 'E');
8233 }
8234
8235 return memory_remove_breakpoint (gdbarch, bp_tgt);
8236 }
8237
8238 static int
8239 watchpoint_to_Z_packet (int type)
8240 {
8241 switch (type)
8242 {
8243 case hw_write:
8244 return Z_PACKET_WRITE_WP;
8245 break;
8246 case hw_read:
8247 return Z_PACKET_READ_WP;
8248 break;
8249 case hw_access:
8250 return Z_PACKET_ACCESS_WP;
8251 break;
8252 default:
8253 internal_error (__FILE__, __LINE__,
8254 _("hw_bp_to_z: bad watchpoint type %d"), type);
8255 }
8256 }
8257
8258 static int
8259 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
8260 struct expression *cond)
8261 {
8262 struct remote_state *rs = get_remote_state ();
8263 char *endbuf = rs->buf + get_remote_packet_size ();
8264 char *p;
8265 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8266
8267 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8268 return 1;
8269
8270 /* Make sure the remote is pointing at the right process, if
8271 necessary. */
8272 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8273 set_general_process ();
8274
8275 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8276 p = strchr (rs->buf, '\0');
8277 addr = remote_address_masked (addr);
8278 p += hexnumstr (p, (ULONGEST) addr);
8279 xsnprintf (p, endbuf - p, ",%x", len);
8280
8281 putpkt (rs->buf);
8282 getpkt (&rs->buf, &rs->buf_size, 0);
8283
8284 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8285 {
8286 case PACKET_ERROR:
8287 return -1;
8288 case PACKET_UNKNOWN:
8289 return 1;
8290 case PACKET_OK:
8291 return 0;
8292 }
8293 internal_error (__FILE__, __LINE__,
8294 _("remote_insert_watchpoint: reached end of function"));
8295 }
8296
8297 static int
8298 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8299 CORE_ADDR start, int length)
8300 {
8301 CORE_ADDR diff = remote_address_masked (addr - start);
8302
8303 return diff < length;
8304 }
8305
8306
8307 static int
8308 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
8309 struct expression *cond)
8310 {
8311 struct remote_state *rs = get_remote_state ();
8312 char *endbuf = rs->buf + get_remote_packet_size ();
8313 char *p;
8314 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8315
8316 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8317 return -1;
8318
8319 /* Make sure the remote is pointing at the right process, if
8320 necessary. */
8321 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8322 set_general_process ();
8323
8324 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8325 p = strchr (rs->buf, '\0');
8326 addr = remote_address_masked (addr);
8327 p += hexnumstr (p, (ULONGEST) addr);
8328 xsnprintf (p, endbuf - p, ",%x", len);
8329 putpkt (rs->buf);
8330 getpkt (&rs->buf, &rs->buf_size, 0);
8331
8332 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8333 {
8334 case PACKET_ERROR:
8335 case PACKET_UNKNOWN:
8336 return -1;
8337 case PACKET_OK:
8338 return 0;
8339 }
8340 internal_error (__FILE__, __LINE__,
8341 _("remote_remove_watchpoint: reached end of function"));
8342 }
8343
8344
8345 int remote_hw_watchpoint_limit = -1;
8346 int remote_hw_watchpoint_length_limit = -1;
8347 int remote_hw_breakpoint_limit = -1;
8348
8349 static int
8350 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
8351 {
8352 if (remote_hw_watchpoint_length_limit == 0)
8353 return 0;
8354 else if (remote_hw_watchpoint_length_limit < 0)
8355 return 1;
8356 else if (len <= remote_hw_watchpoint_length_limit)
8357 return 1;
8358 else
8359 return 0;
8360 }
8361
8362 static int
8363 remote_check_watch_resources (int type, int cnt, int ot)
8364 {
8365 if (type == bp_hardware_breakpoint)
8366 {
8367 if (remote_hw_breakpoint_limit == 0)
8368 return 0;
8369 else if (remote_hw_breakpoint_limit < 0)
8370 return 1;
8371 else if (cnt <= remote_hw_breakpoint_limit)
8372 return 1;
8373 }
8374 else
8375 {
8376 if (remote_hw_watchpoint_limit == 0)
8377 return 0;
8378 else if (remote_hw_watchpoint_limit < 0)
8379 return 1;
8380 else if (ot)
8381 return -1;
8382 else if (cnt <= remote_hw_watchpoint_limit)
8383 return 1;
8384 }
8385 return -1;
8386 }
8387
8388 static int
8389 remote_stopped_by_watchpoint (void)
8390 {
8391 struct remote_state *rs = get_remote_state ();
8392
8393 return rs->remote_stopped_by_watchpoint_p;
8394 }
8395
8396 static int
8397 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8398 {
8399 struct remote_state *rs = get_remote_state ();
8400 int rc = 0;
8401
8402 if (remote_stopped_by_watchpoint ())
8403 {
8404 *addr_p = rs->remote_watch_data_address;
8405 rc = 1;
8406 }
8407
8408 return rc;
8409 }
8410
8411
8412 static int
8413 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
8414 struct bp_target_info *bp_tgt)
8415 {
8416 CORE_ADDR addr;
8417 struct remote_state *rs;
8418 char *p, *endbuf;
8419 char *message;
8420
8421 /* The length field should be set to the size of a breakpoint
8422 instruction, even though we aren't inserting one ourselves. */
8423
8424 gdbarch_remote_breakpoint_from_pc
8425 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
8426
8427 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8428 return -1;
8429
8430 /* Make sure the remote is pointing at the right process, if
8431 necessary. */
8432 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8433 set_general_process ();
8434
8435 rs = get_remote_state ();
8436 p = rs->buf;
8437 endbuf = rs->buf + get_remote_packet_size ();
8438
8439 *(p++) = 'Z';
8440 *(p++) = '1';
8441 *(p++) = ',';
8442
8443 addr = remote_address_masked (bp_tgt->placed_address);
8444 p += hexnumstr (p, (ULONGEST) addr);
8445 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8446
8447 if (remote_supports_cond_breakpoints ())
8448 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8449
8450 if (remote_can_run_breakpoint_commands ())
8451 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8452
8453 putpkt (rs->buf);
8454 getpkt (&rs->buf, &rs->buf_size, 0);
8455
8456 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8457 {
8458 case PACKET_ERROR:
8459 if (rs->buf[1] == '.')
8460 {
8461 message = strchr (rs->buf + 2, '.');
8462 if (message)
8463 error (_("Remote failure reply: %s"), message + 1);
8464 }
8465 return -1;
8466 case PACKET_UNKNOWN:
8467 return -1;
8468 case PACKET_OK:
8469 return 0;
8470 }
8471 internal_error (__FILE__, __LINE__,
8472 _("remote_insert_hw_breakpoint: reached end of function"));
8473 }
8474
8475
8476 static int
8477 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
8478 struct bp_target_info *bp_tgt)
8479 {
8480 CORE_ADDR addr;
8481 struct remote_state *rs = get_remote_state ();
8482 char *p = rs->buf;
8483 char *endbuf = rs->buf + get_remote_packet_size ();
8484
8485 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8486 return -1;
8487
8488 /* Make sure the remote is pointing at the right process, if
8489 necessary. */
8490 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8491 set_general_process ();
8492
8493 *(p++) = 'z';
8494 *(p++) = '1';
8495 *(p++) = ',';
8496
8497 addr = remote_address_masked (bp_tgt->placed_address);
8498 p += hexnumstr (p, (ULONGEST) addr);
8499 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8500
8501 putpkt (rs->buf);
8502 getpkt (&rs->buf, &rs->buf_size, 0);
8503
8504 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8505 {
8506 case PACKET_ERROR:
8507 case PACKET_UNKNOWN:
8508 return -1;
8509 case PACKET_OK:
8510 return 0;
8511 }
8512 internal_error (__FILE__, __LINE__,
8513 _("remote_remove_hw_breakpoint: reached end of function"));
8514 }
8515
8516 /* Verify memory using the "qCRC:" request. */
8517
8518 static int
8519 remote_verify_memory (struct target_ops *ops,
8520 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8521 {
8522 struct remote_state *rs = get_remote_state ();
8523 unsigned long host_crc, target_crc;
8524 char *tmp;
8525
8526 /* Make sure the remote is pointing at the right process. */
8527 set_general_process ();
8528
8529 /* FIXME: assumes lma can fit into long. */
8530 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8531 (long) lma, (long) size);
8532 putpkt (rs->buf);
8533
8534 /* Be clever; compute the host_crc before waiting for target
8535 reply. */
8536 host_crc = xcrc32 (data, size, 0xffffffff);
8537
8538 getpkt (&rs->buf, &rs->buf_size, 0);
8539 if (rs->buf[0] == 'E')
8540 return -1;
8541
8542 if (rs->buf[0] != 'C')
8543 error (_("remote target does not support this operation"));
8544
8545 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8546 target_crc = target_crc * 16 + fromhex (*tmp);
8547
8548 return (host_crc == target_crc);
8549 }
8550
8551 /* compare-sections command
8552
8553 With no arguments, compares each loadable section in the exec bfd
8554 with the same memory range on the target, and reports mismatches.
8555 Useful for verifying the image on the target against the exec file. */
8556
8557 static void
8558 compare_sections_command (char *args, int from_tty)
8559 {
8560 asection *s;
8561 struct cleanup *old_chain;
8562 gdb_byte *sectdata;
8563 const char *sectname;
8564 bfd_size_type size;
8565 bfd_vma lma;
8566 int matched = 0;
8567 int mismatched = 0;
8568 int res;
8569
8570 if (!exec_bfd)
8571 error (_("command cannot be used without an exec file"));
8572
8573 /* Make sure the remote is pointing at the right process. */
8574 set_general_process ();
8575
8576 for (s = exec_bfd->sections; s; s = s->next)
8577 {
8578 if (!(s->flags & SEC_LOAD))
8579 continue; /* Skip non-loadable section. */
8580
8581 size = bfd_get_section_size (s);
8582 if (size == 0)
8583 continue; /* Skip zero-length section. */
8584
8585 sectname = bfd_get_section_name (exec_bfd, s);
8586 if (args && strcmp (args, sectname) != 0)
8587 continue; /* Not the section selected by user. */
8588
8589 matched = 1; /* Do this section. */
8590 lma = s->lma;
8591
8592 sectdata = xmalloc (size);
8593 old_chain = make_cleanup (xfree, sectdata);
8594 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8595
8596 res = target_verify_memory (sectdata, lma, size);
8597
8598 if (res == -1)
8599 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8600 paddress (target_gdbarch (), lma),
8601 paddress (target_gdbarch (), lma + size));
8602
8603 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8604 paddress (target_gdbarch (), lma),
8605 paddress (target_gdbarch (), lma + size));
8606 if (res)
8607 printf_filtered ("matched.\n");
8608 else
8609 {
8610 printf_filtered ("MIS-MATCHED!\n");
8611 mismatched++;
8612 }
8613
8614 do_cleanups (old_chain);
8615 }
8616 if (mismatched > 0)
8617 warning (_("One or more sections of the remote executable does not match\n\
8618 the loaded file\n"));
8619 if (args && !matched)
8620 printf_filtered (_("No loaded section named '%s'.\n"), args);
8621 }
8622
8623 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8624 into remote target. The number of bytes written to the remote
8625 target is returned, or -1 for error. */
8626
8627 static LONGEST
8628 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8629 const char *annex, const gdb_byte *writebuf,
8630 ULONGEST offset, LONGEST len,
8631 struct packet_config *packet)
8632 {
8633 int i, buf_len;
8634 ULONGEST n;
8635 struct remote_state *rs = get_remote_state ();
8636 int max_size = get_memory_write_packet_size ();
8637
8638 if (packet->support == PACKET_DISABLE)
8639 return -1;
8640
8641 /* Insert header. */
8642 i = snprintf (rs->buf, max_size,
8643 "qXfer:%s:write:%s:%s:",
8644 object_name, annex ? annex : "",
8645 phex_nz (offset, sizeof offset));
8646 max_size -= (i + 1);
8647
8648 /* Escape as much data as fits into rs->buf. */
8649 buf_len = remote_escape_output
8650 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8651
8652 if (putpkt_binary (rs->buf, i + buf_len) < 0
8653 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8654 || packet_ok (rs->buf, packet) != PACKET_OK)
8655 return -1;
8656
8657 unpack_varlen_hex (rs->buf, &n);
8658 return n;
8659 }
8660
8661 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8662 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8663 number of bytes read is returned, or 0 for EOF, or -1 for error.
8664 The number of bytes read may be less than LEN without indicating an
8665 EOF. PACKET is checked and updated to indicate whether the remote
8666 target supports this object. */
8667
8668 static LONGEST
8669 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8670 const char *annex,
8671 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8672 struct packet_config *packet)
8673 {
8674 struct remote_state *rs = get_remote_state ();
8675 LONGEST i, n, packet_len;
8676
8677 if (packet->support == PACKET_DISABLE)
8678 return -1;
8679
8680 /* Check whether we've cached an end-of-object packet that matches
8681 this request. */
8682 if (rs->finished_object)
8683 {
8684 if (strcmp (object_name, rs->finished_object) == 0
8685 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8686 && offset == rs->finished_offset)
8687 return 0;
8688
8689 /* Otherwise, we're now reading something different. Discard
8690 the cache. */
8691 xfree (rs->finished_object);
8692 xfree (rs->finished_annex);
8693 rs->finished_object = NULL;
8694 rs->finished_annex = NULL;
8695 }
8696
8697 /* Request only enough to fit in a single packet. The actual data
8698 may not, since we don't know how much of it will need to be escaped;
8699 the target is free to respond with slightly less data. We subtract
8700 five to account for the response type and the protocol frame. */
8701 n = min (get_remote_packet_size () - 5, len);
8702 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8703 object_name, annex ? annex : "",
8704 phex_nz (offset, sizeof offset),
8705 phex_nz (n, sizeof n));
8706 i = putpkt (rs->buf);
8707 if (i < 0)
8708 return -1;
8709
8710 rs->buf[0] = '\0';
8711 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8712 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8713 return -1;
8714
8715 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8716 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8717
8718 /* 'm' means there is (or at least might be) more data after this
8719 batch. That does not make sense unless there's at least one byte
8720 of data in this reply. */
8721 if (rs->buf[0] == 'm' && packet_len == 1)
8722 error (_("Remote qXfer reply contained no data."));
8723
8724 /* Got some data. */
8725 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8726 packet_len - 1, readbuf, n);
8727
8728 /* 'l' is an EOF marker, possibly including a final block of data,
8729 or possibly empty. If we have the final block of a non-empty
8730 object, record this fact to bypass a subsequent partial read. */
8731 if (rs->buf[0] == 'l' && offset + i > 0)
8732 {
8733 rs->finished_object = xstrdup (object_name);
8734 rs->finished_annex = xstrdup (annex ? annex : "");
8735 rs->finished_offset = offset + i;
8736 }
8737
8738 return i;
8739 }
8740
8741 static LONGEST
8742 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8743 const char *annex, gdb_byte *readbuf,
8744 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
8745 {
8746 struct remote_state *rs;
8747 int i;
8748 char *p2;
8749 char query_type;
8750
8751 set_remote_traceframe ();
8752 set_general_thread (inferior_ptid);
8753
8754 rs = get_remote_state ();
8755
8756 /* Handle memory using the standard memory routines. */
8757 if (object == TARGET_OBJECT_MEMORY)
8758 {
8759 LONGEST xfered;
8760
8761 /* If the remote target is connected but not running, we should
8762 pass this request down to a lower stratum (e.g. the executable
8763 file). */
8764 if (!target_has_execution)
8765 return 0;
8766
8767 if (writebuf != NULL)
8768 xfered = remote_write_bytes (offset, writebuf, len);
8769 else
8770 xfered = remote_read_bytes (offset, readbuf, len);
8771
8772 return xfered;
8773 }
8774
8775 /* Handle SPU memory using qxfer packets. */
8776 if (object == TARGET_OBJECT_SPU)
8777 {
8778 if (readbuf)
8779 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8780 &remote_protocol_packets
8781 [PACKET_qXfer_spu_read]);
8782 else
8783 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8784 &remote_protocol_packets
8785 [PACKET_qXfer_spu_write]);
8786 }
8787
8788 /* Handle extra signal info using qxfer packets. */
8789 if (object == TARGET_OBJECT_SIGNAL_INFO)
8790 {
8791 if (readbuf)
8792 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8793 &remote_protocol_packets
8794 [PACKET_qXfer_siginfo_read]);
8795 else
8796 return remote_write_qxfer (ops, "siginfo", annex,
8797 writebuf, offset, len,
8798 &remote_protocol_packets
8799 [PACKET_qXfer_siginfo_write]);
8800 }
8801
8802 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8803 {
8804 if (readbuf)
8805 return remote_read_qxfer (ops, "statictrace", annex,
8806 readbuf, offset, len,
8807 &remote_protocol_packets
8808 [PACKET_qXfer_statictrace_read]);
8809 else
8810 return -1;
8811 }
8812
8813 /* Only handle flash writes. */
8814 if (writebuf != NULL)
8815 {
8816 LONGEST xfered;
8817
8818 switch (object)
8819 {
8820 case TARGET_OBJECT_FLASH:
8821 return remote_flash_write (ops, offset, len, writebuf);
8822
8823 default:
8824 return -1;
8825 }
8826 }
8827
8828 /* Map pre-existing objects onto letters. DO NOT do this for new
8829 objects!!! Instead specify new query packets. */
8830 switch (object)
8831 {
8832 case TARGET_OBJECT_AVR:
8833 query_type = 'R';
8834 break;
8835
8836 case TARGET_OBJECT_AUXV:
8837 gdb_assert (annex == NULL);
8838 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8839 &remote_protocol_packets[PACKET_qXfer_auxv]);
8840
8841 case TARGET_OBJECT_AVAILABLE_FEATURES:
8842 return remote_read_qxfer
8843 (ops, "features", annex, readbuf, offset, len,
8844 &remote_protocol_packets[PACKET_qXfer_features]);
8845
8846 case TARGET_OBJECT_LIBRARIES:
8847 return remote_read_qxfer
8848 (ops, "libraries", annex, readbuf, offset, len,
8849 &remote_protocol_packets[PACKET_qXfer_libraries]);
8850
8851 case TARGET_OBJECT_LIBRARIES_SVR4:
8852 return remote_read_qxfer
8853 (ops, "libraries-svr4", annex, readbuf, offset, len,
8854 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8855
8856 case TARGET_OBJECT_MEMORY_MAP:
8857 gdb_assert (annex == NULL);
8858 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8859 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8860
8861 case TARGET_OBJECT_OSDATA:
8862 /* Should only get here if we're connected. */
8863 gdb_assert (rs->remote_desc);
8864 return remote_read_qxfer
8865 (ops, "osdata", annex, readbuf, offset, len,
8866 &remote_protocol_packets[PACKET_qXfer_osdata]);
8867
8868 case TARGET_OBJECT_THREADS:
8869 gdb_assert (annex == NULL);
8870 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8871 &remote_protocol_packets[PACKET_qXfer_threads]);
8872
8873 case TARGET_OBJECT_TRACEFRAME_INFO:
8874 gdb_assert (annex == NULL);
8875 return remote_read_qxfer
8876 (ops, "traceframe-info", annex, readbuf, offset, len,
8877 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8878
8879 case TARGET_OBJECT_FDPIC:
8880 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8881 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8882
8883 case TARGET_OBJECT_OPENVMS_UIB:
8884 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
8885 &remote_protocol_packets[PACKET_qXfer_uib]);
8886
8887 case TARGET_OBJECT_BTRACE:
8888 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
8889 &remote_protocol_packets[PACKET_qXfer_btrace]);
8890
8891 default:
8892 return -1;
8893 }
8894
8895 /* Note: a zero OFFSET and LEN can be used to query the minimum
8896 buffer size. */
8897 if (offset == 0 && len == 0)
8898 return (get_remote_packet_size ());
8899 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8900 large enough let the caller deal with it. */
8901 if (len < get_remote_packet_size ())
8902 return -1;
8903 len = get_remote_packet_size ();
8904
8905 /* Except for querying the minimum buffer size, target must be open. */
8906 if (!rs->remote_desc)
8907 error (_("remote query is only available after target open"));
8908
8909 gdb_assert (annex != NULL);
8910 gdb_assert (readbuf != NULL);
8911
8912 p2 = rs->buf;
8913 *p2++ = 'q';
8914 *p2++ = query_type;
8915
8916 /* We used one buffer char for the remote protocol q command and
8917 another for the query type. As the remote protocol encapsulation
8918 uses 4 chars plus one extra in case we are debugging
8919 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8920 string. */
8921 i = 0;
8922 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8923 {
8924 /* Bad caller may have sent forbidden characters. */
8925 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8926 *p2++ = annex[i];
8927 i++;
8928 }
8929 *p2 = '\0';
8930 gdb_assert (annex[i] == '\0');
8931
8932 i = putpkt (rs->buf);
8933 if (i < 0)
8934 return i;
8935
8936 getpkt (&rs->buf, &rs->buf_size, 0);
8937 strcpy ((char *) readbuf, rs->buf);
8938
8939 return strlen ((char *) readbuf);
8940 }
8941
8942 static int
8943 remote_search_memory (struct target_ops* ops,
8944 CORE_ADDR start_addr, ULONGEST search_space_len,
8945 const gdb_byte *pattern, ULONGEST pattern_len,
8946 CORE_ADDR *found_addrp)
8947 {
8948 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8949 struct remote_state *rs = get_remote_state ();
8950 int max_size = get_memory_write_packet_size ();
8951 struct packet_config *packet =
8952 &remote_protocol_packets[PACKET_qSearch_memory];
8953 /* Number of packet bytes used to encode the pattern;
8954 this could be more than PATTERN_LEN due to escape characters. */
8955 int escaped_pattern_len;
8956 /* Amount of pattern that was encodable in the packet. */
8957 int used_pattern_len;
8958 int i;
8959 int found;
8960 ULONGEST found_addr;
8961
8962 /* Don't go to the target if we don't have to.
8963 This is done before checking packet->support to avoid the possibility that
8964 a success for this edge case means the facility works in general. */
8965 if (pattern_len > search_space_len)
8966 return 0;
8967 if (pattern_len == 0)
8968 {
8969 *found_addrp = start_addr;
8970 return 1;
8971 }
8972
8973 /* If we already know the packet isn't supported, fall back to the simple
8974 way of searching memory. */
8975
8976 if (packet->support == PACKET_DISABLE)
8977 {
8978 /* Target doesn't provided special support, fall back and use the
8979 standard support (copy memory and do the search here). */
8980 return simple_search_memory (ops, start_addr, search_space_len,
8981 pattern, pattern_len, found_addrp);
8982 }
8983
8984 /* Make sure the remote is pointing at the right process. */
8985 set_general_process ();
8986
8987 /* Insert header. */
8988 i = snprintf (rs->buf, max_size,
8989 "qSearch:memory:%s;%s;",
8990 phex_nz (start_addr, addr_size),
8991 phex_nz (search_space_len, sizeof (search_space_len)));
8992 max_size -= (i + 1);
8993
8994 /* Escape as much data as fits into rs->buf. */
8995 escaped_pattern_len =
8996 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
8997 &used_pattern_len, max_size);
8998
8999 /* Bail if the pattern is too large. */
9000 if (used_pattern_len != pattern_len)
9001 error (_("Pattern is too large to transmit to remote target."));
9002
9003 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9004 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9005 || packet_ok (rs->buf, packet) != PACKET_OK)
9006 {
9007 /* The request may not have worked because the command is not
9008 supported. If so, fall back to the simple way. */
9009 if (packet->support == PACKET_DISABLE)
9010 {
9011 return simple_search_memory (ops, start_addr, search_space_len,
9012 pattern, pattern_len, found_addrp);
9013 }
9014 return -1;
9015 }
9016
9017 if (rs->buf[0] == '0')
9018 found = 0;
9019 else if (rs->buf[0] == '1')
9020 {
9021 found = 1;
9022 if (rs->buf[1] != ',')
9023 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9024 unpack_varlen_hex (rs->buf + 2, &found_addr);
9025 *found_addrp = found_addr;
9026 }
9027 else
9028 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9029
9030 return found;
9031 }
9032
9033 static void
9034 remote_rcmd (char *command,
9035 struct ui_file *outbuf)
9036 {
9037 struct remote_state *rs = get_remote_state ();
9038 char *p = rs->buf;
9039
9040 if (!rs->remote_desc)
9041 error (_("remote rcmd is only available after target open"));
9042
9043 /* Send a NULL command across as an empty command. */
9044 if (command == NULL)
9045 command = "";
9046
9047 /* The query prefix. */
9048 strcpy (rs->buf, "qRcmd,");
9049 p = strchr (rs->buf, '\0');
9050
9051 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9052 > get_remote_packet_size ())
9053 error (_("\"monitor\" command ``%s'' is too long."), command);
9054
9055 /* Encode the actual command. */
9056 bin2hex ((gdb_byte *) command, p, 0);
9057
9058 if (putpkt (rs->buf) < 0)
9059 error (_("Communication problem with target."));
9060
9061 /* get/display the response */
9062 while (1)
9063 {
9064 char *buf;
9065
9066 /* XXX - see also remote_get_noisy_reply(). */
9067 QUIT; /* Allow user to bail out with ^C. */
9068 rs->buf[0] = '\0';
9069 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9070 {
9071 /* Timeout. Continue to (try to) read responses.
9072 This is better than stopping with an error, assuming the stub
9073 is still executing the (long) monitor command.
9074 If needed, the user can interrupt gdb using C-c, obtaining
9075 an effect similar to stop on timeout. */
9076 continue;
9077 }
9078 buf = rs->buf;
9079 if (buf[0] == '\0')
9080 error (_("Target does not support this command."));
9081 if (buf[0] == 'O' && buf[1] != 'K')
9082 {
9083 remote_console_output (buf + 1); /* 'O' message from stub. */
9084 continue;
9085 }
9086 if (strcmp (buf, "OK") == 0)
9087 break;
9088 if (strlen (buf) == 3 && buf[0] == 'E'
9089 && isdigit (buf[1]) && isdigit (buf[2]))
9090 {
9091 error (_("Protocol error with Rcmd"));
9092 }
9093 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9094 {
9095 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9096
9097 fputc_unfiltered (c, outbuf);
9098 }
9099 break;
9100 }
9101 }
9102
9103 static VEC(mem_region_s) *
9104 remote_memory_map (struct target_ops *ops)
9105 {
9106 VEC(mem_region_s) *result = NULL;
9107 char *text = target_read_stralloc (&current_target,
9108 TARGET_OBJECT_MEMORY_MAP, NULL);
9109
9110 if (text)
9111 {
9112 struct cleanup *back_to = make_cleanup (xfree, text);
9113
9114 result = parse_memory_map (text);
9115 do_cleanups (back_to);
9116 }
9117
9118 return result;
9119 }
9120
9121 static void
9122 packet_command (char *args, int from_tty)
9123 {
9124 struct remote_state *rs = get_remote_state ();
9125
9126 if (!rs->remote_desc)
9127 error (_("command can only be used with remote target"));
9128
9129 if (!args)
9130 error (_("remote-packet command requires packet text as argument"));
9131
9132 puts_filtered ("sending: ");
9133 print_packet (args);
9134 puts_filtered ("\n");
9135 putpkt (args);
9136
9137 getpkt (&rs->buf, &rs->buf_size, 0);
9138 puts_filtered ("received: ");
9139 print_packet (rs->buf);
9140 puts_filtered ("\n");
9141 }
9142
9143 #if 0
9144 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9145
9146 static void display_thread_info (struct gdb_ext_thread_info *info);
9147
9148 static void threadset_test_cmd (char *cmd, int tty);
9149
9150 static void threadalive_test (char *cmd, int tty);
9151
9152 static void threadlist_test_cmd (char *cmd, int tty);
9153
9154 int get_and_display_threadinfo (threadref *ref);
9155
9156 static void threadinfo_test_cmd (char *cmd, int tty);
9157
9158 static int thread_display_step (threadref *ref, void *context);
9159
9160 static void threadlist_update_test_cmd (char *cmd, int tty);
9161
9162 static void init_remote_threadtests (void);
9163
9164 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9165
9166 static void
9167 threadset_test_cmd (char *cmd, int tty)
9168 {
9169 int sample_thread = SAMPLE_THREAD;
9170
9171 printf_filtered (_("Remote threadset test\n"));
9172 set_general_thread (sample_thread);
9173 }
9174
9175
9176 static void
9177 threadalive_test (char *cmd, int tty)
9178 {
9179 int sample_thread = SAMPLE_THREAD;
9180 int pid = ptid_get_pid (inferior_ptid);
9181 ptid_t ptid = ptid_build (pid, 0, sample_thread);
9182
9183 if (remote_thread_alive (ptid))
9184 printf_filtered ("PASS: Thread alive test\n");
9185 else
9186 printf_filtered ("FAIL: Thread alive test\n");
9187 }
9188
9189 void output_threadid (char *title, threadref *ref);
9190
9191 void
9192 output_threadid (char *title, threadref *ref)
9193 {
9194 char hexid[20];
9195
9196 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9197 hexid[16] = 0;
9198 printf_filtered ("%s %s\n", title, (&hexid[0]));
9199 }
9200
9201 static void
9202 threadlist_test_cmd (char *cmd, int tty)
9203 {
9204 int startflag = 1;
9205 threadref nextthread;
9206 int done, result_count;
9207 threadref threadlist[3];
9208
9209 printf_filtered ("Remote Threadlist test\n");
9210 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9211 &result_count, &threadlist[0]))
9212 printf_filtered ("FAIL: threadlist test\n");
9213 else
9214 {
9215 threadref *scan = threadlist;
9216 threadref *limit = scan + result_count;
9217
9218 while (scan < limit)
9219 output_threadid (" thread ", scan++);
9220 }
9221 }
9222
9223 void
9224 display_thread_info (struct gdb_ext_thread_info *info)
9225 {
9226 output_threadid ("Threadid: ", &info->threadid);
9227 printf_filtered ("Name: %s\n ", info->shortname);
9228 printf_filtered ("State: %s\n", info->display);
9229 printf_filtered ("other: %s\n\n", info->more_display);
9230 }
9231
9232 int
9233 get_and_display_threadinfo (threadref *ref)
9234 {
9235 int result;
9236 int set;
9237 struct gdb_ext_thread_info threadinfo;
9238
9239 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9240 | TAG_MOREDISPLAY | TAG_DISPLAY;
9241 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9242 display_thread_info (&threadinfo);
9243 return result;
9244 }
9245
9246 static void
9247 threadinfo_test_cmd (char *cmd, int tty)
9248 {
9249 int athread = SAMPLE_THREAD;
9250 threadref thread;
9251 int set;
9252
9253 int_to_threadref (&thread, athread);
9254 printf_filtered ("Remote Threadinfo test\n");
9255 if (!get_and_display_threadinfo (&thread))
9256 printf_filtered ("FAIL cannot get thread info\n");
9257 }
9258
9259 static int
9260 thread_display_step (threadref *ref, void *context)
9261 {
9262 /* output_threadid(" threadstep ",ref); *//* simple test */
9263 return get_and_display_threadinfo (ref);
9264 }
9265
9266 static void
9267 threadlist_update_test_cmd (char *cmd, int tty)
9268 {
9269 printf_filtered ("Remote Threadlist update test\n");
9270 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9271 }
9272
9273 static void
9274 init_remote_threadtests (void)
9275 {
9276 add_com ("tlist", class_obscure, threadlist_test_cmd,
9277 _("Fetch and print the remote list of "
9278 "thread identifiers, one pkt only"));
9279 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9280 _("Fetch and display info about one thread"));
9281 add_com ("tset", class_obscure, threadset_test_cmd,
9282 _("Test setting to a different thread"));
9283 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9284 _("Iterate through updating all remote thread info"));
9285 add_com ("talive", class_obscure, threadalive_test,
9286 _(" Remote thread alive test "));
9287 }
9288
9289 #endif /* 0 */
9290
9291 /* Convert a thread ID to a string. Returns the string in a static
9292 buffer. */
9293
9294 static char *
9295 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9296 {
9297 static char buf[64];
9298 struct remote_state *rs = get_remote_state ();
9299
9300 if (ptid_equal (ptid, null_ptid))
9301 return normal_pid_to_str (ptid);
9302 else if (ptid_is_pid (ptid))
9303 {
9304 /* Printing an inferior target id. */
9305
9306 /* When multi-process extensions are off, there's no way in the
9307 remote protocol to know the remote process id, if there's any
9308 at all. There's one exception --- when we're connected with
9309 target extended-remote, and we manually attached to a process
9310 with "attach PID". We don't record anywhere a flag that
9311 allows us to distinguish that case from the case of
9312 connecting with extended-remote and the stub already being
9313 attached to a process, and reporting yes to qAttached, hence
9314 no smart special casing here. */
9315 if (!remote_multi_process_p (rs))
9316 {
9317 xsnprintf (buf, sizeof buf, "Remote target");
9318 return buf;
9319 }
9320
9321 return normal_pid_to_str (ptid);
9322 }
9323 else
9324 {
9325 if (ptid_equal (magic_null_ptid, ptid))
9326 xsnprintf (buf, sizeof buf, "Thread <main>");
9327 else if (rs->extended && remote_multi_process_p (rs))
9328 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9329 ptid_get_pid (ptid), ptid_get_tid (ptid));
9330 else
9331 xsnprintf (buf, sizeof buf, "Thread %ld",
9332 ptid_get_tid (ptid));
9333 return buf;
9334 }
9335 }
9336
9337 /* Get the address of the thread local variable in OBJFILE which is
9338 stored at OFFSET within the thread local storage for thread PTID. */
9339
9340 static CORE_ADDR
9341 remote_get_thread_local_address (struct target_ops *ops,
9342 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9343 {
9344 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
9345 {
9346 struct remote_state *rs = get_remote_state ();
9347 char *p = rs->buf;
9348 char *endp = rs->buf + get_remote_packet_size ();
9349 enum packet_result result;
9350
9351 strcpy (p, "qGetTLSAddr:");
9352 p += strlen (p);
9353 p = write_ptid (p, endp, ptid);
9354 *p++ = ',';
9355 p += hexnumstr (p, offset);
9356 *p++ = ',';
9357 p += hexnumstr (p, lm);
9358 *p++ = '\0';
9359
9360 putpkt (rs->buf);
9361 getpkt (&rs->buf, &rs->buf_size, 0);
9362 result = packet_ok (rs->buf,
9363 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9364 if (result == PACKET_OK)
9365 {
9366 ULONGEST result;
9367
9368 unpack_varlen_hex (rs->buf, &result);
9369 return result;
9370 }
9371 else if (result == PACKET_UNKNOWN)
9372 throw_error (TLS_GENERIC_ERROR,
9373 _("Remote target doesn't support qGetTLSAddr packet"));
9374 else
9375 throw_error (TLS_GENERIC_ERROR,
9376 _("Remote target failed to process qGetTLSAddr request"));
9377 }
9378 else
9379 throw_error (TLS_GENERIC_ERROR,
9380 _("TLS not supported or disabled on this target"));
9381 /* Not reached. */
9382 return 0;
9383 }
9384
9385 /* Provide thread local base, i.e. Thread Information Block address.
9386 Returns 1 if ptid is found and thread_local_base is non zero. */
9387
9388 static int
9389 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
9390 {
9391 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9392 {
9393 struct remote_state *rs = get_remote_state ();
9394 char *p = rs->buf;
9395 char *endp = rs->buf + get_remote_packet_size ();
9396 enum packet_result result;
9397
9398 strcpy (p, "qGetTIBAddr:");
9399 p += strlen (p);
9400 p = write_ptid (p, endp, ptid);
9401 *p++ = '\0';
9402
9403 putpkt (rs->buf);
9404 getpkt (&rs->buf, &rs->buf_size, 0);
9405 result = packet_ok (rs->buf,
9406 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9407 if (result == PACKET_OK)
9408 {
9409 ULONGEST result;
9410
9411 unpack_varlen_hex (rs->buf, &result);
9412 if (addr)
9413 *addr = (CORE_ADDR) result;
9414 return 1;
9415 }
9416 else if (result == PACKET_UNKNOWN)
9417 error (_("Remote target doesn't support qGetTIBAddr packet"));
9418 else
9419 error (_("Remote target failed to process qGetTIBAddr request"));
9420 }
9421 else
9422 error (_("qGetTIBAddr not supported or disabled on this target"));
9423 /* Not reached. */
9424 return 0;
9425 }
9426
9427 /* Support for inferring a target description based on the current
9428 architecture and the size of a 'g' packet. While the 'g' packet
9429 can have any size (since optional registers can be left off the
9430 end), some sizes are easily recognizable given knowledge of the
9431 approximate architecture. */
9432
9433 struct remote_g_packet_guess
9434 {
9435 int bytes;
9436 const struct target_desc *tdesc;
9437 };
9438 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9439 DEF_VEC_O(remote_g_packet_guess_s);
9440
9441 struct remote_g_packet_data
9442 {
9443 VEC(remote_g_packet_guess_s) *guesses;
9444 };
9445
9446 static struct gdbarch_data *remote_g_packet_data_handle;
9447
9448 static void *
9449 remote_g_packet_data_init (struct obstack *obstack)
9450 {
9451 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9452 }
9453
9454 void
9455 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9456 const struct target_desc *tdesc)
9457 {
9458 struct remote_g_packet_data *data
9459 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9460 struct remote_g_packet_guess new_guess, *guess;
9461 int ix;
9462
9463 gdb_assert (tdesc != NULL);
9464
9465 for (ix = 0;
9466 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9467 ix++)
9468 if (guess->bytes == bytes)
9469 internal_error (__FILE__, __LINE__,
9470 _("Duplicate g packet description added for size %d"),
9471 bytes);
9472
9473 new_guess.bytes = bytes;
9474 new_guess.tdesc = tdesc;
9475 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9476 }
9477
9478 /* Return 1 if remote_read_description would do anything on this target
9479 and architecture, 0 otherwise. */
9480
9481 static int
9482 remote_read_description_p (struct target_ops *target)
9483 {
9484 struct remote_g_packet_data *data
9485 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9486
9487 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9488 return 1;
9489
9490 return 0;
9491 }
9492
9493 static const struct target_desc *
9494 remote_read_description (struct target_ops *target)
9495 {
9496 struct remote_g_packet_data *data
9497 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9498
9499 /* Do not try this during initial connection, when we do not know
9500 whether there is a running but stopped thread. */
9501 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9502 return NULL;
9503
9504 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9505 {
9506 struct remote_g_packet_guess *guess;
9507 int ix;
9508 int bytes = send_g_packet ();
9509
9510 for (ix = 0;
9511 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9512 ix++)
9513 if (guess->bytes == bytes)
9514 return guess->tdesc;
9515
9516 /* We discard the g packet. A minor optimization would be to
9517 hold on to it, and fill the register cache once we have selected
9518 an architecture, but it's too tricky to do safely. */
9519 }
9520
9521 return NULL;
9522 }
9523
9524 /* Remote file transfer support. This is host-initiated I/O, not
9525 target-initiated; for target-initiated, see remote-fileio.c. */
9526
9527 /* If *LEFT is at least the length of STRING, copy STRING to
9528 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9529 decrease *LEFT. Otherwise raise an error. */
9530
9531 static void
9532 remote_buffer_add_string (char **buffer, int *left, char *string)
9533 {
9534 int len = strlen (string);
9535
9536 if (len > *left)
9537 error (_("Packet too long for target."));
9538
9539 memcpy (*buffer, string, len);
9540 *buffer += len;
9541 *left -= len;
9542
9543 /* NUL-terminate the buffer as a convenience, if there is
9544 room. */
9545 if (*left)
9546 **buffer = '\0';
9547 }
9548
9549 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9550 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9551 decrease *LEFT. Otherwise raise an error. */
9552
9553 static void
9554 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9555 int len)
9556 {
9557 if (2 * len > *left)
9558 error (_("Packet too long for target."));
9559
9560 bin2hex (bytes, *buffer, len);
9561 *buffer += 2 * len;
9562 *left -= 2 * len;
9563
9564 /* NUL-terminate the buffer as a convenience, if there is
9565 room. */
9566 if (*left)
9567 **buffer = '\0';
9568 }
9569
9570 /* If *LEFT is large enough, convert VALUE to hex and add it to
9571 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9572 decrease *LEFT. Otherwise raise an error. */
9573
9574 static void
9575 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9576 {
9577 int len = hexnumlen (value);
9578
9579 if (len > *left)
9580 error (_("Packet too long for target."));
9581
9582 hexnumstr (*buffer, value);
9583 *buffer += len;
9584 *left -= len;
9585
9586 /* NUL-terminate the buffer as a convenience, if there is
9587 room. */
9588 if (*left)
9589 **buffer = '\0';
9590 }
9591
9592 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9593 value, *REMOTE_ERRNO to the remote error number or zero if none
9594 was included, and *ATTACHMENT to point to the start of the annex
9595 if any. The length of the packet isn't needed here; there may
9596 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9597
9598 Return 0 if the packet could be parsed, -1 if it could not. If
9599 -1 is returned, the other variables may not be initialized. */
9600
9601 static int
9602 remote_hostio_parse_result (char *buffer, int *retcode,
9603 int *remote_errno, char **attachment)
9604 {
9605 char *p, *p2;
9606
9607 *remote_errno = 0;
9608 *attachment = NULL;
9609
9610 if (buffer[0] != 'F')
9611 return -1;
9612
9613 errno = 0;
9614 *retcode = strtol (&buffer[1], &p, 16);
9615 if (errno != 0 || p == &buffer[1])
9616 return -1;
9617
9618 /* Check for ",errno". */
9619 if (*p == ',')
9620 {
9621 errno = 0;
9622 *remote_errno = strtol (p + 1, &p2, 16);
9623 if (errno != 0 || p + 1 == p2)
9624 return -1;
9625 p = p2;
9626 }
9627
9628 /* Check for ";attachment". If there is no attachment, the
9629 packet should end here. */
9630 if (*p == ';')
9631 {
9632 *attachment = p + 1;
9633 return 0;
9634 }
9635 else if (*p == '\0')
9636 return 0;
9637 else
9638 return -1;
9639 }
9640
9641 /* Send a prepared I/O packet to the target and read its response.
9642 The prepared packet is in the global RS->BUF before this function
9643 is called, and the answer is there when we return.
9644
9645 COMMAND_BYTES is the length of the request to send, which may include
9646 binary data. WHICH_PACKET is the packet configuration to check
9647 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9648 is set to the error number and -1 is returned. Otherwise the value
9649 returned by the function is returned.
9650
9651 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9652 attachment is expected; an error will be reported if there's a
9653 mismatch. If one is found, *ATTACHMENT will be set to point into
9654 the packet buffer and *ATTACHMENT_LEN will be set to the
9655 attachment's length. */
9656
9657 static int
9658 remote_hostio_send_command (int command_bytes, int which_packet,
9659 int *remote_errno, char **attachment,
9660 int *attachment_len)
9661 {
9662 struct remote_state *rs = get_remote_state ();
9663 int ret, bytes_read;
9664 char *attachment_tmp;
9665
9666 if (!rs->remote_desc
9667 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
9668 {
9669 *remote_errno = FILEIO_ENOSYS;
9670 return -1;
9671 }
9672
9673 putpkt_binary (rs->buf, command_bytes);
9674 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9675
9676 /* If it timed out, something is wrong. Don't try to parse the
9677 buffer. */
9678 if (bytes_read < 0)
9679 {
9680 *remote_errno = FILEIO_EINVAL;
9681 return -1;
9682 }
9683
9684 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9685 {
9686 case PACKET_ERROR:
9687 *remote_errno = FILEIO_EINVAL;
9688 return -1;
9689 case PACKET_UNKNOWN:
9690 *remote_errno = FILEIO_ENOSYS;
9691 return -1;
9692 case PACKET_OK:
9693 break;
9694 }
9695
9696 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9697 &attachment_tmp))
9698 {
9699 *remote_errno = FILEIO_EINVAL;
9700 return -1;
9701 }
9702
9703 /* Make sure we saw an attachment if and only if we expected one. */
9704 if ((attachment_tmp == NULL && attachment != NULL)
9705 || (attachment_tmp != NULL && attachment == NULL))
9706 {
9707 *remote_errno = FILEIO_EINVAL;
9708 return -1;
9709 }
9710
9711 /* If an attachment was found, it must point into the packet buffer;
9712 work out how many bytes there were. */
9713 if (attachment_tmp != NULL)
9714 {
9715 *attachment = attachment_tmp;
9716 *attachment_len = bytes_read - (*attachment - rs->buf);
9717 }
9718
9719 return ret;
9720 }
9721
9722 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9723 remote file descriptor, or -1 if an error occurs (and set
9724 *REMOTE_ERRNO). */
9725
9726 static int
9727 remote_hostio_open (const char *filename, int flags, int mode,
9728 int *remote_errno)
9729 {
9730 struct remote_state *rs = get_remote_state ();
9731 char *p = rs->buf;
9732 int left = get_remote_packet_size () - 1;
9733
9734 remote_buffer_add_string (&p, &left, "vFile:open:");
9735
9736 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9737 strlen (filename));
9738 remote_buffer_add_string (&p, &left, ",");
9739
9740 remote_buffer_add_int (&p, &left, flags);
9741 remote_buffer_add_string (&p, &left, ",");
9742
9743 remote_buffer_add_int (&p, &left, mode);
9744
9745 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9746 remote_errno, NULL, NULL);
9747 }
9748
9749 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9750 Return the number of bytes written, or -1 if an error occurs (and
9751 set *REMOTE_ERRNO). */
9752
9753 static int
9754 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9755 ULONGEST offset, int *remote_errno)
9756 {
9757 struct remote_state *rs = get_remote_state ();
9758 char *p = rs->buf;
9759 int left = get_remote_packet_size ();
9760 int out_len;
9761
9762 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9763
9764 remote_buffer_add_int (&p, &left, fd);
9765 remote_buffer_add_string (&p, &left, ",");
9766
9767 remote_buffer_add_int (&p, &left, offset);
9768 remote_buffer_add_string (&p, &left, ",");
9769
9770 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9771 get_remote_packet_size () - (p - rs->buf));
9772
9773 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9774 remote_errno, NULL, NULL);
9775 }
9776
9777 /* Read up to LEN bytes FD on the remote target into READ_BUF
9778 Return the number of bytes read, or -1 if an error occurs (and
9779 set *REMOTE_ERRNO). */
9780
9781 static int
9782 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9783 ULONGEST offset, int *remote_errno)
9784 {
9785 struct remote_state *rs = get_remote_state ();
9786 char *p = rs->buf;
9787 char *attachment;
9788 int left = get_remote_packet_size ();
9789 int ret, attachment_len;
9790 int read_len;
9791
9792 remote_buffer_add_string (&p, &left, "vFile:pread:");
9793
9794 remote_buffer_add_int (&p, &left, fd);
9795 remote_buffer_add_string (&p, &left, ",");
9796
9797 remote_buffer_add_int (&p, &left, len);
9798 remote_buffer_add_string (&p, &left, ",");
9799
9800 remote_buffer_add_int (&p, &left, offset);
9801
9802 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9803 remote_errno, &attachment,
9804 &attachment_len);
9805
9806 if (ret < 0)
9807 return ret;
9808
9809 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9810 read_buf, len);
9811 if (read_len != ret)
9812 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9813
9814 return ret;
9815 }
9816
9817 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9818 (and set *REMOTE_ERRNO). */
9819
9820 static int
9821 remote_hostio_close (int fd, int *remote_errno)
9822 {
9823 struct remote_state *rs = get_remote_state ();
9824 char *p = rs->buf;
9825 int left = get_remote_packet_size () - 1;
9826
9827 remote_buffer_add_string (&p, &left, "vFile:close:");
9828
9829 remote_buffer_add_int (&p, &left, fd);
9830
9831 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9832 remote_errno, NULL, NULL);
9833 }
9834
9835 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9836 occurs (and set *REMOTE_ERRNO). */
9837
9838 static int
9839 remote_hostio_unlink (const char *filename, int *remote_errno)
9840 {
9841 struct remote_state *rs = get_remote_state ();
9842 char *p = rs->buf;
9843 int left = get_remote_packet_size () - 1;
9844
9845 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9846
9847 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9848 strlen (filename));
9849
9850 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9851 remote_errno, NULL, NULL);
9852 }
9853
9854 /* Read value of symbolic link FILENAME on the remote target. Return
9855 a null-terminated string allocated via xmalloc, or NULL if an error
9856 occurs (and set *REMOTE_ERRNO). */
9857
9858 static char *
9859 remote_hostio_readlink (const char *filename, int *remote_errno)
9860 {
9861 struct remote_state *rs = get_remote_state ();
9862 char *p = rs->buf;
9863 char *attachment;
9864 int left = get_remote_packet_size ();
9865 int len, attachment_len;
9866 int read_len;
9867 char *ret;
9868
9869 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9870
9871 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9872 strlen (filename));
9873
9874 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9875 remote_errno, &attachment,
9876 &attachment_len);
9877
9878 if (len < 0)
9879 return NULL;
9880
9881 ret = xmalloc (len + 1);
9882
9883 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9884 (gdb_byte *) ret, len);
9885 if (read_len != len)
9886 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9887
9888 ret[len] = '\0';
9889 return ret;
9890 }
9891
9892 static int
9893 remote_fileio_errno_to_host (int errnum)
9894 {
9895 switch (errnum)
9896 {
9897 case FILEIO_EPERM:
9898 return EPERM;
9899 case FILEIO_ENOENT:
9900 return ENOENT;
9901 case FILEIO_EINTR:
9902 return EINTR;
9903 case FILEIO_EIO:
9904 return EIO;
9905 case FILEIO_EBADF:
9906 return EBADF;
9907 case FILEIO_EACCES:
9908 return EACCES;
9909 case FILEIO_EFAULT:
9910 return EFAULT;
9911 case FILEIO_EBUSY:
9912 return EBUSY;
9913 case FILEIO_EEXIST:
9914 return EEXIST;
9915 case FILEIO_ENODEV:
9916 return ENODEV;
9917 case FILEIO_ENOTDIR:
9918 return ENOTDIR;
9919 case FILEIO_EISDIR:
9920 return EISDIR;
9921 case FILEIO_EINVAL:
9922 return EINVAL;
9923 case FILEIO_ENFILE:
9924 return ENFILE;
9925 case FILEIO_EMFILE:
9926 return EMFILE;
9927 case FILEIO_EFBIG:
9928 return EFBIG;
9929 case FILEIO_ENOSPC:
9930 return ENOSPC;
9931 case FILEIO_ESPIPE:
9932 return ESPIPE;
9933 case FILEIO_EROFS:
9934 return EROFS;
9935 case FILEIO_ENOSYS:
9936 return ENOSYS;
9937 case FILEIO_ENAMETOOLONG:
9938 return ENAMETOOLONG;
9939 }
9940 return -1;
9941 }
9942
9943 static char *
9944 remote_hostio_error (int errnum)
9945 {
9946 int host_error = remote_fileio_errno_to_host (errnum);
9947
9948 if (host_error == -1)
9949 error (_("Unknown remote I/O error %d"), errnum);
9950 else
9951 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9952 }
9953
9954 static void
9955 remote_hostio_close_cleanup (void *opaque)
9956 {
9957 int fd = *(int *) opaque;
9958 int remote_errno;
9959
9960 remote_hostio_close (fd, &remote_errno);
9961 }
9962
9963
9964 static void *
9965 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9966 {
9967 const char *filename = bfd_get_filename (abfd);
9968 int fd, remote_errno;
9969 int *stream;
9970
9971 gdb_assert (remote_filename_p (filename));
9972
9973 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
9974 if (fd == -1)
9975 {
9976 errno = remote_fileio_errno_to_host (remote_errno);
9977 bfd_set_error (bfd_error_system_call);
9978 return NULL;
9979 }
9980
9981 stream = xmalloc (sizeof (int));
9982 *stream = fd;
9983 return stream;
9984 }
9985
9986 static int
9987 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9988 {
9989 int fd = *(int *)stream;
9990 int remote_errno;
9991
9992 xfree (stream);
9993
9994 /* Ignore errors on close; these may happen if the remote
9995 connection was already torn down. */
9996 remote_hostio_close (fd, &remote_errno);
9997
9998 /* Zero means success. */
9999 return 0;
10000 }
10001
10002 static file_ptr
10003 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10004 file_ptr nbytes, file_ptr offset)
10005 {
10006 int fd = *(int *)stream;
10007 int remote_errno;
10008 file_ptr pos, bytes;
10009
10010 pos = 0;
10011 while (nbytes > pos)
10012 {
10013 bytes = remote_hostio_pread (fd, (gdb_byte *) buf + pos, nbytes - pos,
10014 offset + pos, &remote_errno);
10015 if (bytes == 0)
10016 /* Success, but no bytes, means end-of-file. */
10017 break;
10018 if (bytes == -1)
10019 {
10020 errno = remote_fileio_errno_to_host (remote_errno);
10021 bfd_set_error (bfd_error_system_call);
10022 return -1;
10023 }
10024
10025 pos += bytes;
10026 }
10027
10028 return pos;
10029 }
10030
10031 static int
10032 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10033 {
10034 /* FIXME: We should probably implement remote_hostio_stat. */
10035 sb->st_size = INT_MAX;
10036 return 0;
10037 }
10038
10039 int
10040 remote_filename_p (const char *filename)
10041 {
10042 return strncmp (filename,
10043 REMOTE_SYSROOT_PREFIX,
10044 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
10045 }
10046
10047 bfd *
10048 remote_bfd_open (const char *remote_file, const char *target)
10049 {
10050 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10051 remote_bfd_iovec_open, NULL,
10052 remote_bfd_iovec_pread,
10053 remote_bfd_iovec_close,
10054 remote_bfd_iovec_stat);
10055
10056 return abfd;
10057 }
10058
10059 void
10060 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10061 {
10062 struct cleanup *back_to, *close_cleanup;
10063 int retcode, fd, remote_errno, bytes, io_size;
10064 FILE *file;
10065 gdb_byte *buffer;
10066 int bytes_in_buffer;
10067 int saw_eof;
10068 ULONGEST offset;
10069 struct remote_state *rs = get_remote_state ();
10070
10071 if (!rs->remote_desc)
10072 error (_("command can only be used with remote target"));
10073
10074 file = gdb_fopen_cloexec (local_file, "rb");
10075 if (file == NULL)
10076 perror_with_name (local_file);
10077 back_to = make_cleanup_fclose (file);
10078
10079 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10080 | FILEIO_O_TRUNC),
10081 0700, &remote_errno);
10082 if (fd == -1)
10083 remote_hostio_error (remote_errno);
10084
10085 /* Send up to this many bytes at once. They won't all fit in the
10086 remote packet limit, so we'll transfer slightly fewer. */
10087 io_size = get_remote_packet_size ();
10088 buffer = xmalloc (io_size);
10089 make_cleanup (xfree, buffer);
10090
10091 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10092
10093 bytes_in_buffer = 0;
10094 saw_eof = 0;
10095 offset = 0;
10096 while (bytes_in_buffer || !saw_eof)
10097 {
10098 if (!saw_eof)
10099 {
10100 bytes = fread (buffer + bytes_in_buffer, 1,
10101 io_size - bytes_in_buffer,
10102 file);
10103 if (bytes == 0)
10104 {
10105 if (ferror (file))
10106 error (_("Error reading %s."), local_file);
10107 else
10108 {
10109 /* EOF. Unless there is something still in the
10110 buffer from the last iteration, we are done. */
10111 saw_eof = 1;
10112 if (bytes_in_buffer == 0)
10113 break;
10114 }
10115 }
10116 }
10117 else
10118 bytes = 0;
10119
10120 bytes += bytes_in_buffer;
10121 bytes_in_buffer = 0;
10122
10123 retcode = remote_hostio_pwrite (fd, buffer, bytes,
10124 offset, &remote_errno);
10125
10126 if (retcode < 0)
10127 remote_hostio_error (remote_errno);
10128 else if (retcode == 0)
10129 error (_("Remote write of %d bytes returned 0!"), bytes);
10130 else if (retcode < bytes)
10131 {
10132 /* Short write. Save the rest of the read data for the next
10133 write. */
10134 bytes_in_buffer = bytes - retcode;
10135 memmove (buffer, buffer + retcode, bytes_in_buffer);
10136 }
10137
10138 offset += retcode;
10139 }
10140
10141 discard_cleanups (close_cleanup);
10142 if (remote_hostio_close (fd, &remote_errno))
10143 remote_hostio_error (remote_errno);
10144
10145 if (from_tty)
10146 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10147 do_cleanups (back_to);
10148 }
10149
10150 void
10151 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10152 {
10153 struct cleanup *back_to, *close_cleanup;
10154 int fd, remote_errno, bytes, io_size;
10155 FILE *file;
10156 gdb_byte *buffer;
10157 ULONGEST offset;
10158 struct remote_state *rs = get_remote_state ();
10159
10160 if (!rs->remote_desc)
10161 error (_("command can only be used with remote target"));
10162
10163 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10164 if (fd == -1)
10165 remote_hostio_error (remote_errno);
10166
10167 file = gdb_fopen_cloexec (local_file, "wb");
10168 if (file == NULL)
10169 perror_with_name (local_file);
10170 back_to = make_cleanup_fclose (file);
10171
10172 /* Send up to this many bytes at once. They won't all fit in the
10173 remote packet limit, so we'll transfer slightly fewer. */
10174 io_size = get_remote_packet_size ();
10175 buffer = xmalloc (io_size);
10176 make_cleanup (xfree, buffer);
10177
10178 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10179
10180 offset = 0;
10181 while (1)
10182 {
10183 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
10184 if (bytes == 0)
10185 /* Success, but no bytes, means end-of-file. */
10186 break;
10187 if (bytes == -1)
10188 remote_hostio_error (remote_errno);
10189
10190 offset += bytes;
10191
10192 bytes = fwrite (buffer, 1, bytes, file);
10193 if (bytes == 0)
10194 perror_with_name (local_file);
10195 }
10196
10197 discard_cleanups (close_cleanup);
10198 if (remote_hostio_close (fd, &remote_errno))
10199 remote_hostio_error (remote_errno);
10200
10201 if (from_tty)
10202 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10203 do_cleanups (back_to);
10204 }
10205
10206 void
10207 remote_file_delete (const char *remote_file, int from_tty)
10208 {
10209 int retcode, remote_errno;
10210 struct remote_state *rs = get_remote_state ();
10211
10212 if (!rs->remote_desc)
10213 error (_("command can only be used with remote target"));
10214
10215 retcode = remote_hostio_unlink (remote_file, &remote_errno);
10216 if (retcode == -1)
10217 remote_hostio_error (remote_errno);
10218
10219 if (from_tty)
10220 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10221 }
10222
10223 static void
10224 remote_put_command (char *args, int from_tty)
10225 {
10226 struct cleanup *back_to;
10227 char **argv;
10228
10229 if (args == NULL)
10230 error_no_arg (_("file to put"));
10231
10232 argv = gdb_buildargv (args);
10233 back_to = make_cleanup_freeargv (argv);
10234 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10235 error (_("Invalid parameters to remote put"));
10236
10237 remote_file_put (argv[0], argv[1], from_tty);
10238
10239 do_cleanups (back_to);
10240 }
10241
10242 static void
10243 remote_get_command (char *args, int from_tty)
10244 {
10245 struct cleanup *back_to;
10246 char **argv;
10247
10248 if (args == NULL)
10249 error_no_arg (_("file to get"));
10250
10251 argv = gdb_buildargv (args);
10252 back_to = make_cleanup_freeargv (argv);
10253 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10254 error (_("Invalid parameters to remote get"));
10255
10256 remote_file_get (argv[0], argv[1], from_tty);
10257
10258 do_cleanups (back_to);
10259 }
10260
10261 static void
10262 remote_delete_command (char *args, int from_tty)
10263 {
10264 struct cleanup *back_to;
10265 char **argv;
10266
10267 if (args == NULL)
10268 error_no_arg (_("file to delete"));
10269
10270 argv = gdb_buildargv (args);
10271 back_to = make_cleanup_freeargv (argv);
10272 if (argv[0] == NULL || argv[1] != NULL)
10273 error (_("Invalid parameters to remote delete"));
10274
10275 remote_file_delete (argv[0], from_tty);
10276
10277 do_cleanups (back_to);
10278 }
10279
10280 static void
10281 remote_command (char *args, int from_tty)
10282 {
10283 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10284 }
10285
10286 static int
10287 remote_can_execute_reverse (void)
10288 {
10289 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10290 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10291 return 1;
10292 else
10293 return 0;
10294 }
10295
10296 static int
10297 remote_supports_non_stop (void)
10298 {
10299 return 1;
10300 }
10301
10302 static int
10303 remote_supports_disable_randomization (void)
10304 {
10305 /* Only supported in extended mode. */
10306 return 0;
10307 }
10308
10309 static int
10310 remote_supports_multi_process (void)
10311 {
10312 struct remote_state *rs = get_remote_state ();
10313
10314 /* Only extended-remote handles being attached to multiple
10315 processes, even though plain remote can use the multi-process
10316 thread id extensions, so that GDB knows the target process's
10317 PID. */
10318 return rs->extended && remote_multi_process_p (rs);
10319 }
10320
10321 static int
10322 remote_supports_cond_tracepoints (void)
10323 {
10324 struct remote_state *rs = get_remote_state ();
10325
10326 return rs->cond_tracepoints;
10327 }
10328
10329 static int
10330 remote_supports_cond_breakpoints (void)
10331 {
10332 struct remote_state *rs = get_remote_state ();
10333
10334 return rs->cond_breakpoints;
10335 }
10336
10337 static int
10338 remote_supports_fast_tracepoints (void)
10339 {
10340 struct remote_state *rs = get_remote_state ();
10341
10342 return rs->fast_tracepoints;
10343 }
10344
10345 static int
10346 remote_supports_static_tracepoints (void)
10347 {
10348 struct remote_state *rs = get_remote_state ();
10349
10350 return rs->static_tracepoints;
10351 }
10352
10353 static int
10354 remote_supports_install_in_trace (void)
10355 {
10356 struct remote_state *rs = get_remote_state ();
10357
10358 return rs->install_in_trace;
10359 }
10360
10361 static int
10362 remote_supports_enable_disable_tracepoint (void)
10363 {
10364 struct remote_state *rs = get_remote_state ();
10365
10366 return rs->enable_disable_tracepoints;
10367 }
10368
10369 static int
10370 remote_supports_string_tracing (void)
10371 {
10372 struct remote_state *rs = get_remote_state ();
10373
10374 return rs->string_tracing;
10375 }
10376
10377 static int
10378 remote_can_run_breakpoint_commands (void)
10379 {
10380 struct remote_state *rs = get_remote_state ();
10381
10382 return rs->breakpoint_commands;
10383 }
10384
10385 static void
10386 remote_trace_init (void)
10387 {
10388 putpkt ("QTinit");
10389 remote_get_noisy_reply (&target_buf, &target_buf_size);
10390 if (strcmp (target_buf, "OK") != 0)
10391 error (_("Target does not support this command."));
10392 }
10393
10394 static void free_actions_list (char **actions_list);
10395 static void free_actions_list_cleanup_wrapper (void *);
10396 static void
10397 free_actions_list_cleanup_wrapper (void *al)
10398 {
10399 free_actions_list (al);
10400 }
10401
10402 static void
10403 free_actions_list (char **actions_list)
10404 {
10405 int ndx;
10406
10407 if (actions_list == 0)
10408 return;
10409
10410 for (ndx = 0; actions_list[ndx]; ndx++)
10411 xfree (actions_list[ndx]);
10412
10413 xfree (actions_list);
10414 }
10415
10416 /* Recursive routine to walk through command list including loops, and
10417 download packets for each command. */
10418
10419 static void
10420 remote_download_command_source (int num, ULONGEST addr,
10421 struct command_line *cmds)
10422 {
10423 struct remote_state *rs = get_remote_state ();
10424 struct command_line *cmd;
10425
10426 for (cmd = cmds; cmd; cmd = cmd->next)
10427 {
10428 QUIT; /* Allow user to bail out with ^C. */
10429 strcpy (rs->buf, "QTDPsrc:");
10430 encode_source_string (num, addr, "cmd", cmd->line,
10431 rs->buf + strlen (rs->buf),
10432 rs->buf_size - strlen (rs->buf));
10433 putpkt (rs->buf);
10434 remote_get_noisy_reply (&target_buf, &target_buf_size);
10435 if (strcmp (target_buf, "OK"))
10436 warning (_("Target does not support source download."));
10437
10438 if (cmd->control_type == while_control
10439 || cmd->control_type == while_stepping_control)
10440 {
10441 remote_download_command_source (num, addr, *cmd->body_list);
10442
10443 QUIT; /* Allow user to bail out with ^C. */
10444 strcpy (rs->buf, "QTDPsrc:");
10445 encode_source_string (num, addr, "cmd", "end",
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 }
10454 }
10455
10456 static void
10457 remote_download_tracepoint (struct bp_location *loc)
10458 {
10459 #define BUF_SIZE 2048
10460
10461 CORE_ADDR tpaddr;
10462 char addrbuf[40];
10463 char buf[BUF_SIZE];
10464 char **tdp_actions;
10465 char **stepping_actions;
10466 int ndx;
10467 struct cleanup *old_chain = NULL;
10468 struct agent_expr *aexpr;
10469 struct cleanup *aexpr_chain = NULL;
10470 char *pkt;
10471 struct breakpoint *b = loc->owner;
10472 struct tracepoint *t = (struct tracepoint *) b;
10473
10474 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10475 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10476 tdp_actions);
10477 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10478 stepping_actions);
10479
10480 tpaddr = loc->address;
10481 sprintf_vma (addrbuf, tpaddr);
10482 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10483 addrbuf, /* address */
10484 (b->enable_state == bp_enabled ? 'E' : 'D'),
10485 t->step_count, t->pass_count);
10486 /* Fast tracepoints are mostly handled by the target, but we can
10487 tell the target how big of an instruction block should be moved
10488 around. */
10489 if (b->type == bp_fast_tracepoint)
10490 {
10491 /* Only test for support at download time; we may not know
10492 target capabilities at definition time. */
10493 if (remote_supports_fast_tracepoints ())
10494 {
10495 int isize;
10496
10497 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10498 tpaddr, &isize, NULL))
10499 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10500 isize);
10501 else
10502 /* If it passed validation at definition but fails now,
10503 something is very wrong. */
10504 internal_error (__FILE__, __LINE__,
10505 _("Fast tracepoint not "
10506 "valid during download"));
10507 }
10508 else
10509 /* Fast tracepoints are functionally identical to regular
10510 tracepoints, so don't take lack of support as a reason to
10511 give up on the trace run. */
10512 warning (_("Target does not support fast tracepoints, "
10513 "downloading %d as regular tracepoint"), b->number);
10514 }
10515 else if (b->type == bp_static_tracepoint)
10516 {
10517 /* Only test for support at download time; we may not know
10518 target capabilities at definition time. */
10519 if (remote_supports_static_tracepoints ())
10520 {
10521 struct static_tracepoint_marker marker;
10522
10523 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10524 strcat (buf, ":S");
10525 else
10526 error (_("Static tracepoint not valid during download"));
10527 }
10528 else
10529 /* Fast tracepoints are functionally identical to regular
10530 tracepoints, so don't take lack of support as a reason
10531 to give up on the trace run. */
10532 error (_("Target does not support static tracepoints"));
10533 }
10534 /* If the tracepoint has a conditional, make it into an agent
10535 expression and append to the definition. */
10536 if (loc->cond)
10537 {
10538 /* Only test support at download time, we may not know target
10539 capabilities at definition time. */
10540 if (remote_supports_cond_tracepoints ())
10541 {
10542 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10543 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10544 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10545 aexpr->len);
10546 pkt = buf + strlen (buf);
10547 for (ndx = 0; ndx < aexpr->len; ++ndx)
10548 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10549 *pkt = '\0';
10550 do_cleanups (aexpr_chain);
10551 }
10552 else
10553 warning (_("Target does not support conditional tracepoints, "
10554 "ignoring tp %d cond"), b->number);
10555 }
10556
10557 if (b->commands || *default_collect)
10558 strcat (buf, "-");
10559 putpkt (buf);
10560 remote_get_noisy_reply (&target_buf, &target_buf_size);
10561 if (strcmp (target_buf, "OK"))
10562 error (_("Target does not support tracepoints."));
10563
10564 /* do_single_steps (t); */
10565 if (tdp_actions)
10566 {
10567 for (ndx = 0; tdp_actions[ndx]; ndx++)
10568 {
10569 QUIT; /* Allow user to bail out with ^C. */
10570 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10571 b->number, addrbuf, /* address */
10572 tdp_actions[ndx],
10573 ((tdp_actions[ndx + 1] || stepping_actions)
10574 ? '-' : 0));
10575 putpkt (buf);
10576 remote_get_noisy_reply (&target_buf,
10577 &target_buf_size);
10578 if (strcmp (target_buf, "OK"))
10579 error (_("Error on target while setting tracepoints."));
10580 }
10581 }
10582 if (stepping_actions)
10583 {
10584 for (ndx = 0; stepping_actions[ndx]; ndx++)
10585 {
10586 QUIT; /* Allow user to bail out with ^C. */
10587 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10588 b->number, addrbuf, /* address */
10589 ((ndx == 0) ? "S" : ""),
10590 stepping_actions[ndx],
10591 (stepping_actions[ndx + 1] ? "-" : ""));
10592 putpkt (buf);
10593 remote_get_noisy_reply (&target_buf,
10594 &target_buf_size);
10595 if (strcmp (target_buf, "OK"))
10596 error (_("Error on target while setting tracepoints."));
10597 }
10598 }
10599
10600 if (remote_protocol_packets[PACKET_TracepointSource].support
10601 == PACKET_ENABLE)
10602 {
10603 if (b->addr_string)
10604 {
10605 strcpy (buf, "QTDPsrc:");
10606 encode_source_string (b->number, loc->address,
10607 "at", b->addr_string, buf + strlen (buf),
10608 2048 - strlen (buf));
10609
10610 putpkt (buf);
10611 remote_get_noisy_reply (&target_buf, &target_buf_size);
10612 if (strcmp (target_buf, "OK"))
10613 warning (_("Target does not support source download."));
10614 }
10615 if (b->cond_string)
10616 {
10617 strcpy (buf, "QTDPsrc:");
10618 encode_source_string (b->number, loc->address,
10619 "cond", b->cond_string, buf + strlen (buf),
10620 2048 - strlen (buf));
10621 putpkt (buf);
10622 remote_get_noisy_reply (&target_buf, &target_buf_size);
10623 if (strcmp (target_buf, "OK"))
10624 warning (_("Target does not support source download."));
10625 }
10626 remote_download_command_source (b->number, loc->address,
10627 breakpoint_commands (b));
10628 }
10629
10630 do_cleanups (old_chain);
10631 }
10632
10633 static int
10634 remote_can_download_tracepoint (void)
10635 {
10636 struct remote_state *rs = get_remote_state ();
10637 struct trace_status *ts;
10638 int status;
10639
10640 /* Don't try to install tracepoints until we've relocated our
10641 symbols, and fetched and merged the target's tracepoint list with
10642 ours. */
10643 if (rs->starting_up)
10644 return 0;
10645
10646 ts = current_trace_status ();
10647 status = remote_get_trace_status (ts);
10648
10649 if (status == -1 || !ts->running_known || !ts->running)
10650 return 0;
10651
10652 /* If we are in a tracing experiment, but remote stub doesn't support
10653 installing tracepoint in trace, we have to return. */
10654 if (!remote_supports_install_in_trace ())
10655 return 0;
10656
10657 return 1;
10658 }
10659
10660
10661 static void
10662 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10663 {
10664 struct remote_state *rs = get_remote_state ();
10665 char *p;
10666
10667 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10668 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10669 tsv->builtin);
10670 p = rs->buf + strlen (rs->buf);
10671 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10672 error (_("Trace state variable name too long for tsv definition packet"));
10673 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10674 *p++ = '\0';
10675 putpkt (rs->buf);
10676 remote_get_noisy_reply (&target_buf, &target_buf_size);
10677 if (*target_buf == '\0')
10678 error (_("Target does not support this command."));
10679 if (strcmp (target_buf, "OK") != 0)
10680 error (_("Error on target while downloading trace state variable."));
10681 }
10682
10683 static void
10684 remote_enable_tracepoint (struct bp_location *location)
10685 {
10686 struct remote_state *rs = get_remote_state ();
10687 char addr_buf[40];
10688
10689 sprintf_vma (addr_buf, location->address);
10690 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10691 location->owner->number, addr_buf);
10692 putpkt (rs->buf);
10693 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10694 if (*rs->buf == '\0')
10695 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10696 if (strcmp (rs->buf, "OK") != 0)
10697 error (_("Error on target while enabling tracepoint."));
10698 }
10699
10700 static void
10701 remote_disable_tracepoint (struct bp_location *location)
10702 {
10703 struct remote_state *rs = get_remote_state ();
10704 char addr_buf[40];
10705
10706 sprintf_vma (addr_buf, location->address);
10707 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10708 location->owner->number, addr_buf);
10709 putpkt (rs->buf);
10710 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10711 if (*rs->buf == '\0')
10712 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10713 if (strcmp (rs->buf, "OK") != 0)
10714 error (_("Error on target while disabling tracepoint."));
10715 }
10716
10717 static void
10718 remote_trace_set_readonly_regions (void)
10719 {
10720 asection *s;
10721 bfd *abfd = NULL;
10722 bfd_size_type size;
10723 bfd_vma vma;
10724 int anysecs = 0;
10725 int offset = 0;
10726
10727 if (!exec_bfd)
10728 return; /* No information to give. */
10729
10730 strcpy (target_buf, "QTro");
10731 offset = strlen (target_buf);
10732 for (s = exec_bfd->sections; s; s = s->next)
10733 {
10734 char tmp1[40], tmp2[40];
10735 int sec_length;
10736
10737 if ((s->flags & SEC_LOAD) == 0 ||
10738 /* (s->flags & SEC_CODE) == 0 || */
10739 (s->flags & SEC_READONLY) == 0)
10740 continue;
10741
10742 anysecs = 1;
10743 vma = bfd_get_section_vma (abfd, s);
10744 size = bfd_get_section_size (s);
10745 sprintf_vma (tmp1, vma);
10746 sprintf_vma (tmp2, vma + size);
10747 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10748 if (offset + sec_length + 1 > target_buf_size)
10749 {
10750 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10751 != PACKET_ENABLE)
10752 warning (_("\
10753 Too many sections for read-only sections definition packet."));
10754 break;
10755 }
10756 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10757 tmp1, tmp2);
10758 offset += sec_length;
10759 }
10760 if (anysecs)
10761 {
10762 putpkt (target_buf);
10763 getpkt (&target_buf, &target_buf_size, 0);
10764 }
10765 }
10766
10767 static void
10768 remote_trace_start (void)
10769 {
10770 putpkt ("QTStart");
10771 remote_get_noisy_reply (&target_buf, &target_buf_size);
10772 if (*target_buf == '\0')
10773 error (_("Target does not support this command."));
10774 if (strcmp (target_buf, "OK") != 0)
10775 error (_("Bogus reply from target: %s"), target_buf);
10776 }
10777
10778 static int
10779 remote_get_trace_status (struct trace_status *ts)
10780 {
10781 /* Initialize it just to avoid a GCC false warning. */
10782 char *p = NULL;
10783 /* FIXME we need to get register block size some other way. */
10784 extern int trace_regblock_size;
10785 volatile struct gdb_exception ex;
10786 enum packet_result result;
10787
10788 if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
10789 return -1;
10790
10791 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10792
10793 putpkt ("qTStatus");
10794
10795 TRY_CATCH (ex, RETURN_MASK_ERROR)
10796 {
10797 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10798 }
10799 if (ex.reason < 0)
10800 {
10801 if (ex.error != TARGET_CLOSE_ERROR)
10802 {
10803 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10804 return -1;
10805 }
10806 throw_exception (ex);
10807 }
10808
10809 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10810
10811 /* If the remote target doesn't do tracing, flag it. */
10812 if (result == PACKET_UNKNOWN)
10813 return -1;
10814
10815 /* We're working with a live target. */
10816 ts->filename = NULL;
10817
10818 if (*p++ != 'T')
10819 error (_("Bogus trace status reply from target: %s"), target_buf);
10820
10821 /* Function 'parse_trace_status' sets default value of each field of
10822 'ts' at first, so we don't have to do it here. */
10823 parse_trace_status (p, ts);
10824
10825 return ts->running;
10826 }
10827
10828 static void
10829 remote_get_tracepoint_status (struct breakpoint *bp,
10830 struct uploaded_tp *utp)
10831 {
10832 struct remote_state *rs = get_remote_state ();
10833 char *reply;
10834 struct bp_location *loc;
10835 struct tracepoint *tp = (struct tracepoint *) bp;
10836 size_t size = get_remote_packet_size ();
10837
10838 if (tp)
10839 {
10840 tp->base.hit_count = 0;
10841 tp->traceframe_usage = 0;
10842 for (loc = tp->base.loc; loc; loc = loc->next)
10843 {
10844 /* If the tracepoint was never downloaded, don't go asking for
10845 any status. */
10846 if (tp->number_on_target == 0)
10847 continue;
10848 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10849 phex_nz (loc->address, 0));
10850 putpkt (rs->buf);
10851 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10852 if (reply && *reply)
10853 {
10854 if (*reply == 'V')
10855 parse_tracepoint_status (reply + 1, bp, utp);
10856 }
10857 }
10858 }
10859 else if (utp)
10860 {
10861 utp->hit_count = 0;
10862 utp->traceframe_usage = 0;
10863 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10864 phex_nz (utp->addr, 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
10875 static void
10876 remote_trace_stop (void)
10877 {
10878 putpkt ("QTStop");
10879 remote_get_noisy_reply (&target_buf, &target_buf_size);
10880 if (*target_buf == '\0')
10881 error (_("Target does not support this command."));
10882 if (strcmp (target_buf, "OK") != 0)
10883 error (_("Bogus reply from target: %s"), target_buf);
10884 }
10885
10886 static int
10887 remote_trace_find (enum trace_find_type type, int num,
10888 CORE_ADDR addr1, CORE_ADDR addr2,
10889 int *tpp)
10890 {
10891 struct remote_state *rs = get_remote_state ();
10892 char *endbuf = rs->buf + get_remote_packet_size ();
10893 char *p, *reply;
10894 int target_frameno = -1, target_tracept = -1;
10895
10896 /* Lookups other than by absolute frame number depend on the current
10897 trace selected, so make sure it is correct on the remote end
10898 first. */
10899 if (type != tfind_number)
10900 set_remote_traceframe ();
10901
10902 p = rs->buf;
10903 strcpy (p, "QTFrame:");
10904 p = strchr (p, '\0');
10905 switch (type)
10906 {
10907 case tfind_number:
10908 xsnprintf (p, endbuf - p, "%x", num);
10909 break;
10910 case tfind_pc:
10911 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
10912 break;
10913 case tfind_tp:
10914 xsnprintf (p, endbuf - p, "tdp:%x", num);
10915 break;
10916 case tfind_range:
10917 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10918 phex_nz (addr2, 0));
10919 break;
10920 case tfind_outside:
10921 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10922 phex_nz (addr2, 0));
10923 break;
10924 default:
10925 error (_("Unknown trace find type %d"), type);
10926 }
10927
10928 putpkt (rs->buf);
10929 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
10930 if (*reply == '\0')
10931 error (_("Target does not support this command."));
10932
10933 while (reply && *reply)
10934 switch (*reply)
10935 {
10936 case 'F':
10937 p = ++reply;
10938 target_frameno = (int) strtol (p, &reply, 16);
10939 if (reply == p)
10940 error (_("Unable to parse trace frame number"));
10941 /* Don't update our remote traceframe number cache on failure
10942 to select a remote traceframe. */
10943 if (target_frameno == -1)
10944 return -1;
10945 break;
10946 case 'T':
10947 p = ++reply;
10948 target_tracept = (int) strtol (p, &reply, 16);
10949 if (reply == p)
10950 error (_("Unable to parse tracepoint number"));
10951 break;
10952 case 'O': /* "OK"? */
10953 if (reply[1] == 'K' && reply[2] == '\0')
10954 reply += 2;
10955 else
10956 error (_("Bogus reply from target: %s"), reply);
10957 break;
10958 default:
10959 error (_("Bogus reply from target: %s"), reply);
10960 }
10961 if (tpp)
10962 *tpp = target_tracept;
10963
10964 rs->remote_traceframe_number = target_frameno;
10965 return target_frameno;
10966 }
10967
10968 static int
10969 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
10970 {
10971 struct remote_state *rs = get_remote_state ();
10972 char *reply;
10973 ULONGEST uval;
10974
10975 set_remote_traceframe ();
10976
10977 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
10978 putpkt (rs->buf);
10979 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10980 if (reply && *reply)
10981 {
10982 if (*reply == 'V')
10983 {
10984 unpack_varlen_hex (reply + 1, &uval);
10985 *val = (LONGEST) uval;
10986 return 1;
10987 }
10988 }
10989 return 0;
10990 }
10991
10992 static int
10993 remote_save_trace_data (const char *filename)
10994 {
10995 struct remote_state *rs = get_remote_state ();
10996 char *p, *reply;
10997
10998 p = rs->buf;
10999 strcpy (p, "QTSave:");
11000 p += strlen (p);
11001 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11002 error (_("Remote file name too long for trace save packet"));
11003 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
11004 *p++ = '\0';
11005 putpkt (rs->buf);
11006 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11007 if (*reply == '\0')
11008 error (_("Target does not support this command."));
11009 if (strcmp (reply, "OK") != 0)
11010 error (_("Bogus reply from target: %s"), reply);
11011 return 0;
11012 }
11013
11014 /* This is basically a memory transfer, but needs to be its own packet
11015 because we don't know how the target actually organizes its trace
11016 memory, plus we want to be able to ask for as much as possible, but
11017 not be unhappy if we don't get as much as we ask for. */
11018
11019 static LONGEST
11020 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
11021 {
11022 struct remote_state *rs = get_remote_state ();
11023 char *reply;
11024 char *p;
11025 int rslt;
11026
11027 p = rs->buf;
11028 strcpy (p, "qTBuffer:");
11029 p += strlen (p);
11030 p += hexnumstr (p, offset);
11031 *p++ = ',';
11032 p += hexnumstr (p, len);
11033 *p++ = '\0';
11034
11035 putpkt (rs->buf);
11036 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11037 if (reply && *reply)
11038 {
11039 /* 'l' by itself means we're at the end of the buffer and
11040 there is nothing more to get. */
11041 if (*reply == 'l')
11042 return 0;
11043
11044 /* Convert the reply into binary. Limit the number of bytes to
11045 convert according to our passed-in buffer size, rather than
11046 what was returned in the packet; if the target is
11047 unexpectedly generous and gives us a bigger reply than we
11048 asked for, we don't want to crash. */
11049 rslt = hex2bin (target_buf, buf, len);
11050 return rslt;
11051 }
11052
11053 /* Something went wrong, flag as an error. */
11054 return -1;
11055 }
11056
11057 static void
11058 remote_set_disconnected_tracing (int val)
11059 {
11060 struct remote_state *rs = get_remote_state ();
11061
11062 if (rs->disconnected_tracing)
11063 {
11064 char *reply;
11065
11066 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11067 putpkt (rs->buf);
11068 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11069 if (*reply == '\0')
11070 error (_("Target does not support this command."));
11071 if (strcmp (reply, "OK") != 0)
11072 error (_("Bogus reply from target: %s"), reply);
11073 }
11074 else if (val)
11075 warning (_("Target does not support disconnected tracing."));
11076 }
11077
11078 static int
11079 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11080 {
11081 struct thread_info *info = find_thread_ptid (ptid);
11082
11083 if (info && info->private)
11084 return info->private->core;
11085 return -1;
11086 }
11087
11088 static void
11089 remote_set_circular_trace_buffer (int val)
11090 {
11091 struct remote_state *rs = get_remote_state ();
11092 char *reply;
11093
11094 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11095 putpkt (rs->buf);
11096 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11097 if (*reply == '\0')
11098 error (_("Target does not support this command."));
11099 if (strcmp (reply, "OK") != 0)
11100 error (_("Bogus reply from target: %s"), reply);
11101 }
11102
11103 static struct traceframe_info *
11104 remote_traceframe_info (void)
11105 {
11106 char *text;
11107
11108 text = target_read_stralloc (&current_target,
11109 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11110 if (text != NULL)
11111 {
11112 struct traceframe_info *info;
11113 struct cleanup *back_to = make_cleanup (xfree, text);
11114
11115 info = parse_traceframe_info (text);
11116 do_cleanups (back_to);
11117 return info;
11118 }
11119
11120 return NULL;
11121 }
11122
11123 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11124 instruction on which a fast tracepoint may be placed. Returns -1
11125 if the packet is not supported, and 0 if the minimum instruction
11126 length is unknown. */
11127
11128 static int
11129 remote_get_min_fast_tracepoint_insn_len (void)
11130 {
11131 struct remote_state *rs = get_remote_state ();
11132 char *reply;
11133
11134 /* If we're not debugging a process yet, the IPA can't be
11135 loaded. */
11136 if (!target_has_execution)
11137 return 0;
11138
11139 /* Make sure the remote is pointing at the right process. */
11140 set_general_process ();
11141
11142 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11143 putpkt (rs->buf);
11144 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11145 if (*reply == '\0')
11146 return -1;
11147 else
11148 {
11149 ULONGEST min_insn_len;
11150
11151 unpack_varlen_hex (reply, &min_insn_len);
11152
11153 return (int) min_insn_len;
11154 }
11155 }
11156
11157 static void
11158 remote_set_trace_buffer_size (LONGEST val)
11159 {
11160 if (remote_protocol_packets[PACKET_QTBuffer_size].support
11161 != PACKET_DISABLE)
11162 {
11163 struct remote_state *rs = get_remote_state ();
11164 char *buf = rs->buf;
11165 char *endbuf = rs->buf + get_remote_packet_size ();
11166 enum packet_result result;
11167
11168 gdb_assert (val >= 0 || val == -1);
11169 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11170 /* Send -1 as literal "-1" to avoid host size dependency. */
11171 if (val < 0)
11172 {
11173 *buf++ = '-';
11174 buf += hexnumstr (buf, (ULONGEST) -val);
11175 }
11176 else
11177 buf += hexnumstr (buf, (ULONGEST) val);
11178
11179 putpkt (rs->buf);
11180 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11181 result = packet_ok (rs->buf,
11182 &remote_protocol_packets[PACKET_QTBuffer_size]);
11183
11184 if (result != PACKET_OK)
11185 warning (_("Bogus reply from target: %s"), rs->buf);
11186 }
11187 }
11188
11189 static int
11190 remote_set_trace_notes (const char *user, const char *notes,
11191 const char *stop_notes)
11192 {
11193 struct remote_state *rs = get_remote_state ();
11194 char *reply;
11195 char *buf = rs->buf;
11196 char *endbuf = rs->buf + get_remote_packet_size ();
11197 int nbytes;
11198
11199 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11200 if (user)
11201 {
11202 buf += xsnprintf (buf, endbuf - buf, "user:");
11203 nbytes = bin2hex ((gdb_byte *) user, buf, 0);
11204 buf += 2 * nbytes;
11205 *buf++ = ';';
11206 }
11207 if (notes)
11208 {
11209 buf += xsnprintf (buf, endbuf - buf, "notes:");
11210 nbytes = bin2hex ((gdb_byte *) notes, buf, 0);
11211 buf += 2 * nbytes;
11212 *buf++ = ';';
11213 }
11214 if (stop_notes)
11215 {
11216 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11217 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, 0);
11218 buf += 2 * nbytes;
11219 *buf++ = ';';
11220 }
11221 /* Ensure the buffer is terminated. */
11222 *buf = '\0';
11223
11224 putpkt (rs->buf);
11225 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11226 if (*reply == '\0')
11227 return 0;
11228
11229 if (strcmp (reply, "OK") != 0)
11230 error (_("Bogus reply from target: %s"), reply);
11231
11232 return 1;
11233 }
11234
11235 static int
11236 remote_use_agent (int use)
11237 {
11238 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11239 {
11240 struct remote_state *rs = get_remote_state ();
11241
11242 /* If the stub supports QAgent. */
11243 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11244 putpkt (rs->buf);
11245 getpkt (&rs->buf, &rs->buf_size, 0);
11246
11247 if (strcmp (rs->buf, "OK") == 0)
11248 {
11249 use_agent = use;
11250 return 1;
11251 }
11252 }
11253
11254 return 0;
11255 }
11256
11257 static int
11258 remote_can_use_agent (void)
11259 {
11260 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11261 }
11262
11263 struct btrace_target_info
11264 {
11265 /* The ptid of the traced thread. */
11266 ptid_t ptid;
11267 };
11268
11269 /* Check whether the target supports branch tracing. */
11270
11271 static int
11272 remote_supports_btrace (void)
11273 {
11274 if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11275 return 0;
11276 if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11277 return 0;
11278 if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11279 return 0;
11280
11281 return 1;
11282 }
11283
11284 /* Enable branch tracing. */
11285
11286 static struct btrace_target_info *
11287 remote_enable_btrace (ptid_t ptid)
11288 {
11289 struct btrace_target_info *tinfo = NULL;
11290 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11291 struct remote_state *rs = get_remote_state ();
11292 char *buf = rs->buf;
11293 char *endbuf = rs->buf + get_remote_packet_size ();
11294
11295 if (packet->support != PACKET_ENABLE)
11296 error (_("Target does not support branch tracing."));
11297
11298 set_general_thread (ptid);
11299
11300 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11301 putpkt (rs->buf);
11302 getpkt (&rs->buf, &rs->buf_size, 0);
11303
11304 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11305 {
11306 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11307 error (_("Could not enable branch tracing for %s: %s"),
11308 target_pid_to_str (ptid), rs->buf + 2);
11309 else
11310 error (_("Could not enable branch tracing for %s."),
11311 target_pid_to_str (ptid));
11312 }
11313
11314 tinfo = xzalloc (sizeof (*tinfo));
11315 tinfo->ptid = ptid;
11316
11317 return tinfo;
11318 }
11319
11320 /* Disable branch tracing. */
11321
11322 static void
11323 remote_disable_btrace (struct btrace_target_info *tinfo)
11324 {
11325 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11326 struct remote_state *rs = get_remote_state ();
11327 char *buf = rs->buf;
11328 char *endbuf = rs->buf + get_remote_packet_size ();
11329
11330 if (packet->support != PACKET_ENABLE)
11331 error (_("Target does not support branch tracing."));
11332
11333 set_general_thread (tinfo->ptid);
11334
11335 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11336 putpkt (rs->buf);
11337 getpkt (&rs->buf, &rs->buf_size, 0);
11338
11339 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11340 {
11341 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11342 error (_("Could not disable branch tracing for %s: %s"),
11343 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11344 else
11345 error (_("Could not disable branch tracing for %s."),
11346 target_pid_to_str (tinfo->ptid));
11347 }
11348
11349 xfree (tinfo);
11350 }
11351
11352 /* Teardown branch tracing. */
11353
11354 static void
11355 remote_teardown_btrace (struct btrace_target_info *tinfo)
11356 {
11357 /* We must not talk to the target during teardown. */
11358 xfree (tinfo);
11359 }
11360
11361 /* Read the branch trace. */
11362
11363 static VEC (btrace_block_s) *
11364 remote_read_btrace (struct btrace_target_info *tinfo,
11365 enum btrace_read_type type)
11366 {
11367 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11368 struct remote_state *rs = get_remote_state ();
11369 VEC (btrace_block_s) *btrace = NULL;
11370 const char *annex;
11371 char *xml;
11372
11373 if (packet->support != PACKET_ENABLE)
11374 error (_("Target does not support branch tracing."));
11375
11376 #if !defined(HAVE_LIBEXPAT)
11377 error (_("Cannot process branch tracing result. XML parsing not supported."));
11378 #endif
11379
11380 switch (type)
11381 {
11382 case btrace_read_all:
11383 annex = "all";
11384 break;
11385 case btrace_read_new:
11386 annex = "new";
11387 break;
11388 default:
11389 internal_error (__FILE__, __LINE__,
11390 _("Bad branch tracing read type: %u."),
11391 (unsigned int) type);
11392 }
11393
11394 xml = target_read_stralloc (&current_target,
11395 TARGET_OBJECT_BTRACE, annex);
11396 if (xml != NULL)
11397 {
11398 struct cleanup *cleanup = make_cleanup (xfree, xml);
11399
11400 btrace = parse_xml_btrace (xml);
11401 do_cleanups (cleanup);
11402 }
11403
11404 return btrace;
11405 }
11406
11407 static int
11408 remote_augmented_libraries_svr4_read (void)
11409 {
11410 struct remote_state *rs = get_remote_state ();
11411
11412 return rs->augmented_libraries_svr4_read;
11413 }
11414
11415 static void
11416 init_remote_ops (void)
11417 {
11418 remote_ops.to_shortname = "remote";
11419 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11420 remote_ops.to_doc =
11421 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11422 Specify the serial device it is connected to\n\
11423 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11424 remote_ops.to_open = remote_open;
11425 remote_ops.to_close = remote_close;
11426 remote_ops.to_detach = remote_detach;
11427 remote_ops.to_disconnect = remote_disconnect;
11428 remote_ops.to_resume = remote_resume;
11429 remote_ops.to_wait = remote_wait;
11430 remote_ops.to_fetch_registers = remote_fetch_registers;
11431 remote_ops.to_store_registers = remote_store_registers;
11432 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11433 remote_ops.to_files_info = remote_files_info;
11434 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11435 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11436 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11437 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11438 remote_ops.to_watchpoint_addr_within_range =
11439 remote_watchpoint_addr_within_range;
11440 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11441 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11442 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11443 remote_ops.to_region_ok_for_hw_watchpoint
11444 = remote_region_ok_for_hw_watchpoint;
11445 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11446 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11447 remote_ops.to_kill = remote_kill;
11448 remote_ops.to_load = generic_load;
11449 remote_ops.to_mourn_inferior = remote_mourn;
11450 remote_ops.to_pass_signals = remote_pass_signals;
11451 remote_ops.to_program_signals = remote_program_signals;
11452 remote_ops.to_thread_alive = remote_thread_alive;
11453 remote_ops.to_find_new_threads = remote_threads_info;
11454 remote_ops.to_pid_to_str = remote_pid_to_str;
11455 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11456 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11457 remote_ops.to_stop = remote_stop;
11458 remote_ops.to_xfer_partial = remote_xfer_partial;
11459 remote_ops.to_rcmd = remote_rcmd;
11460 remote_ops.to_log_command = serial_log_command;
11461 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11462 remote_ops.to_stratum = process_stratum;
11463 remote_ops.to_has_all_memory = default_child_has_all_memory;
11464 remote_ops.to_has_memory = default_child_has_memory;
11465 remote_ops.to_has_stack = default_child_has_stack;
11466 remote_ops.to_has_registers = default_child_has_registers;
11467 remote_ops.to_has_execution = default_child_has_execution;
11468 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11469 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11470 remote_ops.to_magic = OPS_MAGIC;
11471 remote_ops.to_memory_map = remote_memory_map;
11472 remote_ops.to_flash_erase = remote_flash_erase;
11473 remote_ops.to_flash_done = remote_flash_done;
11474 remote_ops.to_read_description = remote_read_description;
11475 remote_ops.to_search_memory = remote_search_memory;
11476 remote_ops.to_can_async_p = remote_can_async_p;
11477 remote_ops.to_is_async_p = remote_is_async_p;
11478 remote_ops.to_async = remote_async;
11479 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11480 remote_ops.to_terminal_ours = remote_terminal_ours;
11481 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11482 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11483 remote_ops.to_supports_disable_randomization
11484 = remote_supports_disable_randomization;
11485 remote_ops.to_fileio_open = remote_hostio_open;
11486 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11487 remote_ops.to_fileio_pread = remote_hostio_pread;
11488 remote_ops.to_fileio_close = remote_hostio_close;
11489 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11490 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11491 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11492 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11493 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11494 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11495 remote_ops.to_trace_init = remote_trace_init;
11496 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11497 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11498 remote_ops.to_download_trace_state_variable
11499 = remote_download_trace_state_variable;
11500 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11501 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11502 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11503 remote_ops.to_trace_start = remote_trace_start;
11504 remote_ops.to_get_trace_status = remote_get_trace_status;
11505 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11506 remote_ops.to_trace_stop = remote_trace_stop;
11507 remote_ops.to_trace_find = remote_trace_find;
11508 remote_ops.to_get_trace_state_variable_value
11509 = remote_get_trace_state_variable_value;
11510 remote_ops.to_save_trace_data = remote_save_trace_data;
11511 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11512 remote_ops.to_upload_trace_state_variables
11513 = remote_upload_trace_state_variables;
11514 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11515 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11516 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11517 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11518 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11519 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11520 remote_ops.to_core_of_thread = remote_core_of_thread;
11521 remote_ops.to_verify_memory = remote_verify_memory;
11522 remote_ops.to_get_tib_address = remote_get_tib_address;
11523 remote_ops.to_set_permissions = remote_set_permissions;
11524 remote_ops.to_static_tracepoint_marker_at
11525 = remote_static_tracepoint_marker_at;
11526 remote_ops.to_static_tracepoint_markers_by_strid
11527 = remote_static_tracepoint_markers_by_strid;
11528 remote_ops.to_traceframe_info = remote_traceframe_info;
11529 remote_ops.to_use_agent = remote_use_agent;
11530 remote_ops.to_can_use_agent = remote_can_use_agent;
11531 remote_ops.to_supports_btrace = remote_supports_btrace;
11532 remote_ops.to_enable_btrace = remote_enable_btrace;
11533 remote_ops.to_disable_btrace = remote_disable_btrace;
11534 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11535 remote_ops.to_read_btrace = remote_read_btrace;
11536 remote_ops.to_augmented_libraries_svr4_read =
11537 remote_augmented_libraries_svr4_read;
11538 }
11539
11540 /* Set up the extended remote vector by making a copy of the standard
11541 remote vector and adding to it. */
11542
11543 static void
11544 init_extended_remote_ops (void)
11545 {
11546 extended_remote_ops = remote_ops;
11547
11548 extended_remote_ops.to_shortname = "extended-remote";
11549 extended_remote_ops.to_longname =
11550 "Extended remote serial target in gdb-specific protocol";
11551 extended_remote_ops.to_doc =
11552 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11553 Specify the serial device it is connected to (e.g. /dev/ttya).";
11554 extended_remote_ops.to_open = extended_remote_open;
11555 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11556 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11557 extended_remote_ops.to_detach = extended_remote_detach;
11558 extended_remote_ops.to_attach = extended_remote_attach;
11559 extended_remote_ops.to_kill = extended_remote_kill;
11560 extended_remote_ops.to_supports_disable_randomization
11561 = extended_remote_supports_disable_randomization;
11562 }
11563
11564 static int
11565 remote_can_async_p (void)
11566 {
11567 struct remote_state *rs = get_remote_state ();
11568
11569 if (!target_async_permitted)
11570 /* We only enable async when the user specifically asks for it. */
11571 return 0;
11572
11573 /* We're async whenever the serial device is. */
11574 return serial_can_async_p (rs->remote_desc);
11575 }
11576
11577 static int
11578 remote_is_async_p (void)
11579 {
11580 struct remote_state *rs = get_remote_state ();
11581
11582 if (!target_async_permitted)
11583 /* We only enable async when the user specifically asks for it. */
11584 return 0;
11585
11586 /* We're async whenever the serial device is. */
11587 return serial_is_async_p (rs->remote_desc);
11588 }
11589
11590 /* Pass the SERIAL event on and up to the client. One day this code
11591 will be able to delay notifying the client of an event until the
11592 point where an entire packet has been received. */
11593
11594 static serial_event_ftype remote_async_serial_handler;
11595
11596 static void
11597 remote_async_serial_handler (struct serial *scb, void *context)
11598 {
11599 struct remote_state *rs = context;
11600
11601 /* Don't propogate error information up to the client. Instead let
11602 the client find out about the error by querying the target. */
11603 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
11604 }
11605
11606 static void
11607 remote_async_inferior_event_handler (gdb_client_data data)
11608 {
11609 inferior_event_handler (INF_REG_EVENT, NULL);
11610 }
11611
11612 static void
11613 remote_async (void (*callback) (enum inferior_event_type event_type,
11614 void *context), void *context)
11615 {
11616 struct remote_state *rs = get_remote_state ();
11617
11618 if (callback != NULL)
11619 {
11620 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11621 rs->async_client_callback = callback;
11622 rs->async_client_context = context;
11623 }
11624 else
11625 serial_async (rs->remote_desc, NULL, NULL);
11626 }
11627
11628 static void
11629 set_remote_cmd (char *args, int from_tty)
11630 {
11631 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
11632 }
11633
11634 static void
11635 show_remote_cmd (char *args, int from_tty)
11636 {
11637 /* We can't just use cmd_show_list here, because we want to skip
11638 the redundant "show remote Z-packet" and the legacy aliases. */
11639 struct cleanup *showlist_chain;
11640 struct cmd_list_element *list = remote_show_cmdlist;
11641 struct ui_out *uiout = current_uiout;
11642
11643 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11644 for (; list != NULL; list = list->next)
11645 if (strcmp (list->name, "Z-packet") == 0)
11646 continue;
11647 else if (list->type == not_set_cmd)
11648 /* Alias commands are exactly like the original, except they
11649 don't have the normal type. */
11650 continue;
11651 else
11652 {
11653 struct cleanup *option_chain
11654 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11655
11656 ui_out_field_string (uiout, "name", list->name);
11657 ui_out_text (uiout, ": ");
11658 if (list->type == show_cmd)
11659 do_show_command ((char *) NULL, from_tty, list);
11660 else
11661 cmd_func (list, NULL, from_tty);
11662 /* Close the tuple. */
11663 do_cleanups (option_chain);
11664 }
11665
11666 /* Close the tuple. */
11667 do_cleanups (showlist_chain);
11668 }
11669
11670
11671 /* Function to be called whenever a new objfile (shlib) is detected. */
11672 static void
11673 remote_new_objfile (struct objfile *objfile)
11674 {
11675 struct remote_state *rs = get_remote_state ();
11676
11677 if (rs->remote_desc != 0) /* Have a remote connection. */
11678 remote_check_symbols ();
11679 }
11680
11681 /* Pull all the tracepoints defined on the target and create local
11682 data structures representing them. We don't want to create real
11683 tracepoints yet, we don't want to mess up the user's existing
11684 collection. */
11685
11686 static int
11687 remote_upload_tracepoints (struct uploaded_tp **utpp)
11688 {
11689 struct remote_state *rs = get_remote_state ();
11690 char *p;
11691
11692 /* Ask for a first packet of tracepoint definition. */
11693 putpkt ("qTfP");
11694 getpkt (&rs->buf, &rs->buf_size, 0);
11695 p = rs->buf;
11696 while (*p && *p != 'l')
11697 {
11698 parse_tracepoint_definition (p, utpp);
11699 /* Ask for another packet of tracepoint definition. */
11700 putpkt ("qTsP");
11701 getpkt (&rs->buf, &rs->buf_size, 0);
11702 p = rs->buf;
11703 }
11704 return 0;
11705 }
11706
11707 static int
11708 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
11709 {
11710 struct remote_state *rs = get_remote_state ();
11711 char *p;
11712
11713 /* Ask for a first packet of variable definition. */
11714 putpkt ("qTfV");
11715 getpkt (&rs->buf, &rs->buf_size, 0);
11716 p = rs->buf;
11717 while (*p && *p != 'l')
11718 {
11719 parse_tsv_definition (p, utsvp);
11720 /* Ask for another packet of variable definition. */
11721 putpkt ("qTsV");
11722 getpkt (&rs->buf, &rs->buf_size, 0);
11723 p = rs->buf;
11724 }
11725 return 0;
11726 }
11727
11728 /* The "set/show range-stepping" show hook. */
11729
11730 static void
11731 show_range_stepping (struct ui_file *file, int from_tty,
11732 struct cmd_list_element *c,
11733 const char *value)
11734 {
11735 fprintf_filtered (file,
11736 _("Debugger's willingness to use range stepping "
11737 "is %s.\n"), value);
11738 }
11739
11740 /* The "set/show range-stepping" set hook. */
11741
11742 static void
11743 set_range_stepping (char *ignore_args, int from_tty,
11744 struct cmd_list_element *c)
11745 {
11746 struct remote_state *rs = get_remote_state ();
11747
11748 /* Whene enabling, check whether range stepping is actually
11749 supported by the target, and warn if not. */
11750 if (use_range_stepping)
11751 {
11752 if (rs->remote_desc != NULL)
11753 {
11754 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
11755 remote_vcont_probe (rs);
11756
11757 if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
11758 && rs->supports_vCont.r)
11759 return;
11760 }
11761
11762 warning (_("Range stepping is not supported by the current target"));
11763 }
11764 }
11765
11766 void
11767 _initialize_remote (void)
11768 {
11769 struct remote_state *rs;
11770 struct cmd_list_element *cmd;
11771 const char *cmd_name;
11772
11773 /* architecture specific data */
11774 remote_gdbarch_data_handle =
11775 gdbarch_data_register_post_init (init_remote_state);
11776 remote_g_packet_data_handle =
11777 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11778
11779 /* Initialize the per-target state. At the moment there is only one
11780 of these, not one per target. Only one target is active at a
11781 time. */
11782 remote_state = new_remote_state ();
11783
11784 init_remote_ops ();
11785 add_target (&remote_ops);
11786
11787 init_extended_remote_ops ();
11788 add_target (&extended_remote_ops);
11789
11790 /* Hook into new objfile notification. */
11791 observer_attach_new_objfile (remote_new_objfile);
11792 /* We're no longer interested in notification events of an inferior
11793 when it exits. */
11794 observer_attach_inferior_exit (discard_pending_stop_replies);
11795
11796 /* Set up signal handlers. */
11797 async_sigint_remote_token =
11798 create_async_signal_handler (async_remote_interrupt, NULL);
11799 async_sigint_remote_twice_token =
11800 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11801
11802 #if 0
11803 init_remote_threadtests ();
11804 #endif
11805
11806 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11807 /* set/show remote ... */
11808
11809 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11810 Remote protocol specific variables\n\
11811 Configure various remote-protocol specific variables such as\n\
11812 the packets being used"),
11813 &remote_set_cmdlist, "set remote ",
11814 0 /* allow-unknown */, &setlist);
11815 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11816 Remote protocol specific variables\n\
11817 Configure various remote-protocol specific variables such as\n\
11818 the packets being used"),
11819 &remote_show_cmdlist, "show remote ",
11820 0 /* allow-unknown */, &showlist);
11821
11822 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11823 Compare section data on target to the exec file.\n\
11824 Argument is a single section name (default: all loaded sections)."),
11825 &cmdlist);
11826
11827 add_cmd ("packet", class_maintenance, packet_command, _("\
11828 Send an arbitrary packet to a remote target.\n\
11829 maintenance packet TEXT\n\
11830 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11831 this command sends the string TEXT to the inferior, and displays the\n\
11832 response packet. GDB supplies the initial `$' character, and the\n\
11833 terminating `#' character and checksum."),
11834 &maintenancelist);
11835
11836 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11837 Set whether to send break if interrupted."), _("\
11838 Show whether to send break if interrupted."), _("\
11839 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11840 set_remotebreak, show_remotebreak,
11841 &setlist, &showlist);
11842 cmd_name = "remotebreak";
11843 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11844 deprecate_cmd (cmd, "set remote interrupt-sequence");
11845 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11846 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11847 deprecate_cmd (cmd, "show remote interrupt-sequence");
11848
11849 add_setshow_enum_cmd ("interrupt-sequence", class_support,
11850 interrupt_sequence_modes, &interrupt_sequence_mode,
11851 _("\
11852 Set interrupt sequence to remote target."), _("\
11853 Show interrupt sequence to remote target."), _("\
11854 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11855 NULL, show_interrupt_sequence,
11856 &remote_set_cmdlist,
11857 &remote_show_cmdlist);
11858
11859 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11860 &interrupt_on_connect, _("\
11861 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11862 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11863 If set, interrupt sequence is sent to remote target."),
11864 NULL, NULL,
11865 &remote_set_cmdlist, &remote_show_cmdlist);
11866
11867 /* Install commands for configuring memory read/write packets. */
11868
11869 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11870 Set the maximum number of bytes per memory write packet (deprecated)."),
11871 &setlist);
11872 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11873 Show the maximum number of bytes per memory write packet (deprecated)."),
11874 &showlist);
11875 add_cmd ("memory-write-packet-size", no_class,
11876 set_memory_write_packet_size, _("\
11877 Set the maximum number of bytes per memory-write packet.\n\
11878 Specify the number of bytes in a packet or 0 (zero) for the\n\
11879 default packet size. The actual limit is further reduced\n\
11880 dependent on the target. Specify ``fixed'' to disable the\n\
11881 further restriction and ``limit'' to enable that restriction."),
11882 &remote_set_cmdlist);
11883 add_cmd ("memory-read-packet-size", no_class,
11884 set_memory_read_packet_size, _("\
11885 Set the maximum number of bytes per memory-read packet.\n\
11886 Specify the number of bytes in a packet or 0 (zero) for the\n\
11887 default packet size. The actual limit is further reduced\n\
11888 dependent on the target. Specify ``fixed'' to disable the\n\
11889 further restriction and ``limit'' to enable that restriction."),
11890 &remote_set_cmdlist);
11891 add_cmd ("memory-write-packet-size", no_class,
11892 show_memory_write_packet_size,
11893 _("Show the maximum number of bytes per memory-write packet."),
11894 &remote_show_cmdlist);
11895 add_cmd ("memory-read-packet-size", no_class,
11896 show_memory_read_packet_size,
11897 _("Show the maximum number of bytes per memory-read packet."),
11898 &remote_show_cmdlist);
11899
11900 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11901 &remote_hw_watchpoint_limit, _("\
11902 Set the maximum number of target hardware watchpoints."), _("\
11903 Show the maximum number of target hardware watchpoints."), _("\
11904 Specify a negative limit for unlimited."),
11905 NULL, NULL, /* FIXME: i18n: The maximum
11906 number of target hardware
11907 watchpoints is %s. */
11908 &remote_set_cmdlist, &remote_show_cmdlist);
11909 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11910 &remote_hw_watchpoint_length_limit, _("\
11911 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11912 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11913 Specify a negative limit for unlimited."),
11914 NULL, NULL, /* FIXME: i18n: The maximum
11915 length (in bytes) of a target
11916 hardware watchpoint is %s. */
11917 &remote_set_cmdlist, &remote_show_cmdlist);
11918 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11919 &remote_hw_breakpoint_limit, _("\
11920 Set the maximum number of target hardware breakpoints."), _("\
11921 Show the maximum number of target hardware breakpoints."), _("\
11922 Specify a negative limit for unlimited."),
11923 NULL, NULL, /* FIXME: i18n: The maximum
11924 number of target hardware
11925 breakpoints is %s. */
11926 &remote_set_cmdlist, &remote_show_cmdlist);
11927
11928 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
11929 &remote_address_size, _("\
11930 Set the maximum size of the address (in bits) in a memory packet."), _("\
11931 Show the maximum size of the address (in bits) in a memory packet."), NULL,
11932 NULL,
11933 NULL, /* FIXME: i18n: */
11934 &setlist, &showlist);
11935
11936 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
11937 "X", "binary-download", 1);
11938
11939 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
11940 "vCont", "verbose-resume", 0);
11941
11942 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11943 "QPassSignals", "pass-signals", 0);
11944
11945 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
11946 "QProgramSignals", "program-signals", 0);
11947
11948 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
11949 "qSymbol", "symbol-lookup", 0);
11950
11951 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
11952 "P", "set-register", 1);
11953
11954 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
11955 "p", "fetch-register", 1);
11956
11957 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
11958 "Z0", "software-breakpoint", 0);
11959
11960 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
11961 "Z1", "hardware-breakpoint", 0);
11962
11963 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
11964 "Z2", "write-watchpoint", 0);
11965
11966 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
11967 "Z3", "read-watchpoint", 0);
11968
11969 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
11970 "Z4", "access-watchpoint", 0);
11971
11972 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11973 "qXfer:auxv:read", "read-aux-vector", 0);
11974
11975 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11976 "qXfer:features:read", "target-features", 0);
11977
11978 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
11979 "qXfer:libraries:read", "library-info", 0);
11980
11981 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
11982 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
11983
11984 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
11985 "qXfer:memory-map:read", "memory-map", 0);
11986
11987 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
11988 "qXfer:spu:read", "read-spu-object", 0);
11989
11990 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
11991 "qXfer:spu:write", "write-spu-object", 0);
11992
11993 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
11994 "qXfer:osdata:read", "osdata", 0);
11995
11996 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
11997 "qXfer:threads:read", "threads", 0);
11998
11999 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12000 "qXfer:siginfo:read", "read-siginfo-object", 0);
12001
12002 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12003 "qXfer:siginfo:write", "write-siginfo-object", 0);
12004
12005 add_packet_config_cmd
12006 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12007 "qXfer:traceframe-info:read", "traceframe-info", 0);
12008
12009 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12010 "qXfer:uib:read", "unwind-info-block", 0);
12011
12012 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12013 "qGetTLSAddr", "get-thread-local-storage-address",
12014 0);
12015
12016 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12017 "qGetTIBAddr", "get-thread-information-block-address",
12018 0);
12019
12020 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12021 "bc", "reverse-continue", 0);
12022
12023 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12024 "bs", "reverse-step", 0);
12025
12026 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12027 "qSupported", "supported-packets", 0);
12028
12029 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12030 "qSearch:memory", "search-memory", 0);
12031
12032 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12033 "qTStatus", "trace-status", 0);
12034
12035 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12036 "vFile:open", "hostio-open", 0);
12037
12038 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12039 "vFile:pread", "hostio-pread", 0);
12040
12041 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12042 "vFile:pwrite", "hostio-pwrite", 0);
12043
12044 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12045 "vFile:close", "hostio-close", 0);
12046
12047 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12048 "vFile:unlink", "hostio-unlink", 0);
12049
12050 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12051 "vFile:readlink", "hostio-readlink", 0);
12052
12053 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12054 "vAttach", "attach", 0);
12055
12056 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12057 "vRun", "run", 0);
12058
12059 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12060 "QStartNoAckMode", "noack", 0);
12061
12062 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12063 "vKill", "kill", 0);
12064
12065 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12066 "qAttached", "query-attached", 0);
12067
12068 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12069 "ConditionalTracepoints",
12070 "conditional-tracepoints", 0);
12071
12072 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12073 "ConditionalBreakpoints",
12074 "conditional-breakpoints", 0);
12075
12076 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12077 "BreakpointCommands",
12078 "breakpoint-commands", 0);
12079
12080 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12081 "FastTracepoints", "fast-tracepoints", 0);
12082
12083 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12084 "TracepointSource", "TracepointSource", 0);
12085
12086 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12087 "QAllow", "allow", 0);
12088
12089 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12090 "StaticTracepoints", "static-tracepoints", 0);
12091
12092 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12093 "InstallInTrace", "install-in-trace", 0);
12094
12095 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12096 "qXfer:statictrace:read", "read-sdata-object", 0);
12097
12098 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12099 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12100
12101 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12102 "QDisableRandomization", "disable-randomization", 0);
12103
12104 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12105 "QAgent", "agent", 0);
12106
12107 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12108 "QTBuffer:size", "trace-buffer-size", 0);
12109
12110 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12111 "Qbtrace:off", "disable-btrace", 0);
12112
12113 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12114 "Qbtrace:bts", "enable-btrace", 0);
12115
12116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12117 "qXfer:btrace", "read-btrace", 0);
12118
12119 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12120 Z sub-packet has its own set and show commands, but users may
12121 have sets to this variable in their .gdbinit files (or in their
12122 documentation). */
12123 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12124 &remote_Z_packet_detect, _("\
12125 Set use of remote protocol `Z' packets"), _("\
12126 Show use of remote protocol `Z' packets "), _("\
12127 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12128 packets."),
12129 set_remote_protocol_Z_packet_cmd,
12130 show_remote_protocol_Z_packet_cmd,
12131 /* FIXME: i18n: Use of remote protocol
12132 `Z' packets is %s. */
12133 &remote_set_cmdlist, &remote_show_cmdlist);
12134
12135 add_prefix_cmd ("remote", class_files, remote_command, _("\
12136 Manipulate files on the remote system\n\
12137 Transfer files to and from the remote target system."),
12138 &remote_cmdlist, "remote ",
12139 0 /* allow-unknown */, &cmdlist);
12140
12141 add_cmd ("put", class_files, remote_put_command,
12142 _("Copy a local file to the remote system."),
12143 &remote_cmdlist);
12144
12145 add_cmd ("get", class_files, remote_get_command,
12146 _("Copy a remote file to the local system."),
12147 &remote_cmdlist);
12148
12149 add_cmd ("delete", class_files, remote_delete_command,
12150 _("Delete a remote file."),
12151 &remote_cmdlist);
12152
12153 remote_exec_file = xstrdup ("");
12154 add_setshow_string_noescape_cmd ("exec-file", class_files,
12155 &remote_exec_file, _("\
12156 Set the remote pathname for \"run\""), _("\
12157 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12158 &remote_set_cmdlist, &remote_show_cmdlist);
12159
12160 add_setshow_boolean_cmd ("range-stepping", class_run,
12161 &use_range_stepping, _("\
12162 Enable or disable range stepping."), _("\
12163 Show whether target-assisted range stepping is enabled."), _("\
12164 If on, and the target supports it, when stepping a source line, GDB\n\
12165 tells the target to step the corresponding range of addresses itself instead\n\
12166 of issuing multiple single-steps. This speeds up source level\n\
12167 stepping. If off, GDB always issues single-steps, even if range\n\
12168 stepping is supported by the target. The default is on."),
12169 set_range_stepping,
12170 show_range_stepping,
12171 &setlist,
12172 &showlist);
12173
12174 /* Eventually initialize fileio. See fileio.c */
12175 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12176
12177 /* Take advantage of the fact that the LWP field is not used, to tag
12178 special ptids with it set to != 0. */
12179 magic_null_ptid = ptid_build (42000, 1, -1);
12180 not_sent_ptid = ptid_build (42000, 1, -2);
12181 any_thread_ptid = ptid_build (42000, 1, 0);
12182
12183 target_buf_size = 2048;
12184 target_buf = xmalloc (target_buf_size);
12185 }
12186