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