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