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