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