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