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