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