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