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