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