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