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