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