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