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