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