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