40e1460473ef789370f7b789b19a2a9bc5ff4c43
[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 remote_support_xml = reconcat (remote_support_xml,
3527 remote_support_xml, ",", xml,
3528 (char *) NULL);
3529 }
3530 #endif
3531 }
3532
3533 static char *
3534 remote_query_supported_append (char *msg, const char *append)
3535 {
3536 if (msg)
3537 return reconcat (msg, msg, ";", append, (char *) NULL);
3538 else
3539 return xstrdup (append);
3540 }
3541
3542 static void
3543 remote_query_supported (void)
3544 {
3545 struct remote_state *rs = get_remote_state ();
3546 char *next;
3547 int i;
3548 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3549
3550 /* The packet support flags are handled differently for this packet
3551 than for most others. We treat an error, a disabled packet, and
3552 an empty response identically: any features which must be reported
3553 to be used will be automatically disabled. An empty buffer
3554 accomplishes this, since that is also the representation for a list
3555 containing no features. */
3556
3557 rs->buf[0] = 0;
3558 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
3559 {
3560 char *q = NULL;
3561 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
3562
3563 if (rs->extended)
3564 q = remote_query_supported_append (q, "multiprocess+");
3565
3566 if (remote_support_xml)
3567 q = remote_query_supported_append (q, remote_support_xml);
3568
3569 if (q)
3570 {
3571 q = reconcat (q, "qSupported:", q, (char *) NULL);
3572 putpkt (q);
3573 }
3574 else
3575 putpkt ("qSupported");
3576
3577 do_cleanups (old_chain);
3578
3579 getpkt (&rs->buf, &rs->buf_size, 0);
3580
3581 /* If an error occured, warn, but do not return - just reset the
3582 buffer to empty and go on to disable features. */
3583 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
3584 == PACKET_ERROR)
3585 {
3586 warning (_("Remote failure reply: %s"), rs->buf);
3587 rs->buf[0] = 0;
3588 }
3589 }
3590
3591 memset (seen, 0, sizeof (seen));
3592
3593 next = rs->buf;
3594 while (*next)
3595 {
3596 enum packet_support is_supported;
3597 char *p, *end, *name_end, *value;
3598
3599 /* First separate out this item from the rest of the packet. If
3600 there's another item after this, we overwrite the separator
3601 (terminated strings are much easier to work with). */
3602 p = next;
3603 end = strchr (p, ';');
3604 if (end == NULL)
3605 {
3606 end = p + strlen (p);
3607 next = end;
3608 }
3609 else
3610 {
3611 *end = '\0';
3612 next = end + 1;
3613
3614 if (end == p)
3615 {
3616 warning (_("empty item in \"qSupported\" response"));
3617 continue;
3618 }
3619 }
3620
3621 name_end = strchr (p, '=');
3622 if (name_end)
3623 {
3624 /* This is a name=value entry. */
3625 is_supported = PACKET_ENABLE;
3626 value = name_end + 1;
3627 *name_end = '\0';
3628 }
3629 else
3630 {
3631 value = NULL;
3632 switch (end[-1])
3633 {
3634 case '+':
3635 is_supported = PACKET_ENABLE;
3636 break;
3637
3638 case '-':
3639 is_supported = PACKET_DISABLE;
3640 break;
3641
3642 case '?':
3643 is_supported = PACKET_SUPPORT_UNKNOWN;
3644 break;
3645
3646 default:
3647 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
3648 continue;
3649 }
3650 end[-1] = '\0';
3651 }
3652
3653 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3654 if (strcmp (remote_protocol_features[i].name, p) == 0)
3655 {
3656 const struct protocol_feature *feature;
3657
3658 seen[i] = 1;
3659 feature = &remote_protocol_features[i];
3660 feature->func (feature, is_supported, value);
3661 break;
3662 }
3663 }
3664
3665 /* If we increased the packet size, make sure to increase the global
3666 buffer size also. We delay this until after parsing the entire
3667 qSupported packet, because this is the same buffer we were
3668 parsing. */
3669 if (rs->buf_size < rs->explicit_packet_size)
3670 {
3671 rs->buf_size = rs->explicit_packet_size;
3672 rs->buf = xrealloc (rs->buf, rs->buf_size);
3673 }
3674
3675 /* Handle the defaults for unmentioned features. */
3676 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3677 if (!seen[i])
3678 {
3679 const struct protocol_feature *feature;
3680
3681 feature = &remote_protocol_features[i];
3682 feature->func (feature, feature->default_support, NULL);
3683 }
3684 }
3685
3686
3687 static void
3688 remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
3689 {
3690 struct remote_state *rs = get_remote_state ();
3691
3692 if (name == 0)
3693 error (_("To open a remote debug connection, you need to specify what\n"
3694 "serial device is attached to the remote system\n"
3695 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
3696
3697 /* See FIXME above. */
3698 if (!target_async_permitted)
3699 wait_forever_enabled_p = 1;
3700
3701 /* If we're connected to a running target, target_preopen will kill it.
3702 But if we're connected to a target system with no running process,
3703 then we will still be connected when it returns. Ask this question
3704 first, before target_preopen has a chance to kill anything. */
3705 if (remote_desc != NULL && !have_inferiors ())
3706 {
3707 if (!from_tty
3708 || query (_("Already connected to a remote target. Disconnect? ")))
3709 pop_target ();
3710 else
3711 error (_("Still connected."));
3712 }
3713
3714 target_preopen (from_tty);
3715
3716 unpush_target (target);
3717
3718 /* This time without a query. If we were connected to an
3719 extended-remote target and target_preopen killed the running
3720 process, we may still be connected. If we are starting "target
3721 remote" now, the extended-remote target will not have been
3722 removed by unpush_target. */
3723 if (remote_desc != NULL && !have_inferiors ())
3724 pop_target ();
3725
3726 /* Make sure we send the passed signals list the next time we resume. */
3727 xfree (last_pass_packet);
3728 last_pass_packet = NULL;
3729
3730 remote_fileio_reset ();
3731 reopen_exec_file ();
3732 reread_symbols ();
3733
3734 remote_desc = remote_serial_open (name);
3735 if (!remote_desc)
3736 perror_with_name (name);
3737
3738 if (baud_rate != -1)
3739 {
3740 if (serial_setbaudrate (remote_desc, baud_rate))
3741 {
3742 /* The requested speed could not be set. Error out to
3743 top level after closing remote_desc. Take care to
3744 set remote_desc to NULL to avoid closing remote_desc
3745 more than once. */
3746 serial_close (remote_desc);
3747 remote_desc = NULL;
3748 perror_with_name (name);
3749 }
3750 }
3751
3752 serial_raw (remote_desc);
3753
3754 /* If there is something sitting in the buffer we might take it as a
3755 response to a command, which would be bad. */
3756 serial_flush_input (remote_desc);
3757
3758 if (from_tty)
3759 {
3760 puts_filtered ("Remote debugging using ");
3761 puts_filtered (name);
3762 puts_filtered ("\n");
3763 }
3764 push_target (target); /* Switch to using remote target now. */
3765
3766 /* Register extra event sources in the event loop. */
3767 remote_async_inferior_event_token
3768 = create_async_event_handler (remote_async_inferior_event_handler,
3769 NULL);
3770 remote_async_get_pending_events_token
3771 = create_async_event_handler (remote_async_get_pending_events_handler,
3772 NULL);
3773
3774 /* Reset the target state; these things will be queried either by
3775 remote_query_supported or as they are needed. */
3776 init_all_packet_configs ();
3777 rs->cached_wait_status = 0;
3778 rs->explicit_packet_size = 0;
3779 rs->noack_mode = 0;
3780 rs->multi_process_aware = 0;
3781 rs->extended = extended_p;
3782 rs->non_stop_aware = 0;
3783 rs->waiting_for_stop_reply = 0;
3784 rs->ctrlc_pending_p = 0;
3785
3786 general_thread = not_sent_ptid;
3787 continue_thread = not_sent_ptid;
3788
3789 /* Probe for ability to use "ThreadInfo" query, as required. */
3790 use_threadinfo_query = 1;
3791 use_threadextra_query = 1;
3792
3793 if (target_async_permitted)
3794 {
3795 /* With this target we start out by owning the terminal. */
3796 remote_async_terminal_ours_p = 1;
3797
3798 /* FIXME: cagney/1999-09-23: During the initial connection it is
3799 assumed that the target is already ready and able to respond to
3800 requests. Unfortunately remote_start_remote() eventually calls
3801 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
3802 around this. Eventually a mechanism that allows
3803 wait_for_inferior() to expect/get timeouts will be
3804 implemented. */
3805 wait_forever_enabled_p = 0;
3806 }
3807
3808 /* First delete any symbols previously loaded from shared libraries. */
3809 no_shared_libraries (NULL, 0);
3810
3811 /* Start afresh. */
3812 init_thread_list ();
3813
3814 /* Start the remote connection. If error() or QUIT, discard this
3815 target (we'd otherwise be in an inconsistent state) and then
3816 propogate the error on up the exception chain. This ensures that
3817 the caller doesn't stumble along blindly assuming that the
3818 function succeeded. The CLI doesn't have this problem but other
3819 UI's, such as MI do.
3820
3821 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
3822 this function should return an error indication letting the
3823 caller restore the previous state. Unfortunately the command
3824 ``target remote'' is directly wired to this function making that
3825 impossible. On a positive note, the CLI side of this problem has
3826 been fixed - the function set_cmd_context() makes it possible for
3827 all the ``target ....'' commands to share a common callback
3828 function. See cli-dump.c. */
3829 {
3830 struct gdb_exception ex;
3831 struct start_remote_args args;
3832
3833 args.from_tty = from_tty;
3834 args.target = target;
3835 args.extended_p = extended_p;
3836
3837 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
3838 if (ex.reason < 0)
3839 {
3840 /* Pop the partially set up target - unless something else did
3841 already before throwing the exception. */
3842 if (remote_desc != NULL)
3843 pop_target ();
3844 if (target_async_permitted)
3845 wait_forever_enabled_p = 1;
3846 throw_exception (ex);
3847 }
3848 }
3849
3850 if (target_async_permitted)
3851 wait_forever_enabled_p = 1;
3852 }
3853
3854 /* This takes a program previously attached to and detaches it. After
3855 this is done, GDB can be used to debug some other program. We
3856 better not have left any breakpoints in the target program or it'll
3857 die when it hits one. */
3858
3859 static void
3860 remote_detach_1 (char *args, int from_tty, int extended)
3861 {
3862 int pid = ptid_get_pid (inferior_ptid);
3863 struct remote_state *rs = get_remote_state ();
3864
3865 if (args)
3866 error (_("Argument given to \"detach\" when remotely debugging."));
3867
3868 if (!target_has_execution)
3869 error (_("No process to detach from."));
3870
3871 /* Tell the remote target to detach. */
3872 if (remote_multi_process_p (rs))
3873 sprintf (rs->buf, "D;%x", pid);
3874 else
3875 strcpy (rs->buf, "D");
3876
3877 putpkt (rs->buf);
3878 getpkt (&rs->buf, &rs->buf_size, 0);
3879
3880 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
3881 ;
3882 else if (rs->buf[0] == '\0')
3883 error (_("Remote doesn't know how to detach"));
3884 else
3885 error (_("Can't detach process."));
3886
3887 if (from_tty)
3888 {
3889 if (remote_multi_process_p (rs))
3890 printf_filtered (_("Detached from remote %s.\n"),
3891 target_pid_to_str (pid_to_ptid (pid)));
3892 else
3893 {
3894 if (extended)
3895 puts_filtered (_("Detached from remote process.\n"));
3896 else
3897 puts_filtered (_("Ending remote debugging.\n"));
3898 }
3899 }
3900
3901 discard_pending_stop_replies (pid);
3902 target_mourn_inferior ();
3903 }
3904
3905 static void
3906 remote_detach (struct target_ops *ops, char *args, int from_tty)
3907 {
3908 remote_detach_1 (args, from_tty, 0);
3909 }
3910
3911 static void
3912 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
3913 {
3914 remote_detach_1 (args, from_tty, 1);
3915 }
3916
3917 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
3918
3919 static void
3920 remote_disconnect (struct target_ops *target, char *args, int from_tty)
3921 {
3922 if (args)
3923 error (_("Argument given to \"disconnect\" when remotely debugging."));
3924
3925 /* Make sure we unpush even the extended remote targets; mourn
3926 won't do it. So call remote_mourn_1 directly instead of
3927 target_mourn_inferior. */
3928 remote_mourn_1 (target);
3929
3930 if (from_tty)
3931 puts_filtered ("Ending remote debugging.\n");
3932 }
3933
3934 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
3935 be chatty about it. */
3936
3937 static void
3938 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
3939 {
3940 struct remote_state *rs = get_remote_state ();
3941 int pid;
3942 char *wait_status = NULL;
3943
3944 pid = parse_pid_to_attach (args);
3945
3946 /* Remote PID can be freely equal to getpid, do not check it here the same
3947 way as in other targets. */
3948
3949 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3950 error (_("This target does not support attaching to a process"));
3951
3952 sprintf (rs->buf, "vAttach;%x", pid);
3953 putpkt (rs->buf);
3954 getpkt (&rs->buf, &rs->buf_size, 0);
3955
3956 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
3957 {
3958 if (from_tty)
3959 printf_unfiltered (_("Attached to %s\n"),
3960 target_pid_to_str (pid_to_ptid (pid)));
3961
3962 if (!non_stop)
3963 {
3964 /* Save the reply for later. */
3965 wait_status = alloca (strlen (rs->buf) + 1);
3966 strcpy (wait_status, rs->buf);
3967 }
3968 else if (strcmp (rs->buf, "OK") != 0)
3969 error (_("Attaching to %s failed with: %s"),
3970 target_pid_to_str (pid_to_ptid (pid)),
3971 rs->buf);
3972 }
3973 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3974 error (_("This target does not support attaching to a process"));
3975 else
3976 error (_("Attaching to %s failed"),
3977 target_pid_to_str (pid_to_ptid (pid)));
3978
3979 set_current_inferior (remote_add_inferior (pid, 1));
3980
3981 inferior_ptid = pid_to_ptid (pid);
3982
3983 if (non_stop)
3984 {
3985 struct thread_info *thread;
3986
3987 /* Get list of threads. */
3988 remote_threads_info (target);
3989
3990 thread = first_thread_of_process (pid);
3991 if (thread)
3992 inferior_ptid = thread->ptid;
3993 else
3994 inferior_ptid = pid_to_ptid (pid);
3995
3996 /* Invalidate our notion of the remote current thread. */
3997 record_currthread (minus_one_ptid);
3998 }
3999 else
4000 {
4001 /* Now, if we have thread information, update inferior_ptid. */
4002 inferior_ptid = remote_current_thread (inferior_ptid);
4003
4004 /* Add the main thread to the thread list. */
4005 add_thread_silent (inferior_ptid);
4006 }
4007
4008 /* Next, if the target can specify a description, read it. We do
4009 this before anything involving memory or registers. */
4010 target_find_description ();
4011
4012 if (!non_stop)
4013 {
4014 /* Use the previously fetched status. */
4015 gdb_assert (wait_status != NULL);
4016
4017 if (target_can_async_p ())
4018 {
4019 struct stop_reply *stop_reply;
4020 struct cleanup *old_chain;
4021
4022 stop_reply = stop_reply_xmalloc ();
4023 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4024 remote_parse_stop_reply (wait_status, stop_reply);
4025 discard_cleanups (old_chain);
4026 push_stop_reply (stop_reply);
4027
4028 target_async (inferior_event_handler, 0);
4029 }
4030 else
4031 {
4032 gdb_assert (wait_status != NULL);
4033 strcpy (rs->buf, wait_status);
4034 rs->cached_wait_status = 1;
4035 }
4036 }
4037 else
4038 gdb_assert (wait_status == NULL);
4039 }
4040
4041 static void
4042 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4043 {
4044 extended_remote_attach_1 (ops, args, from_tty);
4045 }
4046
4047 /* Convert hex digit A to a number. */
4048
4049 static int
4050 fromhex (int a)
4051 {
4052 if (a >= '0' && a <= '9')
4053 return a - '0';
4054 else if (a >= 'a' && a <= 'f')
4055 return a - 'a' + 10;
4056 else if (a >= 'A' && a <= 'F')
4057 return a - 'A' + 10;
4058 else
4059 error (_("Reply contains invalid hex digit %d"), a);
4060 }
4061
4062 int
4063 hex2bin (const char *hex, gdb_byte *bin, int count)
4064 {
4065 int i;
4066
4067 for (i = 0; i < count; i++)
4068 {
4069 if (hex[0] == 0 || hex[1] == 0)
4070 {
4071 /* Hex string is short, or of uneven length.
4072 Return the count that has been converted so far. */
4073 return i;
4074 }
4075 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4076 hex += 2;
4077 }
4078 return i;
4079 }
4080
4081 /* Convert number NIB to a hex digit. */
4082
4083 static int
4084 tohex (int nib)
4085 {
4086 if (nib < 10)
4087 return '0' + nib;
4088 else
4089 return 'a' + nib - 10;
4090 }
4091
4092 int
4093 bin2hex (const gdb_byte *bin, char *hex, int count)
4094 {
4095 int i;
4096 /* May use a length, or a nul-terminated string as input. */
4097 if (count == 0)
4098 count = strlen ((char *) bin);
4099
4100 for (i = 0; i < count; i++)
4101 {
4102 *hex++ = tohex ((*bin >> 4) & 0xf);
4103 *hex++ = tohex (*bin++ & 0xf);
4104 }
4105 *hex = 0;
4106 return i;
4107 }
4108 \f
4109 /* Check for the availability of vCont. This function should also check
4110 the response. */
4111
4112 static void
4113 remote_vcont_probe (struct remote_state *rs)
4114 {
4115 char *buf;
4116
4117 strcpy (rs->buf, "vCont?");
4118 putpkt (rs->buf);
4119 getpkt (&rs->buf, &rs->buf_size, 0);
4120 buf = rs->buf;
4121
4122 /* Make sure that the features we assume are supported. */
4123 if (strncmp (buf, "vCont", 5) == 0)
4124 {
4125 char *p = &buf[5];
4126 int support_s, support_S, support_c, support_C;
4127
4128 support_s = 0;
4129 support_S = 0;
4130 support_c = 0;
4131 support_C = 0;
4132 rs->support_vCont_t = 0;
4133 while (p && *p == ';')
4134 {
4135 p++;
4136 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4137 support_s = 1;
4138 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4139 support_S = 1;
4140 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4141 support_c = 1;
4142 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4143 support_C = 1;
4144 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4145 rs->support_vCont_t = 1;
4146
4147 p = strchr (p, ';');
4148 }
4149
4150 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4151 BUF will make packet_ok disable the packet. */
4152 if (!support_s || !support_S || !support_c || !support_C)
4153 buf[0] = 0;
4154 }
4155
4156 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4157 }
4158
4159 /* Helper function for building "vCont" resumptions. Write a
4160 resumption to P. ENDP points to one-passed-the-end of the buffer
4161 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4162 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4163 resumed thread should be single-stepped and/or signalled. If PTID
4164 equals minus_one_ptid, then all threads are resumed; if PTID
4165 represents a process, then all threads of the process are resumed;
4166 the thread to be stepped and/or signalled is given in the global
4167 INFERIOR_PTID. */
4168
4169 static char *
4170 append_resumption (char *p, char *endp,
4171 ptid_t ptid, int step, enum target_signal siggnal)
4172 {
4173 struct remote_state *rs = get_remote_state ();
4174
4175 if (step && siggnal != TARGET_SIGNAL_0)
4176 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4177 else if (step)
4178 p += xsnprintf (p, endp - p, ";s");
4179 else if (siggnal != TARGET_SIGNAL_0)
4180 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4181 else
4182 p += xsnprintf (p, endp - p, ";c");
4183
4184 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4185 {
4186 ptid_t nptid;
4187
4188 /* All (-1) threads of process. */
4189 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4190
4191 p += xsnprintf (p, endp - p, ":");
4192 p = write_ptid (p, endp, nptid);
4193 }
4194 else if (!ptid_equal (ptid, minus_one_ptid))
4195 {
4196 p += xsnprintf (p, endp - p, ":");
4197 p = write_ptid (p, endp, ptid);
4198 }
4199
4200 return p;
4201 }
4202
4203 /* Resume the remote inferior by using a "vCont" packet. The thread
4204 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4205 resumed thread should be single-stepped and/or signalled. If PTID
4206 equals minus_one_ptid, then all threads are resumed; the thread to
4207 be stepped and/or signalled is given in the global INFERIOR_PTID.
4208 This function returns non-zero iff it resumes the inferior.
4209
4210 This function issues a strict subset of all possible vCont commands at the
4211 moment. */
4212
4213 static int
4214 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
4215 {
4216 struct remote_state *rs = get_remote_state ();
4217 char *p;
4218 char *endp;
4219
4220 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4221 remote_vcont_probe (rs);
4222
4223 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4224 return 0;
4225
4226 p = rs->buf;
4227 endp = rs->buf + get_remote_packet_size ();
4228
4229 /* If we could generate a wider range of packets, we'd have to worry
4230 about overflowing BUF. Should there be a generic
4231 "multi-part-packet" packet? */
4232
4233 p += xsnprintf (p, endp - p, "vCont");
4234
4235 if (ptid_equal (ptid, magic_null_ptid))
4236 {
4237 /* MAGIC_NULL_PTID means that we don't have any active threads,
4238 so we don't have any TID numbers the inferior will
4239 understand. Make sure to only send forms that do not specify
4240 a TID. */
4241 p = append_resumption (p, endp, minus_one_ptid, step, siggnal);
4242 }
4243 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4244 {
4245 /* Resume all threads (of all processes, or of a single
4246 process), with preference for INFERIOR_PTID. This assumes
4247 inferior_ptid belongs to the set of all threads we are about
4248 to resume. */
4249 if (step || siggnal != TARGET_SIGNAL_0)
4250 {
4251 /* Step inferior_ptid, with or without signal. */
4252 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4253 }
4254
4255 /* And continue others without a signal. */
4256 p = append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
4257 }
4258 else
4259 {
4260 /* Scheduler locking; resume only PTID. */
4261 p = append_resumption (p, endp, ptid, step, siggnal);
4262 }
4263
4264 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4265 putpkt (rs->buf);
4266
4267 if (non_stop)
4268 {
4269 /* In non-stop, the stub replies to vCont with "OK". The stop
4270 reply will be reported asynchronously by means of a `%Stop'
4271 notification. */
4272 getpkt (&rs->buf, &rs->buf_size, 0);
4273 if (strcmp (rs->buf, "OK") != 0)
4274 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4275 }
4276
4277 return 1;
4278 }
4279
4280 /* Tell the remote machine to resume. */
4281
4282 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
4283
4284 static int last_sent_step;
4285
4286 static void
4287 remote_resume (struct target_ops *ops,
4288 ptid_t ptid, int step, enum target_signal siggnal)
4289 {
4290 struct remote_state *rs = get_remote_state ();
4291 char *buf;
4292
4293 last_sent_signal = siggnal;
4294 last_sent_step = step;
4295
4296 /* Update the inferior on signals to silently pass, if they've changed. */
4297 remote_pass_signals ();
4298
4299 /* The vCont packet doesn't need to specify threads via Hc. */
4300 /* No reverse support (yet) for vCont. */
4301 if (execution_direction != EXEC_REVERSE)
4302 if (remote_vcont_resume (ptid, step, siggnal))
4303 goto done;
4304
4305 /* All other supported resume packets do use Hc, so set the continue
4306 thread. */
4307 if (ptid_equal (ptid, minus_one_ptid))
4308 set_continue_thread (any_thread_ptid);
4309 else
4310 set_continue_thread (ptid);
4311
4312 buf = rs->buf;
4313 if (execution_direction == EXEC_REVERSE)
4314 {
4315 /* We don't pass signals to the target in reverse exec mode. */
4316 if (info_verbose && siggnal != TARGET_SIGNAL_0)
4317 warning (" - Can't pass signal %d to target in reverse: ignored.\n",
4318 siggnal);
4319
4320 if (step
4321 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4322 error (_("Remote reverse-step not supported."));
4323 if (!step
4324 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4325 error (_("Remote reverse-continue not supported."));
4326
4327 strcpy (buf, step ? "bs" : "bc");
4328 }
4329 else if (siggnal != TARGET_SIGNAL_0)
4330 {
4331 buf[0] = step ? 'S' : 'C';
4332 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4333 buf[2] = tohex (((int) siggnal) & 0xf);
4334 buf[3] = '\0';
4335 }
4336 else
4337 strcpy (buf, step ? "s" : "c");
4338
4339 putpkt (buf);
4340
4341 done:
4342 /* We are about to start executing the inferior, let's register it
4343 with the event loop. NOTE: this is the one place where all the
4344 execution commands end up. We could alternatively do this in each
4345 of the execution commands in infcmd.c. */
4346 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4347 into infcmd.c in order to allow inferior function calls to work
4348 NOT asynchronously. */
4349 if (target_can_async_p ())
4350 target_async (inferior_event_handler, 0);
4351
4352 /* We've just told the target to resume. The remote server will
4353 wait for the inferior to stop, and then send a stop reply. In
4354 the mean time, we can't start another command/query ourselves
4355 because the stub wouldn't be ready to process it. This applies
4356 only to the base all-stop protocol, however. In non-stop (which
4357 only supports vCont), the stub replies with an "OK", and is
4358 immediate able to process further serial input. */
4359 if (!non_stop)
4360 rs->waiting_for_stop_reply = 1;
4361 }
4362 \f
4363
4364 /* Set up the signal handler for SIGINT, while the target is
4365 executing, ovewriting the 'regular' SIGINT signal handler. */
4366 static void
4367 initialize_sigint_signal_handler (void)
4368 {
4369 signal (SIGINT, handle_remote_sigint);
4370 }
4371
4372 /* Signal handler for SIGINT, while the target is executing. */
4373 static void
4374 handle_remote_sigint (int sig)
4375 {
4376 signal (sig, handle_remote_sigint_twice);
4377 mark_async_signal_handler_wrapper (sigint_remote_token);
4378 }
4379
4380 /* Signal handler for SIGINT, installed after SIGINT has already been
4381 sent once. It will take effect the second time that the user sends
4382 a ^C. */
4383 static void
4384 handle_remote_sigint_twice (int sig)
4385 {
4386 signal (sig, handle_remote_sigint);
4387 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
4388 }
4389
4390 /* Perform the real interruption of the target execution, in response
4391 to a ^C. */
4392 static void
4393 async_remote_interrupt (gdb_client_data arg)
4394 {
4395 if (remote_debug)
4396 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
4397
4398 target_stop (inferior_ptid);
4399 }
4400
4401 /* Perform interrupt, if the first attempt did not succeed. Just give
4402 up on the target alltogether. */
4403 void
4404 async_remote_interrupt_twice (gdb_client_data arg)
4405 {
4406 if (remote_debug)
4407 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
4408
4409 interrupt_query ();
4410 }
4411
4412 /* Reinstall the usual SIGINT handlers, after the target has
4413 stopped. */
4414 static void
4415 cleanup_sigint_signal_handler (void *dummy)
4416 {
4417 signal (SIGINT, handle_sigint);
4418 }
4419
4420 /* Send ^C to target to halt it. Target will respond, and send us a
4421 packet. */
4422 static void (*ofunc) (int);
4423
4424 /* The command line interface's stop routine. This function is installed
4425 as a signal handler for SIGINT. The first time a user requests a
4426 stop, we call remote_stop to send a break or ^C. If there is no
4427 response from the target (it didn't stop when the user requested it),
4428 we ask the user if he'd like to detach from the target. */
4429 static void
4430 remote_interrupt (int signo)
4431 {
4432 /* If this doesn't work, try more severe steps. */
4433 signal (signo, remote_interrupt_twice);
4434
4435 gdb_call_async_signal_handler (sigint_remote_token, 1);
4436 }
4437
4438 /* The user typed ^C twice. */
4439
4440 static void
4441 remote_interrupt_twice (int signo)
4442 {
4443 signal (signo, ofunc);
4444 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
4445 signal (signo, remote_interrupt);
4446 }
4447
4448 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4449 thread, all threads of a remote process, or all threads of all
4450 processes. */
4451
4452 static void
4453 remote_stop_ns (ptid_t ptid)
4454 {
4455 struct remote_state *rs = get_remote_state ();
4456 char *p = rs->buf;
4457 char *endp = rs->buf + get_remote_packet_size ();
4458
4459 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4460 remote_vcont_probe (rs);
4461
4462 if (!rs->support_vCont_t)
4463 error (_("Remote server does not support stopping threads"));
4464
4465 if (ptid_equal (ptid, minus_one_ptid)
4466 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4467 p += xsnprintf (p, endp - p, "vCont;t");
4468 else
4469 {
4470 ptid_t nptid;
4471
4472 p += xsnprintf (p, endp - p, "vCont;t:");
4473
4474 if (ptid_is_pid (ptid))
4475 /* All (-1) threads of process. */
4476 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4477 else
4478 {
4479 /* Small optimization: if we already have a stop reply for
4480 this thread, no use in telling the stub we want this
4481 stopped. */
4482 if (peek_stop_reply (ptid))
4483 return;
4484
4485 nptid = ptid;
4486 }
4487
4488 p = write_ptid (p, endp, nptid);
4489 }
4490
4491 /* In non-stop, we get an immediate OK reply. The stop reply will
4492 come in asynchronously by notification. */
4493 putpkt (rs->buf);
4494 getpkt (&rs->buf, &rs->buf_size, 0);
4495 if (strcmp (rs->buf, "OK") != 0)
4496 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
4497 }
4498
4499 /* All-stop version of target_stop. Sends a break or a ^C to stop the
4500 remote target. It is undefined which thread of which process
4501 reports the stop. */
4502
4503 static void
4504 remote_stop_as (ptid_t ptid)
4505 {
4506 struct remote_state *rs = get_remote_state ();
4507
4508 rs->ctrlc_pending_p = 1;
4509
4510 /* If the inferior is stopped already, but the core didn't know
4511 about it yet, just ignore the request. The cached wait status
4512 will be collected in remote_wait. */
4513 if (rs->cached_wait_status)
4514 return;
4515
4516 /* Send interrupt_sequence to remote target. */
4517 send_interrupt_sequence ();
4518 }
4519
4520 /* This is the generic stop called via the target vector. When a target
4521 interrupt is requested, either by the command line or the GUI, we
4522 will eventually end up here. */
4523
4524 static void
4525 remote_stop (ptid_t ptid)
4526 {
4527 if (remote_debug)
4528 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
4529
4530 if (non_stop)
4531 remote_stop_ns (ptid);
4532 else
4533 remote_stop_as (ptid);
4534 }
4535
4536 /* Ask the user what to do when an interrupt is received. */
4537
4538 static void
4539 interrupt_query (void)
4540 {
4541 target_terminal_ours ();
4542
4543 if (target_can_async_p ())
4544 {
4545 signal (SIGINT, handle_sigint);
4546 deprecated_throw_reason (RETURN_QUIT);
4547 }
4548 else
4549 {
4550 if (query (_("Interrupted while waiting for the program.\n\
4551 Give up (and stop debugging it)? ")))
4552 {
4553 pop_target ();
4554 deprecated_throw_reason (RETURN_QUIT);
4555 }
4556 }
4557
4558 target_terminal_inferior ();
4559 }
4560
4561 /* Enable/disable target terminal ownership. Most targets can use
4562 terminal groups to control terminal ownership. Remote targets are
4563 different in that explicit transfer of ownership to/from GDB/target
4564 is required. */
4565
4566 static void
4567 remote_terminal_inferior (void)
4568 {
4569 if (!target_async_permitted)
4570 /* Nothing to do. */
4571 return;
4572
4573 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
4574 idempotent. The event-loop GDB talking to an asynchronous target
4575 with a synchronous command calls this function from both
4576 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
4577 transfer the terminal to the target when it shouldn't this guard
4578 can go away. */
4579 if (!remote_async_terminal_ours_p)
4580 return;
4581 delete_file_handler (input_fd);
4582 remote_async_terminal_ours_p = 0;
4583 initialize_sigint_signal_handler ();
4584 /* NOTE: At this point we could also register our selves as the
4585 recipient of all input. Any characters typed could then be
4586 passed on down to the target. */
4587 }
4588
4589 static void
4590 remote_terminal_ours (void)
4591 {
4592 if (!target_async_permitted)
4593 /* Nothing to do. */
4594 return;
4595
4596 /* See FIXME in remote_terminal_inferior. */
4597 if (remote_async_terminal_ours_p)
4598 return;
4599 cleanup_sigint_signal_handler (NULL);
4600 add_file_handler (input_fd, stdin_event_handler, 0);
4601 remote_async_terminal_ours_p = 1;
4602 }
4603
4604 void
4605 remote_console_output (char *msg)
4606 {
4607 char *p;
4608
4609 for (p = msg; p[0] && p[1]; p += 2)
4610 {
4611 char tb[2];
4612 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
4613 tb[0] = c;
4614 tb[1] = 0;
4615 fputs_unfiltered (tb, gdb_stdtarg);
4616 }
4617 gdb_flush (gdb_stdtarg);
4618 }
4619
4620 typedef struct cached_reg
4621 {
4622 int num;
4623 gdb_byte data[MAX_REGISTER_SIZE];
4624 } cached_reg_t;
4625
4626 DEF_VEC_O(cached_reg_t);
4627
4628 struct stop_reply
4629 {
4630 struct stop_reply *next;
4631
4632 ptid_t ptid;
4633
4634 struct target_waitstatus ws;
4635
4636 VEC(cached_reg_t) *regcache;
4637
4638 int stopped_by_watchpoint_p;
4639 CORE_ADDR watch_data_address;
4640
4641 int solibs_changed;
4642 int replay_event;
4643
4644 int core;
4645 };
4646
4647 /* The list of already fetched and acknowledged stop events. */
4648 static struct stop_reply *stop_reply_queue;
4649
4650 static struct stop_reply *
4651 stop_reply_xmalloc (void)
4652 {
4653 struct stop_reply *r = XMALLOC (struct stop_reply);
4654 r->next = NULL;
4655 return r;
4656 }
4657
4658 static void
4659 stop_reply_xfree (struct stop_reply *r)
4660 {
4661 if (r != NULL)
4662 {
4663 VEC_free (cached_reg_t, r->regcache);
4664 xfree (r);
4665 }
4666 }
4667
4668 /* Discard all pending stop replies of inferior PID. If PID is -1,
4669 discard everything. */
4670
4671 static void
4672 discard_pending_stop_replies (int pid)
4673 {
4674 struct stop_reply *prev = NULL, *reply, *next;
4675
4676 /* Discard the in-flight notification. */
4677 if (pending_stop_reply != NULL
4678 && (pid == -1
4679 || ptid_get_pid (pending_stop_reply->ptid) == pid))
4680 {
4681 stop_reply_xfree (pending_stop_reply);
4682 pending_stop_reply = NULL;
4683 }
4684
4685 /* Discard the stop replies we have already pulled with
4686 vStopped. */
4687 for (reply = stop_reply_queue; reply; reply = next)
4688 {
4689 next = reply->next;
4690 if (pid == -1
4691 || ptid_get_pid (reply->ptid) == pid)
4692 {
4693 if (reply == stop_reply_queue)
4694 stop_reply_queue = reply->next;
4695 else
4696 prev->next = reply->next;
4697
4698 stop_reply_xfree (reply);
4699 }
4700 else
4701 prev = reply;
4702 }
4703 }
4704
4705 /* Cleanup wrapper. */
4706
4707 static void
4708 do_stop_reply_xfree (void *arg)
4709 {
4710 struct stop_reply *r = arg;
4711 stop_reply_xfree (r);
4712 }
4713
4714 /* Look for a queued stop reply belonging to PTID. If one is found,
4715 remove it from the queue, and return it. Returns NULL if none is
4716 found. If there are still queued events left to process, tell the
4717 event loop to get back to target_wait soon. */
4718
4719 static struct stop_reply *
4720 queued_stop_reply (ptid_t ptid)
4721 {
4722 struct stop_reply *it;
4723 struct stop_reply **it_link;
4724
4725 it = stop_reply_queue;
4726 it_link = &stop_reply_queue;
4727 while (it)
4728 {
4729 if (ptid_match (it->ptid, ptid))
4730 {
4731 *it_link = it->next;
4732 it->next = NULL;
4733 break;
4734 }
4735
4736 it_link = &it->next;
4737 it = *it_link;
4738 }
4739
4740 if (stop_reply_queue)
4741 /* There's still at least an event left. */
4742 mark_async_event_handler (remote_async_inferior_event_token);
4743
4744 return it;
4745 }
4746
4747 /* Push a fully parsed stop reply in the stop reply queue. Since we
4748 know that we now have at least one queued event left to pass to the
4749 core side, tell the event loop to get back to target_wait soon. */
4750
4751 static void
4752 push_stop_reply (struct stop_reply *new_event)
4753 {
4754 struct stop_reply *event;
4755
4756 if (stop_reply_queue)
4757 {
4758 for (event = stop_reply_queue;
4759 event && event->next;
4760 event = event->next)
4761 ;
4762
4763 event->next = new_event;
4764 }
4765 else
4766 stop_reply_queue = new_event;
4767
4768 mark_async_event_handler (remote_async_inferior_event_token);
4769 }
4770
4771 /* Returns true if we have a stop reply for PTID. */
4772
4773 static int
4774 peek_stop_reply (ptid_t ptid)
4775 {
4776 struct stop_reply *it;
4777
4778 for (it = stop_reply_queue; it; it = it->next)
4779 if (ptid_equal (ptid, it->ptid))
4780 {
4781 if (it->ws.kind == TARGET_WAITKIND_STOPPED)
4782 return 1;
4783 }
4784
4785 return 0;
4786 }
4787
4788 /* Parse the stop reply in BUF. Either the function succeeds, and the
4789 result is stored in EVENT, or throws an error. */
4790
4791 static void
4792 remote_parse_stop_reply (char *buf, struct stop_reply *event)
4793 {
4794 struct remote_arch_state *rsa = get_remote_arch_state ();
4795 ULONGEST addr;
4796 char *p;
4797
4798 event->ptid = null_ptid;
4799 event->ws.kind = TARGET_WAITKIND_IGNORE;
4800 event->ws.value.integer = 0;
4801 event->solibs_changed = 0;
4802 event->replay_event = 0;
4803 event->stopped_by_watchpoint_p = 0;
4804 event->regcache = NULL;
4805 event->core = -1;
4806
4807 switch (buf[0])
4808 {
4809 case 'T': /* Status with PC, SP, FP, ... */
4810 /* Expedited reply, containing Signal, {regno, reg} repeat. */
4811 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
4812 ss = signal number
4813 n... = register number
4814 r... = register contents
4815 */
4816
4817 p = &buf[3]; /* after Txx */
4818 while (*p)
4819 {
4820 char *p1;
4821 char *p_temp;
4822 int fieldsize;
4823 LONGEST pnum = 0;
4824
4825 /* If the packet contains a register number, save it in
4826 pnum and set p1 to point to the character following it.
4827 Otherwise p1 points to p. */
4828
4829 /* If this packet is an awatch packet, don't parse the 'a'
4830 as a register number. */
4831
4832 if (strncmp (p, "awatch", strlen("awatch")) != 0
4833 && strncmp (p, "core", strlen ("core") != 0))
4834 {
4835 /* Read the ``P'' register number. */
4836 pnum = strtol (p, &p_temp, 16);
4837 p1 = p_temp;
4838 }
4839 else
4840 p1 = p;
4841
4842 if (p1 == p) /* No register number present here. */
4843 {
4844 p1 = strchr (p, ':');
4845 if (p1 == NULL)
4846 error (_("Malformed packet(a) (missing colon): %s\n\
4847 Packet: '%s'\n"),
4848 p, buf);
4849 if (strncmp (p, "thread", p1 - p) == 0)
4850 event->ptid = read_ptid (++p1, &p);
4851 else if ((strncmp (p, "watch", p1 - p) == 0)
4852 || (strncmp (p, "rwatch", p1 - p) == 0)
4853 || (strncmp (p, "awatch", p1 - p) == 0))
4854 {
4855 event->stopped_by_watchpoint_p = 1;
4856 p = unpack_varlen_hex (++p1, &addr);
4857 event->watch_data_address = (CORE_ADDR) addr;
4858 }
4859 else if (strncmp (p, "library", p1 - p) == 0)
4860 {
4861 p1++;
4862 p_temp = p1;
4863 while (*p_temp && *p_temp != ';')
4864 p_temp++;
4865
4866 event->solibs_changed = 1;
4867 p = p_temp;
4868 }
4869 else if (strncmp (p, "replaylog", p1 - p) == 0)
4870 {
4871 /* NO_HISTORY event.
4872 p1 will indicate "begin" or "end", but
4873 it makes no difference for now, so ignore it. */
4874 event->replay_event = 1;
4875 p_temp = strchr (p1 + 1, ';');
4876 if (p_temp)
4877 p = p_temp;
4878 }
4879 else if (strncmp (p, "core", p1 - p) == 0)
4880 {
4881 ULONGEST c;
4882 p = unpack_varlen_hex (++p1, &c);
4883 event->core = c;
4884 }
4885 else
4886 {
4887 /* Silently skip unknown optional info. */
4888 p_temp = strchr (p1 + 1, ';');
4889 if (p_temp)
4890 p = p_temp;
4891 }
4892 }
4893 else
4894 {
4895 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
4896 cached_reg_t cached_reg;
4897
4898 p = p1;
4899
4900 if (*p != ':')
4901 error (_("Malformed packet(b) (missing colon): %s\n\
4902 Packet: '%s'\n"),
4903 p, buf);
4904 ++p;
4905
4906 if (reg == NULL)
4907 error (_("Remote sent bad register number %s: %s\n\
4908 Packet: '%s'\n"),
4909 hex_string (pnum), p, buf);
4910
4911 cached_reg.num = reg->regnum;
4912
4913 fieldsize = hex2bin (p, cached_reg.data,
4914 register_size (target_gdbarch,
4915 reg->regnum));
4916 p += 2 * fieldsize;
4917 if (fieldsize < register_size (target_gdbarch,
4918 reg->regnum))
4919 warning (_("Remote reply is too short: %s"), buf);
4920
4921 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
4922 }
4923
4924 if (*p != ';')
4925 error (_("Remote register badly formatted: %s\nhere: %s"),
4926 buf, p);
4927 ++p;
4928 }
4929 /* fall through */
4930 case 'S': /* Old style status, just signal only. */
4931 if (event->solibs_changed)
4932 event->ws.kind = TARGET_WAITKIND_LOADED;
4933 else if (event->replay_event)
4934 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
4935 else
4936 {
4937 event->ws.kind = TARGET_WAITKIND_STOPPED;
4938 event->ws.value.sig = (enum target_signal)
4939 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
4940 }
4941 break;
4942 case 'W': /* Target exited. */
4943 case 'X':
4944 {
4945 char *p;
4946 int pid;
4947 ULONGEST value;
4948
4949 /* GDB used to accept only 2 hex chars here. Stubs should
4950 only send more if they detect GDB supports multi-process
4951 support. */
4952 p = unpack_varlen_hex (&buf[1], &value);
4953
4954 if (buf[0] == 'W')
4955 {
4956 /* The remote process exited. */
4957 event->ws.kind = TARGET_WAITKIND_EXITED;
4958 event->ws.value.integer = value;
4959 }
4960 else
4961 {
4962 /* The remote process exited with a signal. */
4963 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
4964 event->ws.value.sig = (enum target_signal) value;
4965 }
4966
4967 /* If no process is specified, assume inferior_ptid. */
4968 pid = ptid_get_pid (inferior_ptid);
4969 if (*p == '\0')
4970 ;
4971 else if (*p == ';')
4972 {
4973 p++;
4974
4975 if (p == '\0')
4976 ;
4977 else if (strncmp (p,
4978 "process:", sizeof ("process:") - 1) == 0)
4979 {
4980 ULONGEST upid;
4981 p += sizeof ("process:") - 1;
4982 unpack_varlen_hex (p, &upid);
4983 pid = upid;
4984 }
4985 else
4986 error (_("unknown stop reply packet: %s"), buf);
4987 }
4988 else
4989 error (_("unknown stop reply packet: %s"), buf);
4990 event->ptid = pid_to_ptid (pid);
4991 }
4992 break;
4993 }
4994
4995 if (non_stop && ptid_equal (event->ptid, null_ptid))
4996 error (_("No process or thread specified in stop reply: %s"), buf);
4997 }
4998
4999 /* When the stub wants to tell GDB about a new stop reply, it sends a
5000 stop notification (%Stop). Those can come it at any time, hence,
5001 we have to make sure that any pending putpkt/getpkt sequence we're
5002 making is finished, before querying the stub for more events with
5003 vStopped. E.g., if we started a vStopped sequence immediatelly
5004 upon receiving the %Stop notification, something like this could
5005 happen:
5006
5007 1.1) --> Hg 1
5008 1.2) <-- OK
5009 1.3) --> g
5010 1.4) <-- %Stop
5011 1.5) --> vStopped
5012 1.6) <-- (registers reply to step #1.3)
5013
5014 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5015 query.
5016
5017 To solve this, whenever we parse a %Stop notification sucessfully,
5018 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5019 doing whatever we were doing:
5020
5021 2.1) --> Hg 1
5022 2.2) <-- OK
5023 2.3) --> g
5024 2.4) <-- %Stop
5025 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5026 2.5) <-- (registers reply to step #2.3)
5027
5028 Eventualy after step #2.5, we return to the event loop, which
5029 notices there's an event on the
5030 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5031 associated callback --- the function below. At this point, we're
5032 always safe to start a vStopped sequence. :
5033
5034 2.6) --> vStopped
5035 2.7) <-- T05 thread:2
5036 2.8) --> vStopped
5037 2.9) --> OK
5038 */
5039
5040 static void
5041 remote_get_pending_stop_replies (void)
5042 {
5043 struct remote_state *rs = get_remote_state ();
5044
5045 if (pending_stop_reply)
5046 {
5047 /* acknowledge */
5048 putpkt ("vStopped");
5049
5050 /* Now we can rely on it. */
5051 push_stop_reply (pending_stop_reply);
5052 pending_stop_reply = NULL;
5053
5054 while (1)
5055 {
5056 getpkt (&rs->buf, &rs->buf_size, 0);
5057 if (strcmp (rs->buf, "OK") == 0)
5058 break;
5059 else
5060 {
5061 struct cleanup *old_chain;
5062 struct stop_reply *stop_reply = stop_reply_xmalloc ();
5063
5064 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5065 remote_parse_stop_reply (rs->buf, stop_reply);
5066
5067 /* acknowledge */
5068 putpkt ("vStopped");
5069
5070 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
5071 {
5072 /* Now we can rely on it. */
5073 discard_cleanups (old_chain);
5074 push_stop_reply (stop_reply);
5075 }
5076 else
5077 /* We got an unknown stop reply. */
5078 do_cleanups (old_chain);
5079 }
5080 }
5081 }
5082 }
5083
5084
5085 /* Called when it is decided that STOP_REPLY holds the info of the
5086 event that is to be returned to the core. This function always
5087 destroys STOP_REPLY. */
5088
5089 static ptid_t
5090 process_stop_reply (struct stop_reply *stop_reply,
5091 struct target_waitstatus *status)
5092 {
5093 ptid_t ptid;
5094
5095 *status = stop_reply->ws;
5096 ptid = stop_reply->ptid;
5097
5098 /* If no thread/process was reported by the stub, assume the current
5099 inferior. */
5100 if (ptid_equal (ptid, null_ptid))
5101 ptid = inferior_ptid;
5102
5103 if (status->kind != TARGET_WAITKIND_EXITED
5104 && status->kind != TARGET_WAITKIND_SIGNALLED)
5105 {
5106 /* Expedited registers. */
5107 if (stop_reply->regcache)
5108 {
5109 struct regcache *regcache
5110 = get_thread_arch_regcache (ptid, target_gdbarch);
5111 cached_reg_t *reg;
5112 int ix;
5113
5114 for (ix = 0;
5115 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5116 ix++)
5117 regcache_raw_supply (regcache, reg->num, reg->data);
5118 VEC_free (cached_reg_t, stop_reply->regcache);
5119 }
5120
5121 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5122 remote_watch_data_address = stop_reply->watch_data_address;
5123
5124 remote_notice_new_inferior (ptid, 0);
5125 demand_private_info (ptid)->core = stop_reply->core;
5126 }
5127
5128 stop_reply_xfree (stop_reply);
5129 return ptid;
5130 }
5131
5132 /* The non-stop mode version of target_wait. */
5133
5134 static ptid_t
5135 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5136 {
5137 struct remote_state *rs = get_remote_state ();
5138 struct stop_reply *stop_reply;
5139 int ret;
5140
5141 /* If in non-stop mode, get out of getpkt even if a
5142 notification is received. */
5143
5144 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5145 0 /* forever */);
5146 while (1)
5147 {
5148 if (ret != -1)
5149 switch (rs->buf[0])
5150 {
5151 case 'E': /* Error of some sort. */
5152 /* We're out of sync with the target now. Did it continue
5153 or not? We can't tell which thread it was in non-stop,
5154 so just ignore this. */
5155 warning (_("Remote failure reply: %s"), rs->buf);
5156 break;
5157 case 'O': /* Console output. */
5158 remote_console_output (rs->buf + 1);
5159 break;
5160 default:
5161 warning (_("Invalid remote reply: %s"), rs->buf);
5162 break;
5163 }
5164
5165 /* Acknowledge a pending stop reply that may have arrived in the
5166 mean time. */
5167 if (pending_stop_reply != NULL)
5168 remote_get_pending_stop_replies ();
5169
5170 /* If indeed we noticed a stop reply, we're done. */
5171 stop_reply = queued_stop_reply (ptid);
5172 if (stop_reply != NULL)
5173 return process_stop_reply (stop_reply, status);
5174
5175 /* Still no event. If we're just polling for an event, then
5176 return to the event loop. */
5177 if (options & TARGET_WNOHANG)
5178 {
5179 status->kind = TARGET_WAITKIND_IGNORE;
5180 return minus_one_ptid;
5181 }
5182
5183 /* Otherwise do a blocking wait. */
5184 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5185 1 /* forever */);
5186 }
5187 }
5188
5189 /* Wait until the remote machine stops, then return, storing status in
5190 STATUS just as `wait' would. */
5191
5192 static ptid_t
5193 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5194 {
5195 struct remote_state *rs = get_remote_state ();
5196 ptid_t event_ptid = null_ptid;
5197 char *buf;
5198 struct stop_reply *stop_reply;
5199
5200 again:
5201
5202 status->kind = TARGET_WAITKIND_IGNORE;
5203 status->value.integer = 0;
5204
5205 stop_reply = queued_stop_reply (ptid);
5206 if (stop_reply != NULL)
5207 return process_stop_reply (stop_reply, status);
5208
5209 if (rs->cached_wait_status)
5210 /* Use the cached wait status, but only once. */
5211 rs->cached_wait_status = 0;
5212 else
5213 {
5214 int ret;
5215
5216 if (!target_is_async_p ())
5217 {
5218 ofunc = signal (SIGINT, remote_interrupt);
5219 /* If the user hit C-c before this packet, or between packets,
5220 pretend that it was hit right here. */
5221 if (quit_flag)
5222 {
5223 quit_flag = 0;
5224 remote_interrupt (SIGINT);
5225 }
5226 }
5227
5228 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5229 _never_ wait for ever -> test on target_is_async_p().
5230 However, before we do that we need to ensure that the caller
5231 knows how to take the target into/out of async mode. */
5232 ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
5233 if (!target_is_async_p ())
5234 signal (SIGINT, ofunc);
5235 }
5236
5237 buf = rs->buf;
5238
5239 remote_stopped_by_watchpoint_p = 0;
5240
5241 /* We got something. */
5242 rs->waiting_for_stop_reply = 0;
5243
5244 /* Assume that the target has acknowledged Ctrl-C unless we receive
5245 an 'F' or 'O' packet. */
5246 if (buf[0] != 'F' && buf[0] != 'O')
5247 rs->ctrlc_pending_p = 0;
5248
5249 switch (buf[0])
5250 {
5251 case 'E': /* Error of some sort. */
5252 /* We're out of sync with the target now. Did it continue or
5253 not? Not is more likely, so report a stop. */
5254 warning (_("Remote failure reply: %s"), buf);
5255 status->kind = TARGET_WAITKIND_STOPPED;
5256 status->value.sig = TARGET_SIGNAL_0;
5257 break;
5258 case 'F': /* File-I/O request. */
5259 remote_fileio_request (buf, rs->ctrlc_pending_p);
5260 rs->ctrlc_pending_p = 0;
5261 break;
5262 case 'T': case 'S': case 'X': case 'W':
5263 {
5264 struct stop_reply *stop_reply;
5265 struct cleanup *old_chain;
5266
5267 stop_reply = stop_reply_xmalloc ();
5268 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5269 remote_parse_stop_reply (buf, stop_reply);
5270 discard_cleanups (old_chain);
5271 event_ptid = process_stop_reply (stop_reply, status);
5272 break;
5273 }
5274 case 'O': /* Console output. */
5275 remote_console_output (buf + 1);
5276
5277 /* The target didn't really stop; keep waiting. */
5278 rs->waiting_for_stop_reply = 1;
5279
5280 break;
5281 case '\0':
5282 if (last_sent_signal != TARGET_SIGNAL_0)
5283 {
5284 /* Zero length reply means that we tried 'S' or 'C' and the
5285 remote system doesn't support it. */
5286 target_terminal_ours_for_output ();
5287 printf_filtered
5288 ("Can't send signals to this remote system. %s not sent.\n",
5289 target_signal_to_name (last_sent_signal));
5290 last_sent_signal = TARGET_SIGNAL_0;
5291 target_terminal_inferior ();
5292
5293 strcpy ((char *) buf, last_sent_step ? "s" : "c");
5294 putpkt ((char *) buf);
5295
5296 /* We just told the target to resume, so a stop reply is in
5297 order. */
5298 rs->waiting_for_stop_reply = 1;
5299 break;
5300 }
5301 /* else fallthrough */
5302 default:
5303 warning (_("Invalid remote reply: %s"), buf);
5304 /* Keep waiting. */
5305 rs->waiting_for_stop_reply = 1;
5306 break;
5307 }
5308
5309 if (status->kind == TARGET_WAITKIND_IGNORE)
5310 {
5311 /* Nothing interesting happened. If we're doing a non-blocking
5312 poll, we're done. Otherwise, go back to waiting. */
5313 if (options & TARGET_WNOHANG)
5314 return minus_one_ptid;
5315 else
5316 goto again;
5317 }
5318 else if (status->kind != TARGET_WAITKIND_EXITED
5319 && status->kind != TARGET_WAITKIND_SIGNALLED)
5320 {
5321 if (!ptid_equal (event_ptid, null_ptid))
5322 record_currthread (event_ptid);
5323 else
5324 event_ptid = inferior_ptid;
5325 }
5326 else
5327 /* A process exit. Invalidate our notion of current thread. */
5328 record_currthread (minus_one_ptid);
5329
5330 return event_ptid;
5331 }
5332
5333 /* Wait until the remote machine stops, then return, storing status in
5334 STATUS just as `wait' would. */
5335
5336 static ptid_t
5337 remote_wait (struct target_ops *ops,
5338 ptid_t ptid, struct target_waitstatus *status, int options)
5339 {
5340 ptid_t event_ptid;
5341
5342 if (non_stop)
5343 event_ptid = remote_wait_ns (ptid, status, options);
5344 else
5345 event_ptid = remote_wait_as (ptid, status, options);
5346
5347 if (target_can_async_p ())
5348 {
5349 /* If there are are events left in the queue tell the event loop
5350 to return here. */
5351 if (stop_reply_queue)
5352 mark_async_event_handler (remote_async_inferior_event_token);
5353 }
5354
5355 return event_ptid;
5356 }
5357
5358 /* Fetch a single register using a 'p' packet. */
5359
5360 static int
5361 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
5362 {
5363 struct remote_state *rs = get_remote_state ();
5364 char *buf, *p;
5365 char regp[MAX_REGISTER_SIZE];
5366 int i;
5367
5368 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
5369 return 0;
5370
5371 if (reg->pnum == -1)
5372 return 0;
5373
5374 p = rs->buf;
5375 *p++ = 'p';
5376 p += hexnumstr (p, reg->pnum);
5377 *p++ = '\0';
5378 putpkt (rs->buf);
5379 getpkt (&rs->buf, &rs->buf_size, 0);
5380
5381 buf = rs->buf;
5382
5383 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
5384 {
5385 case PACKET_OK:
5386 break;
5387 case PACKET_UNKNOWN:
5388 return 0;
5389 case PACKET_ERROR:
5390 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
5391 gdbarch_register_name (get_regcache_arch (regcache),
5392 reg->regnum),
5393 buf);
5394 }
5395
5396 /* If this register is unfetchable, tell the regcache. */
5397 if (buf[0] == 'x')
5398 {
5399 regcache_raw_supply (regcache, reg->regnum, NULL);
5400 return 1;
5401 }
5402
5403 /* Otherwise, parse and supply the value. */
5404 p = buf;
5405 i = 0;
5406 while (p[0] != 0)
5407 {
5408 if (p[1] == 0)
5409 error (_("fetch_register_using_p: early buf termination"));
5410
5411 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
5412 p += 2;
5413 }
5414 regcache_raw_supply (regcache, reg->regnum, regp);
5415 return 1;
5416 }
5417
5418 /* Fetch the registers included in the target's 'g' packet. */
5419
5420 static int
5421 send_g_packet (void)
5422 {
5423 struct remote_state *rs = get_remote_state ();
5424 int buf_len;
5425
5426 sprintf (rs->buf, "g");
5427 remote_send (&rs->buf, &rs->buf_size);
5428
5429 /* We can get out of synch in various cases. If the first character
5430 in the buffer is not a hex character, assume that has happened
5431 and try to fetch another packet to read. */
5432 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
5433 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
5434 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
5435 && rs->buf[0] != 'x') /* New: unavailable register value. */
5436 {
5437 if (remote_debug)
5438 fprintf_unfiltered (gdb_stdlog,
5439 "Bad register packet; fetching a new packet\n");
5440 getpkt (&rs->buf, &rs->buf_size, 0);
5441 }
5442
5443 buf_len = strlen (rs->buf);
5444
5445 /* Sanity check the received packet. */
5446 if (buf_len % 2 != 0)
5447 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
5448
5449 return buf_len / 2;
5450 }
5451
5452 static void
5453 process_g_packet (struct regcache *regcache)
5454 {
5455 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5456 struct remote_state *rs = get_remote_state ();
5457 struct remote_arch_state *rsa = get_remote_arch_state ();
5458 int i, buf_len;
5459 char *p;
5460 char *regs;
5461
5462 buf_len = strlen (rs->buf);
5463
5464 /* Further sanity checks, with knowledge of the architecture. */
5465 if (buf_len > 2 * rsa->sizeof_g_packet)
5466 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
5467
5468 /* Save the size of the packet sent to us by the target. It is used
5469 as a heuristic when determining the max size of packets that the
5470 target can safely receive. */
5471 if (rsa->actual_register_packet_size == 0)
5472 rsa->actual_register_packet_size = buf_len;
5473
5474 /* If this is smaller than we guessed the 'g' packet would be,
5475 update our records. A 'g' reply that doesn't include a register's
5476 value implies either that the register is not available, or that
5477 the 'p' packet must be used. */
5478 if (buf_len < 2 * rsa->sizeof_g_packet)
5479 {
5480 rsa->sizeof_g_packet = buf_len / 2;
5481
5482 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5483 {
5484 if (rsa->regs[i].pnum == -1)
5485 continue;
5486
5487 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
5488 rsa->regs[i].in_g_packet = 0;
5489 else
5490 rsa->regs[i].in_g_packet = 1;
5491 }
5492 }
5493
5494 regs = alloca (rsa->sizeof_g_packet);
5495
5496 /* Unimplemented registers read as all bits zero. */
5497 memset (regs, 0, rsa->sizeof_g_packet);
5498
5499 /* Reply describes registers byte by byte, each byte encoded as two
5500 hex characters. Suck them all up, then supply them to the
5501 register cacheing/storage mechanism. */
5502
5503 p = rs->buf;
5504 for (i = 0; i < rsa->sizeof_g_packet; i++)
5505 {
5506 if (p[0] == 0 || p[1] == 0)
5507 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
5508 internal_error (__FILE__, __LINE__,
5509 "unexpected end of 'g' packet reply");
5510
5511 if (p[0] == 'x' && p[1] == 'x')
5512 regs[i] = 0; /* 'x' */
5513 else
5514 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5515 p += 2;
5516 }
5517
5518 {
5519 int i;
5520 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5521 {
5522 struct packet_reg *r = &rsa->regs[i];
5523 if (r->in_g_packet)
5524 {
5525 if (r->offset * 2 >= strlen (rs->buf))
5526 /* This shouldn't happen - we adjusted in_g_packet above. */
5527 internal_error (__FILE__, __LINE__,
5528 "unexpected end of 'g' packet reply");
5529 else if (rs->buf[r->offset * 2] == 'x')
5530 {
5531 gdb_assert (r->offset * 2 < strlen (rs->buf));
5532 /* The register isn't available, mark it as such (at
5533 the same time setting the value to zero). */
5534 regcache_raw_supply (regcache, r->regnum, NULL);
5535 }
5536 else
5537 regcache_raw_supply (regcache, r->regnum,
5538 regs + r->offset);
5539 }
5540 }
5541 }
5542 }
5543
5544 static void
5545 fetch_registers_using_g (struct regcache *regcache)
5546 {
5547 send_g_packet ();
5548 process_g_packet (regcache);
5549 }
5550
5551 static void
5552 remote_fetch_registers (struct target_ops *ops,
5553 struct regcache *regcache, int regnum)
5554 {
5555 struct remote_arch_state *rsa = get_remote_arch_state ();
5556 int i;
5557
5558 set_general_thread (inferior_ptid);
5559
5560 if (regnum >= 0)
5561 {
5562 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5563 gdb_assert (reg != NULL);
5564
5565 /* If this register might be in the 'g' packet, try that first -
5566 we are likely to read more than one register. If this is the
5567 first 'g' packet, we might be overly optimistic about its
5568 contents, so fall back to 'p'. */
5569 if (reg->in_g_packet)
5570 {
5571 fetch_registers_using_g (regcache);
5572 if (reg->in_g_packet)
5573 return;
5574 }
5575
5576 if (fetch_register_using_p (regcache, reg))
5577 return;
5578
5579 /* This register is not available. */
5580 regcache_raw_supply (regcache, reg->regnum, NULL);
5581
5582 return;
5583 }
5584
5585 fetch_registers_using_g (regcache);
5586
5587 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5588 if (!rsa->regs[i].in_g_packet)
5589 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
5590 {
5591 /* This register is not available. */
5592 regcache_raw_supply (regcache, i, NULL);
5593 }
5594 }
5595
5596 /* Prepare to store registers. Since we may send them all (using a
5597 'G' request), we have to read out the ones we don't want to change
5598 first. */
5599
5600 static void
5601 remote_prepare_to_store (struct regcache *regcache)
5602 {
5603 struct remote_arch_state *rsa = get_remote_arch_state ();
5604 int i;
5605 gdb_byte buf[MAX_REGISTER_SIZE];
5606
5607 /* Make sure the entire registers array is valid. */
5608 switch (remote_protocol_packets[PACKET_P].support)
5609 {
5610 case PACKET_DISABLE:
5611 case PACKET_SUPPORT_UNKNOWN:
5612 /* Make sure all the necessary registers are cached. */
5613 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5614 if (rsa->regs[i].in_g_packet)
5615 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5616 break;
5617 case PACKET_ENABLE:
5618 break;
5619 }
5620 }
5621
5622 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
5623 packet was not recognized. */
5624
5625 static int
5626 store_register_using_P (const struct regcache *regcache,
5627 struct packet_reg *reg)
5628 {
5629 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5630 struct remote_state *rs = get_remote_state ();
5631 /* Try storing a single register. */
5632 char *buf = rs->buf;
5633 gdb_byte regp[MAX_REGISTER_SIZE];
5634 char *p;
5635
5636 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5637 return 0;
5638
5639 if (reg->pnum == -1)
5640 return 0;
5641
5642 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5643 p = buf + strlen (buf);
5644 regcache_raw_collect (regcache, reg->regnum, regp);
5645 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
5646 putpkt (rs->buf);
5647 getpkt (&rs->buf, &rs->buf_size, 0);
5648
5649 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
5650 {
5651 case PACKET_OK:
5652 return 1;
5653 case PACKET_ERROR:
5654 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
5655 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
5656 case PACKET_UNKNOWN:
5657 return 0;
5658 default:
5659 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
5660 }
5661 }
5662
5663 /* Store register REGNUM, or all registers if REGNUM == -1, from the
5664 contents of the register cache buffer. FIXME: ignores errors. */
5665
5666 static void
5667 store_registers_using_G (const struct regcache *regcache)
5668 {
5669 struct remote_state *rs = get_remote_state ();
5670 struct remote_arch_state *rsa = get_remote_arch_state ();
5671 gdb_byte *regs;
5672 char *p;
5673
5674 /* Extract all the registers in the regcache copying them into a
5675 local buffer. */
5676 {
5677 int i;
5678 regs = alloca (rsa->sizeof_g_packet);
5679 memset (regs, 0, rsa->sizeof_g_packet);
5680 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5681 {
5682 struct packet_reg *r = &rsa->regs[i];
5683 if (r->in_g_packet)
5684 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
5685 }
5686 }
5687
5688 /* Command describes registers byte by byte,
5689 each byte encoded as two hex characters. */
5690 p = rs->buf;
5691 *p++ = 'G';
5692 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
5693 updated. */
5694 bin2hex (regs, p, rsa->sizeof_g_packet);
5695 putpkt (rs->buf);
5696 getpkt (&rs->buf, &rs->buf_size, 0);
5697 if (packet_check_result (rs->buf) == PACKET_ERROR)
5698 error (_("Could not write registers; remote failure reply '%s'"),
5699 rs->buf);
5700 }
5701
5702 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
5703 of the register cache buffer. FIXME: ignores errors. */
5704
5705 static void
5706 remote_store_registers (struct target_ops *ops,
5707 struct regcache *regcache, int regnum)
5708 {
5709 struct remote_arch_state *rsa = get_remote_arch_state ();
5710 int i;
5711
5712 set_general_thread (inferior_ptid);
5713
5714 if (regnum >= 0)
5715 {
5716 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5717 gdb_assert (reg != NULL);
5718
5719 /* Always prefer to store registers using the 'P' packet if
5720 possible; we often change only a small number of registers.
5721 Sometimes we change a larger number; we'd need help from a
5722 higher layer to know to use 'G'. */
5723 if (store_register_using_P (regcache, reg))
5724 return;
5725
5726 /* For now, don't complain if we have no way to write the
5727 register. GDB loses track of unavailable registers too
5728 easily. Some day, this may be an error. We don't have
5729 any way to read the register, either... */
5730 if (!reg->in_g_packet)
5731 return;
5732
5733 store_registers_using_G (regcache);
5734 return;
5735 }
5736
5737 store_registers_using_G (regcache);
5738
5739 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5740 if (!rsa->regs[i].in_g_packet)
5741 if (!store_register_using_P (regcache, &rsa->regs[i]))
5742 /* See above for why we do not issue an error here. */
5743 continue;
5744 }
5745 \f
5746
5747 /* Return the number of hex digits in num. */
5748
5749 static int
5750 hexnumlen (ULONGEST num)
5751 {
5752 int i;
5753
5754 for (i = 0; num != 0; i++)
5755 num >>= 4;
5756
5757 return max (i, 1);
5758 }
5759
5760 /* Set BUF to the minimum number of hex digits representing NUM. */
5761
5762 static int
5763 hexnumstr (char *buf, ULONGEST num)
5764 {
5765 int len = hexnumlen (num);
5766 return hexnumnstr (buf, num, len);
5767 }
5768
5769
5770 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
5771
5772 static int
5773 hexnumnstr (char *buf, ULONGEST num, int width)
5774 {
5775 int i;
5776
5777 buf[width] = '\0';
5778
5779 for (i = width - 1; i >= 0; i--)
5780 {
5781 buf[i] = "0123456789abcdef"[(num & 0xf)];
5782 num >>= 4;
5783 }
5784
5785 return width;
5786 }
5787
5788 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
5789
5790 static CORE_ADDR
5791 remote_address_masked (CORE_ADDR addr)
5792 {
5793 int address_size = remote_address_size;
5794 /* If "remoteaddresssize" was not set, default to target address size. */
5795 if (!address_size)
5796 address_size = gdbarch_addr_bit (target_gdbarch);
5797
5798 if (address_size > 0
5799 && address_size < (sizeof (ULONGEST) * 8))
5800 {
5801 /* Only create a mask when that mask can safely be constructed
5802 in a ULONGEST variable. */
5803 ULONGEST mask = 1;
5804 mask = (mask << address_size) - 1;
5805 addr &= mask;
5806 }
5807 return addr;
5808 }
5809
5810 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
5811 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
5812 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
5813 (which may be more than *OUT_LEN due to escape characters). The
5814 total number of bytes in the output buffer will be at most
5815 OUT_MAXLEN. */
5816
5817 static int
5818 remote_escape_output (const gdb_byte *buffer, int len,
5819 gdb_byte *out_buf, int *out_len,
5820 int out_maxlen)
5821 {
5822 int input_index, output_index;
5823
5824 output_index = 0;
5825 for (input_index = 0; input_index < len; input_index++)
5826 {
5827 gdb_byte b = buffer[input_index];
5828
5829 if (b == '$' || b == '#' || b == '}')
5830 {
5831 /* These must be escaped. */
5832 if (output_index + 2 > out_maxlen)
5833 break;
5834 out_buf[output_index++] = '}';
5835 out_buf[output_index++] = b ^ 0x20;
5836 }
5837 else
5838 {
5839 if (output_index + 1 > out_maxlen)
5840 break;
5841 out_buf[output_index++] = b;
5842 }
5843 }
5844
5845 *out_len = input_index;
5846 return output_index;
5847 }
5848
5849 /* Convert BUFFER, escaped data LEN bytes long, into binary data
5850 in OUT_BUF. Return the number of bytes written to OUT_BUF.
5851 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
5852
5853 This function reverses remote_escape_output. It allows more
5854 escaped characters than that function does, in particular because
5855 '*' must be escaped to avoid the run-length encoding processing
5856 in reading packets. */
5857
5858 static int
5859 remote_unescape_input (const gdb_byte *buffer, int len,
5860 gdb_byte *out_buf, int out_maxlen)
5861 {
5862 int input_index, output_index;
5863 int escaped;
5864
5865 output_index = 0;
5866 escaped = 0;
5867 for (input_index = 0; input_index < len; input_index++)
5868 {
5869 gdb_byte b = buffer[input_index];
5870
5871 if (output_index + 1 > out_maxlen)
5872 {
5873 warning (_("Received too much data from remote target;"
5874 " ignoring overflow."));
5875 return output_index;
5876 }
5877
5878 if (escaped)
5879 {
5880 out_buf[output_index++] = b ^ 0x20;
5881 escaped = 0;
5882 }
5883 else if (b == '}')
5884 escaped = 1;
5885 else
5886 out_buf[output_index++] = b;
5887 }
5888
5889 if (escaped)
5890 error (_("Unmatched escape character in target response."));
5891
5892 return output_index;
5893 }
5894
5895 /* Determine whether the remote target supports binary downloading.
5896 This is accomplished by sending a no-op memory write of zero length
5897 to the target at the specified address. It does not suffice to send
5898 the whole packet, since many stubs strip the eighth bit and
5899 subsequently compute a wrong checksum, which causes real havoc with
5900 remote_write_bytes.
5901
5902 NOTE: This can still lose if the serial line is not eight-bit
5903 clean. In cases like this, the user should clear "remote
5904 X-packet". */
5905
5906 static void
5907 check_binary_download (CORE_ADDR addr)
5908 {
5909 struct remote_state *rs = get_remote_state ();
5910
5911 switch (remote_protocol_packets[PACKET_X].support)
5912 {
5913 case PACKET_DISABLE:
5914 break;
5915 case PACKET_ENABLE:
5916 break;
5917 case PACKET_SUPPORT_UNKNOWN:
5918 {
5919 char *p;
5920
5921 p = rs->buf;
5922 *p++ = 'X';
5923 p += hexnumstr (p, (ULONGEST) addr);
5924 *p++ = ',';
5925 p += hexnumstr (p, (ULONGEST) 0);
5926 *p++ = ':';
5927 *p = '\0';
5928
5929 putpkt_binary (rs->buf, (int) (p - rs->buf));
5930 getpkt (&rs->buf, &rs->buf_size, 0);
5931
5932 if (rs->buf[0] == '\0')
5933 {
5934 if (remote_debug)
5935 fprintf_unfiltered (gdb_stdlog,
5936 "binary downloading NOT suppported by target\n");
5937 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
5938 }
5939 else
5940 {
5941 if (remote_debug)
5942 fprintf_unfiltered (gdb_stdlog,
5943 "binary downloading suppported by target\n");
5944 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
5945 }
5946 break;
5947 }
5948 }
5949 }
5950
5951 /* Write memory data directly to the remote machine.
5952 This does not inform the data cache; the data cache uses this.
5953 HEADER is the starting part of the packet.
5954 MEMADDR is the address in the remote memory space.
5955 MYADDR is the address of the buffer in our space.
5956 LEN is the number of bytes.
5957 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
5958 should send data as binary ('X'), or hex-encoded ('M').
5959
5960 The function creates packet of the form
5961 <HEADER><ADDRESS>,<LENGTH>:<DATA>
5962
5963 where encoding of <DATA> is termined by PACKET_FORMAT.
5964
5965 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
5966 are omitted.
5967
5968 Returns the number of bytes transferred, or 0 (setting errno) for
5969 error. Only transfer a single packet. */
5970
5971 static int
5972 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5973 const gdb_byte *myaddr, int len,
5974 char packet_format, int use_length)
5975 {
5976 struct remote_state *rs = get_remote_state ();
5977 char *p;
5978 char *plen = NULL;
5979 int plenlen = 0;
5980 int todo;
5981 int nr_bytes;
5982 int payload_size;
5983 int payload_length;
5984 int header_length;
5985
5986 if (packet_format != 'X' && packet_format != 'M')
5987 internal_error (__FILE__, __LINE__,
5988 "remote_write_bytes_aux: bad packet format");
5989
5990 if (len <= 0)
5991 return 0;
5992
5993 payload_size = get_memory_write_packet_size ();
5994
5995 /* The packet buffer will be large enough for the payload;
5996 get_memory_packet_size ensures this. */
5997 rs->buf[0] = '\0';
5998
5999 /* Compute the size of the actual payload by subtracting out the
6000 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
6001 */
6002 payload_size -= strlen ("$,:#NN");
6003 if (!use_length)
6004 /* The comma won't be used. */
6005 payload_size += 1;
6006 header_length = strlen (header);
6007 payload_size -= header_length;
6008 payload_size -= hexnumlen (memaddr);
6009
6010 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6011
6012 strcat (rs->buf, header);
6013 p = rs->buf + strlen (header);
6014
6015 /* Compute a best guess of the number of bytes actually transfered. */
6016 if (packet_format == 'X')
6017 {
6018 /* Best guess at number of bytes that will fit. */
6019 todo = min (len, payload_size);
6020 if (use_length)
6021 payload_size -= hexnumlen (todo);
6022 todo = min (todo, payload_size);
6023 }
6024 else
6025 {
6026 /* Num bytes that will fit. */
6027 todo = min (len, payload_size / 2);
6028 if (use_length)
6029 payload_size -= hexnumlen (todo);
6030 todo = min (todo, payload_size / 2);
6031 }
6032
6033 if (todo <= 0)
6034 internal_error (__FILE__, __LINE__,
6035 _("minumum packet size too small to write data"));
6036
6037 /* If we already need another packet, then try to align the end
6038 of this packet to a useful boundary. */
6039 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6040 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6041
6042 /* Append "<memaddr>". */
6043 memaddr = remote_address_masked (memaddr);
6044 p += hexnumstr (p, (ULONGEST) memaddr);
6045
6046 if (use_length)
6047 {
6048 /* Append ",". */
6049 *p++ = ',';
6050
6051 /* Append <len>. Retain the location/size of <len>. It may need to
6052 be adjusted once the packet body has been created. */
6053 plen = p;
6054 plenlen = hexnumstr (p, (ULONGEST) todo);
6055 p += plenlen;
6056 }
6057
6058 /* Append ":". */
6059 *p++ = ':';
6060 *p = '\0';
6061
6062 /* Append the packet body. */
6063 if (packet_format == 'X')
6064 {
6065 /* Binary mode. Send target system values byte by byte, in
6066 increasing byte addresses. Only escape certain critical
6067 characters. */
6068 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
6069 payload_size);
6070
6071 /* If not all TODO bytes fit, then we'll need another packet. Make
6072 a second try to keep the end of the packet aligned. Don't do
6073 this if the packet is tiny. */
6074 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6075 {
6076 int new_nr_bytes;
6077
6078 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6079 - memaddr);
6080 if (new_nr_bytes != nr_bytes)
6081 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6082 p, &nr_bytes,
6083 payload_size);
6084 }
6085
6086 p += payload_length;
6087 if (use_length && nr_bytes < todo)
6088 {
6089 /* Escape chars have filled up the buffer prematurely,
6090 and we have actually sent fewer bytes than planned.
6091 Fix-up the length field of the packet. Use the same
6092 number of characters as before. */
6093 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6094 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6095 }
6096 }
6097 else
6098 {
6099 /* Normal mode: Send target system values byte by byte, in
6100 increasing byte addresses. Each byte is encoded as a two hex
6101 value. */
6102 nr_bytes = bin2hex (myaddr, p, todo);
6103 p += 2 * nr_bytes;
6104 }
6105
6106 putpkt_binary (rs->buf, (int) (p - rs->buf));
6107 getpkt (&rs->buf, &rs->buf_size, 0);
6108
6109 if (rs->buf[0] == 'E')
6110 {
6111 /* There is no correspondance between what the remote protocol
6112 uses for errors and errno codes. We would like a cleaner way
6113 of representing errors (big enough to include errno codes,
6114 bfd_error codes, and others). But for now just return EIO. */
6115 errno = EIO;
6116 return 0;
6117 }
6118
6119 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6120 fewer bytes than we'd planned. */
6121 return nr_bytes;
6122 }
6123
6124 /* Write memory data directly to the remote machine.
6125 This does not inform the data cache; the data cache uses this.
6126 MEMADDR is the address in the remote memory space.
6127 MYADDR is the address of the buffer in our space.
6128 LEN is the number of bytes.
6129
6130 Returns number of bytes transferred, or 0 (setting errno) for
6131 error. Only transfer a single packet. */
6132
6133 int
6134 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
6135 {
6136 char *packet_format = 0;
6137
6138 /* Check whether the target supports binary download. */
6139 check_binary_download (memaddr);
6140
6141 switch (remote_protocol_packets[PACKET_X].support)
6142 {
6143 case PACKET_ENABLE:
6144 packet_format = "X";
6145 break;
6146 case PACKET_DISABLE:
6147 packet_format = "M";
6148 break;
6149 case PACKET_SUPPORT_UNKNOWN:
6150 internal_error (__FILE__, __LINE__,
6151 _("remote_write_bytes: bad internal state"));
6152 default:
6153 internal_error (__FILE__, __LINE__, _("bad switch"));
6154 }
6155
6156 return remote_write_bytes_aux (packet_format,
6157 memaddr, myaddr, len, packet_format[0], 1);
6158 }
6159
6160 /* Read memory data directly from the remote machine.
6161 This does not use the data cache; the data cache uses this.
6162 MEMADDR is the address in the remote memory space.
6163 MYADDR is the address of the buffer in our space.
6164 LEN is the number of bytes.
6165
6166 Returns number of bytes transferred, or 0 for error. */
6167
6168 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
6169 remote targets) shouldn't attempt to read the entire buffer.
6170 Instead it should read a single packet worth of data and then
6171 return the byte size of that packet to the caller. The caller (its
6172 caller and its callers caller ;-) already contains code for
6173 handling partial reads. */
6174
6175 int
6176 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6177 {
6178 struct remote_state *rs = get_remote_state ();
6179 int max_buf_size; /* Max size of packet output buffer. */
6180 int origlen;
6181
6182 if (len <= 0)
6183 return 0;
6184
6185 max_buf_size = get_memory_read_packet_size ();
6186 /* The packet buffer will be large enough for the payload;
6187 get_memory_packet_size ensures this. */
6188
6189 origlen = len;
6190 while (len > 0)
6191 {
6192 char *p;
6193 int todo;
6194 int i;
6195
6196 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
6197
6198 /* construct "m"<memaddr>","<len>" */
6199 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
6200 memaddr = remote_address_masked (memaddr);
6201 p = rs->buf;
6202 *p++ = 'm';
6203 p += hexnumstr (p, (ULONGEST) memaddr);
6204 *p++ = ',';
6205 p += hexnumstr (p, (ULONGEST) todo);
6206 *p = '\0';
6207
6208 putpkt (rs->buf);
6209 getpkt (&rs->buf, &rs->buf_size, 0);
6210
6211 if (rs->buf[0] == 'E'
6212 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6213 && rs->buf[3] == '\0')
6214 {
6215 /* There is no correspondance between what the remote
6216 protocol uses for errors and errno codes. We would like
6217 a cleaner way of representing errors (big enough to
6218 include errno codes, bfd_error codes, and others). But
6219 for now just return EIO. */
6220 errno = EIO;
6221 return 0;
6222 }
6223
6224 /* Reply describes memory byte by byte,
6225 each byte encoded as two hex characters. */
6226
6227 p = rs->buf;
6228 if ((i = hex2bin (p, myaddr, todo)) < todo)
6229 {
6230 /* Reply is short. This means that we were able to read
6231 only part of what we wanted to. */
6232 return i + (origlen - len);
6233 }
6234 myaddr += todo;
6235 memaddr += todo;
6236 len -= todo;
6237 }
6238 return origlen;
6239 }
6240 \f
6241
6242 /* Remote notification handler. */
6243
6244 static void
6245 handle_notification (char *buf, size_t length)
6246 {
6247 if (strncmp (buf, "Stop:", 5) == 0)
6248 {
6249 if (pending_stop_reply)
6250 {
6251 /* We've already parsed the in-flight stop-reply, but the
6252 stub for some reason thought we didn't, possibly due to
6253 timeout on its side. Just ignore it. */
6254 if (remote_debug)
6255 fprintf_unfiltered (gdb_stdlog, "ignoring resent notification\n");
6256 }
6257 else
6258 {
6259 struct cleanup *old_chain;
6260 struct stop_reply *reply = stop_reply_xmalloc ();
6261 old_chain = make_cleanup (do_stop_reply_xfree, reply);
6262
6263 remote_parse_stop_reply (buf + 5, reply);
6264
6265 discard_cleanups (old_chain);
6266
6267 /* Be careful to only set it after parsing, since an error
6268 may be thrown then. */
6269 pending_stop_reply = reply;
6270
6271 /* Notify the event loop there's a stop reply to acknowledge
6272 and that there may be more events to fetch. */
6273 mark_async_event_handler (remote_async_get_pending_events_token);
6274
6275 if (remote_debug)
6276 fprintf_unfiltered (gdb_stdlog, "stop notification captured\n");
6277 }
6278 }
6279 else
6280 /* We ignore notifications we don't recognize, for compatibility
6281 with newer stubs. */
6282 ;
6283 }
6284
6285 \f
6286 /* Read or write LEN bytes from inferior memory at MEMADDR,
6287 transferring to or from debugger address BUFFER. Write to inferior
6288 if SHOULD_WRITE is nonzero. Returns length of data written or
6289 read; 0 for error. TARGET is unused. */
6290
6291 static int
6292 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
6293 int should_write, struct mem_attrib *attrib,
6294 struct target_ops *target)
6295 {
6296 int res;
6297
6298 set_general_thread (inferior_ptid);
6299
6300 if (should_write)
6301 res = remote_write_bytes (mem_addr, buffer, mem_len);
6302 else
6303 res = remote_read_bytes (mem_addr, buffer, mem_len);
6304
6305 return res;
6306 }
6307
6308 /* Sends a packet with content determined by the printf format string
6309 FORMAT and the remaining arguments, then gets the reply. Returns
6310 whether the packet was a success, a failure, or unknown. */
6311
6312 static enum packet_result
6313 remote_send_printf (const char *format, ...)
6314 {
6315 struct remote_state *rs = get_remote_state ();
6316 int max_size = get_remote_packet_size ();
6317
6318 va_list ap;
6319 va_start (ap, format);
6320
6321 rs->buf[0] = '\0';
6322 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6323 internal_error (__FILE__, __LINE__, "Too long remote packet.");
6324
6325 if (putpkt (rs->buf) < 0)
6326 error (_("Communication problem with target."));
6327
6328 rs->buf[0] = '\0';
6329 getpkt (&rs->buf, &rs->buf_size, 0);
6330
6331 return packet_check_result (rs->buf);
6332 }
6333
6334 static void
6335 restore_remote_timeout (void *p)
6336 {
6337 int value = *(int *)p;
6338 remote_timeout = value;
6339 }
6340
6341 /* Flash writing can take quite some time. We'll set
6342 effectively infinite timeout for flash operations.
6343 In future, we'll need to decide on a better approach. */
6344 static const int remote_flash_timeout = 1000;
6345
6346 static void
6347 remote_flash_erase (struct target_ops *ops,
6348 ULONGEST address, LONGEST length)
6349 {
6350 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
6351 int saved_remote_timeout = remote_timeout;
6352 enum packet_result ret;
6353
6354 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6355 &saved_remote_timeout);
6356 remote_timeout = remote_flash_timeout;
6357
6358 ret = remote_send_printf ("vFlashErase:%s,%s",
6359 phex (address, addr_size),
6360 phex (length, 4));
6361 switch (ret)
6362 {
6363 case PACKET_UNKNOWN:
6364 error (_("Remote target does not support flash erase"));
6365 case PACKET_ERROR:
6366 error (_("Error erasing flash with vFlashErase packet"));
6367 default:
6368 break;
6369 }
6370
6371 do_cleanups (back_to);
6372 }
6373
6374 static LONGEST
6375 remote_flash_write (struct target_ops *ops,
6376 ULONGEST address, LONGEST length,
6377 const gdb_byte *data)
6378 {
6379 int saved_remote_timeout = remote_timeout;
6380 int ret;
6381 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6382 &saved_remote_timeout);
6383
6384 remote_timeout = remote_flash_timeout;
6385 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
6386 do_cleanups (back_to);
6387
6388 return ret;
6389 }
6390
6391 static void
6392 remote_flash_done (struct target_ops *ops)
6393 {
6394 int saved_remote_timeout = remote_timeout;
6395 int ret;
6396 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6397 &saved_remote_timeout);
6398
6399 remote_timeout = remote_flash_timeout;
6400 ret = remote_send_printf ("vFlashDone");
6401 do_cleanups (back_to);
6402
6403 switch (ret)
6404 {
6405 case PACKET_UNKNOWN:
6406 error (_("Remote target does not support vFlashDone"));
6407 case PACKET_ERROR:
6408 error (_("Error finishing flash operation"));
6409 default:
6410 break;
6411 }
6412 }
6413
6414 static void
6415 remote_files_info (struct target_ops *ignore)
6416 {
6417 puts_filtered ("Debugging a target over a serial line.\n");
6418 }
6419 \f
6420 /* Stuff for dealing with the packets which are part of this protocol.
6421 See comment at top of file for details. */
6422
6423 /* Read a single character from the remote end. */
6424
6425 static int
6426 readchar (int timeout)
6427 {
6428 int ch;
6429
6430 ch = serial_readchar (remote_desc, timeout);
6431
6432 if (ch >= 0)
6433 return ch;
6434
6435 switch ((enum serial_rc) ch)
6436 {
6437 case SERIAL_EOF:
6438 pop_target ();
6439 error (_("Remote connection closed"));
6440 /* no return */
6441 case SERIAL_ERROR:
6442 perror_with_name (_("Remote communication error"));
6443 /* no return */
6444 case SERIAL_TIMEOUT:
6445 break;
6446 }
6447 return ch;
6448 }
6449
6450 /* Send the command in *BUF to the remote machine, and read the reply
6451 into *BUF. Report an error if we get an error reply. Resize
6452 *BUF using xrealloc if necessary to hold the result, and update
6453 *SIZEOF_BUF. */
6454
6455 static void
6456 remote_send (char **buf,
6457 long *sizeof_buf)
6458 {
6459 putpkt (*buf);
6460 getpkt (buf, sizeof_buf, 0);
6461
6462 if ((*buf)[0] == 'E')
6463 error (_("Remote failure reply: %s"), *buf);
6464 }
6465
6466 /* Return a pointer to an xmalloc'ed string representing an escaped
6467 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
6468 etc. The caller is responsible for releasing the returned
6469 memory. */
6470
6471 static char *
6472 escape_buffer (const char *buf, int n)
6473 {
6474 struct cleanup *old_chain;
6475 struct ui_file *stb;
6476 char *str;
6477
6478 stb = mem_fileopen ();
6479 old_chain = make_cleanup_ui_file_delete (stb);
6480
6481 fputstrn_unfiltered (buf, n, 0, stb);
6482 str = ui_file_xstrdup (stb, NULL);
6483 do_cleanups (old_chain);
6484 return str;
6485 }
6486
6487 /* Display a null-terminated packet on stdout, for debugging, using C
6488 string notation. */
6489
6490 static void
6491 print_packet (char *buf)
6492 {
6493 puts_filtered ("\"");
6494 fputstr_filtered (buf, '"', gdb_stdout);
6495 puts_filtered ("\"");
6496 }
6497
6498 int
6499 putpkt (char *buf)
6500 {
6501 return putpkt_binary (buf, strlen (buf));
6502 }
6503
6504 /* Send a packet to the remote machine, with error checking. The data
6505 of the packet is in BUF. The string in BUF can be at most
6506 get_remote_packet_size () - 5 to account for the $, # and checksum,
6507 and for a possible /0 if we are debugging (remote_debug) and want
6508 to print the sent packet as a string. */
6509
6510 static int
6511 putpkt_binary (char *buf, int cnt)
6512 {
6513 struct remote_state *rs = get_remote_state ();
6514 int i;
6515 unsigned char csum = 0;
6516 char *buf2 = alloca (cnt + 6);
6517
6518 int ch;
6519 int tcount = 0;
6520 char *p;
6521
6522 /* Catch cases like trying to read memory or listing threads while
6523 we're waiting for a stop reply. The remote server wouldn't be
6524 ready to handle this request, so we'd hang and timeout. We don't
6525 have to worry about this in synchronous mode, because in that
6526 case it's not possible to issue a command while the target is
6527 running. This is not a problem in non-stop mode, because in that
6528 case, the stub is always ready to process serial input. */
6529 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
6530 error (_("Cannot execute this command while the target is running."));
6531
6532 /* We're sending out a new packet. Make sure we don't look at a
6533 stale cached response. */
6534 rs->cached_wait_status = 0;
6535
6536 /* Copy the packet into buffer BUF2, encapsulating it
6537 and giving it a checksum. */
6538
6539 p = buf2;
6540 *p++ = '$';
6541
6542 for (i = 0; i < cnt; i++)
6543 {
6544 csum += buf[i];
6545 *p++ = buf[i];
6546 }
6547 *p++ = '#';
6548 *p++ = tohex ((csum >> 4) & 0xf);
6549 *p++ = tohex (csum & 0xf);
6550
6551 /* Send it over and over until we get a positive ack. */
6552
6553 while (1)
6554 {
6555 int started_error_output = 0;
6556
6557 if (remote_debug)
6558 {
6559 struct cleanup *old_chain;
6560 char *str;
6561
6562 *p = '\0';
6563 str = escape_buffer (buf2, p - buf2);
6564 old_chain = make_cleanup (xfree, str);
6565 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
6566 gdb_flush (gdb_stdlog);
6567 do_cleanups (old_chain);
6568 }
6569 if (serial_write (remote_desc, buf2, p - buf2))
6570 perror_with_name (_("putpkt: write failed"));
6571
6572 /* If this is a no acks version of the remote protocol, send the
6573 packet and move on. */
6574 if (rs->noack_mode)
6575 break;
6576
6577 /* Read until either a timeout occurs (-2) or '+' is read.
6578 Handle any notification that arrives in the mean time. */
6579 while (1)
6580 {
6581 ch = readchar (remote_timeout);
6582
6583 if (remote_debug)
6584 {
6585 switch (ch)
6586 {
6587 case '+':
6588 case '-':
6589 case SERIAL_TIMEOUT:
6590 case '$':
6591 case '%':
6592 if (started_error_output)
6593 {
6594 putchar_unfiltered ('\n');
6595 started_error_output = 0;
6596 }
6597 }
6598 }
6599
6600 switch (ch)
6601 {
6602 case '+':
6603 if (remote_debug)
6604 fprintf_unfiltered (gdb_stdlog, "Ack\n");
6605 return 1;
6606 case '-':
6607 if (remote_debug)
6608 fprintf_unfiltered (gdb_stdlog, "Nak\n");
6609 case SERIAL_TIMEOUT:
6610 tcount++;
6611 if (tcount > 3)
6612 return 0;
6613 break; /* Retransmit buffer. */
6614 case '$':
6615 {
6616 if (remote_debug)
6617 fprintf_unfiltered (gdb_stdlog,
6618 "Packet instead of Ack, ignoring it\n");
6619 /* It's probably an old response sent because an ACK
6620 was lost. Gobble up the packet and ack it so it
6621 doesn't get retransmitted when we resend this
6622 packet. */
6623 skip_frame ();
6624 serial_write (remote_desc, "+", 1);
6625 continue; /* Now, go look for +. */
6626 }
6627
6628 case '%':
6629 {
6630 int val;
6631
6632 /* If we got a notification, handle it, and go back to looking
6633 for an ack. */
6634 /* We've found the start of a notification. Now
6635 collect the data. */
6636 val = read_frame (&rs->buf, &rs->buf_size);
6637 if (val >= 0)
6638 {
6639 if (remote_debug)
6640 {
6641 struct cleanup *old_chain;
6642 char *str;
6643
6644 str = escape_buffer (rs->buf, val);
6645 old_chain = make_cleanup (xfree, str);
6646 fprintf_unfiltered (gdb_stdlog,
6647 " Notification received: %s\n",
6648 str);
6649 do_cleanups (old_chain);
6650 }
6651 handle_notification (rs->buf, val);
6652 /* We're in sync now, rewait for the ack. */
6653 tcount = 0;
6654 }
6655 else
6656 {
6657 if (remote_debug)
6658 {
6659 if (!started_error_output)
6660 {
6661 started_error_output = 1;
6662 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6663 }
6664 fputc_unfiltered (ch & 0177, gdb_stdlog);
6665 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
6666 }
6667 }
6668 continue;
6669 }
6670 /* fall-through */
6671 default:
6672 if (remote_debug)
6673 {
6674 if (!started_error_output)
6675 {
6676 started_error_output = 1;
6677 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6678 }
6679 fputc_unfiltered (ch & 0177, gdb_stdlog);
6680 }
6681 continue;
6682 }
6683 break; /* Here to retransmit. */
6684 }
6685
6686 #if 0
6687 /* This is wrong. If doing a long backtrace, the user should be
6688 able to get out next time we call QUIT, without anything as
6689 violent as interrupt_query. If we want to provide a way out of
6690 here without getting to the next QUIT, it should be based on
6691 hitting ^C twice as in remote_wait. */
6692 if (quit_flag)
6693 {
6694 quit_flag = 0;
6695 interrupt_query ();
6696 }
6697 #endif
6698 }
6699 return 0;
6700 }
6701
6702 /* Come here after finding the start of a frame when we expected an
6703 ack. Do our best to discard the rest of this packet. */
6704
6705 static void
6706 skip_frame (void)
6707 {
6708 int c;
6709
6710 while (1)
6711 {
6712 c = readchar (remote_timeout);
6713 switch (c)
6714 {
6715 case SERIAL_TIMEOUT:
6716 /* Nothing we can do. */
6717 return;
6718 case '#':
6719 /* Discard the two bytes of checksum and stop. */
6720 c = readchar (remote_timeout);
6721 if (c >= 0)
6722 c = readchar (remote_timeout);
6723
6724 return;
6725 case '*': /* Run length encoding. */
6726 /* Discard the repeat count. */
6727 c = readchar (remote_timeout);
6728 if (c < 0)
6729 return;
6730 break;
6731 default:
6732 /* A regular character. */
6733 break;
6734 }
6735 }
6736 }
6737
6738 /* Come here after finding the start of the frame. Collect the rest
6739 into *BUF, verifying the checksum, length, and handling run-length
6740 compression. NUL terminate the buffer. If there is not enough room,
6741 expand *BUF using xrealloc.
6742
6743 Returns -1 on error, number of characters in buffer (ignoring the
6744 trailing NULL) on success. (could be extended to return one of the
6745 SERIAL status indications). */
6746
6747 static long
6748 read_frame (char **buf_p,
6749 long *sizeof_buf)
6750 {
6751 unsigned char csum;
6752 long bc;
6753 int c;
6754 char *buf = *buf_p;
6755 struct remote_state *rs = get_remote_state ();
6756
6757 csum = 0;
6758 bc = 0;
6759
6760 while (1)
6761 {
6762 c = readchar (remote_timeout);
6763 switch (c)
6764 {
6765 case SERIAL_TIMEOUT:
6766 if (remote_debug)
6767 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
6768 return -1;
6769 case '$':
6770 if (remote_debug)
6771 fputs_filtered ("Saw new packet start in middle of old one\n",
6772 gdb_stdlog);
6773 return -1; /* Start a new packet, count retries. */
6774 case '#':
6775 {
6776 unsigned char pktcsum;
6777 int check_0 = 0;
6778 int check_1 = 0;
6779
6780 buf[bc] = '\0';
6781
6782 check_0 = readchar (remote_timeout);
6783 if (check_0 >= 0)
6784 check_1 = readchar (remote_timeout);
6785
6786 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
6787 {
6788 if (remote_debug)
6789 fputs_filtered ("Timeout in checksum, retrying\n",
6790 gdb_stdlog);
6791 return -1;
6792 }
6793 else if (check_0 < 0 || check_1 < 0)
6794 {
6795 if (remote_debug)
6796 fputs_filtered ("Communication error in checksum\n",
6797 gdb_stdlog);
6798 return -1;
6799 }
6800
6801 /* Don't recompute the checksum; with no ack packets we
6802 don't have any way to indicate a packet retransmission
6803 is necessary. */
6804 if (rs->noack_mode)
6805 return bc;
6806
6807 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
6808 if (csum == pktcsum)
6809 return bc;
6810
6811 if (remote_debug)
6812 {
6813 struct cleanup *old_chain;
6814 char *str;
6815
6816 str = escape_buffer (buf, bc);
6817 old_chain = make_cleanup (xfree, str);
6818 fprintf_unfiltered (gdb_stdlog,
6819 "\
6820 Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
6821 pktcsum, csum, str);
6822 do_cleanups (old_chain);
6823 }
6824 /* Number of characters in buffer ignoring trailing
6825 NULL. */
6826 return -1;
6827 }
6828 case '*': /* Run length encoding. */
6829 {
6830 int repeat;
6831 csum += c;
6832
6833 c = readchar (remote_timeout);
6834 csum += c;
6835 repeat = c - ' ' + 3; /* Compute repeat count. */
6836
6837 /* The character before ``*'' is repeated. */
6838
6839 if (repeat > 0 && repeat <= 255 && bc > 0)
6840 {
6841 if (bc + repeat - 1 >= *sizeof_buf - 1)
6842 {
6843 /* Make some more room in the buffer. */
6844 *sizeof_buf += repeat;
6845 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6846 buf = *buf_p;
6847 }
6848
6849 memset (&buf[bc], buf[bc - 1], repeat);
6850 bc += repeat;
6851 continue;
6852 }
6853
6854 buf[bc] = '\0';
6855 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
6856 return -1;
6857 }
6858 default:
6859 if (bc >= *sizeof_buf - 1)
6860 {
6861 /* Make some more room in the buffer. */
6862 *sizeof_buf *= 2;
6863 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6864 buf = *buf_p;
6865 }
6866
6867 buf[bc++] = c;
6868 csum += c;
6869 continue;
6870 }
6871 }
6872 }
6873
6874 /* Read a packet from the remote machine, with error checking, and
6875 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6876 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6877 rather than timing out; this is used (in synchronous mode) to wait
6878 for a target that is is executing user code to stop. */
6879 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
6880 don't have to change all the calls to getpkt to deal with the
6881 return value, because at the moment I don't know what the right
6882 thing to do it for those. */
6883 void
6884 getpkt (char **buf,
6885 long *sizeof_buf,
6886 int forever)
6887 {
6888 int timed_out;
6889
6890 timed_out = getpkt_sane (buf, sizeof_buf, forever);
6891 }
6892
6893
6894 /* Read a packet from the remote machine, with error checking, and
6895 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6896 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6897 rather than timing out; this is used (in synchronous mode) to wait
6898 for a target that is is executing user code to stop. If FOREVER ==
6899 0, this function is allowed to time out gracefully and return an
6900 indication of this to the caller. Otherwise return the number of
6901 bytes read. If EXPECTING_NOTIF, consider receiving a notification
6902 enough reason to return to the caller. */
6903
6904 static int
6905 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
6906 int expecting_notif)
6907 {
6908 struct remote_state *rs = get_remote_state ();
6909 int c;
6910 int tries;
6911 int timeout;
6912 int val = -1;
6913
6914 /* We're reading a new response. Make sure we don't look at a
6915 previously cached response. */
6916 rs->cached_wait_status = 0;
6917
6918 strcpy (*buf, "timeout");
6919
6920 if (forever)
6921 timeout = watchdog > 0 ? watchdog : -1;
6922 else if (expecting_notif)
6923 timeout = 0; /* There should already be a char in the buffer. If
6924 not, bail out. */
6925 else
6926 timeout = remote_timeout;
6927
6928 #define MAX_TRIES 3
6929
6930 /* Process any number of notifications, and then return when
6931 we get a packet. */
6932 for (;;)
6933 {
6934 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
6935 times. */
6936 for (tries = 1; tries <= MAX_TRIES; tries++)
6937 {
6938 /* This can loop forever if the remote side sends us
6939 characters continuously, but if it pauses, we'll get
6940 SERIAL_TIMEOUT from readchar because of timeout. Then
6941 we'll count that as a retry.
6942
6943 Note that even when forever is set, we will only wait
6944 forever prior to the start of a packet. After that, we
6945 expect characters to arrive at a brisk pace. They should
6946 show up within remote_timeout intervals. */
6947 do
6948 c = readchar (timeout);
6949 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
6950
6951 if (c == SERIAL_TIMEOUT)
6952 {
6953 if (expecting_notif)
6954 return -1; /* Don't complain, it's normal to not get
6955 anything in this case. */
6956
6957 if (forever) /* Watchdog went off? Kill the target. */
6958 {
6959 QUIT;
6960 pop_target ();
6961 error (_("Watchdog timeout has expired. Target detached."));
6962 }
6963 if (remote_debug)
6964 fputs_filtered ("Timed out.\n", gdb_stdlog);
6965 }
6966 else
6967 {
6968 /* We've found the start of a packet or notification.
6969 Now collect the data. */
6970 val = read_frame (buf, sizeof_buf);
6971 if (val >= 0)
6972 break;
6973 }
6974
6975 serial_write (remote_desc, "-", 1);
6976 }
6977
6978 if (tries > MAX_TRIES)
6979 {
6980 /* We have tried hard enough, and just can't receive the
6981 packet/notification. Give up. */
6982 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
6983
6984 /* Skip the ack char if we're in no-ack mode. */
6985 if (!rs->noack_mode)
6986 serial_write (remote_desc, "+", 1);
6987 return -1;
6988 }
6989
6990 /* If we got an ordinary packet, return that to our caller. */
6991 if (c == '$')
6992 {
6993 if (remote_debug)
6994 {
6995 struct cleanup *old_chain;
6996 char *str;
6997
6998 str = escape_buffer (*buf, val);
6999 old_chain = make_cleanup (xfree, str);
7000 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7001 do_cleanups (old_chain);
7002 }
7003
7004 /* Skip the ack char if we're in no-ack mode. */
7005 if (!rs->noack_mode)
7006 serial_write (remote_desc, "+", 1);
7007 return val;
7008 }
7009
7010 /* If we got a notification, handle it, and go back to looking
7011 for a packet. */
7012 else
7013 {
7014 gdb_assert (c == '%');
7015
7016 if (remote_debug)
7017 {
7018 struct cleanup *old_chain;
7019 char *str;
7020
7021 str = escape_buffer (*buf, val);
7022 old_chain = make_cleanup (xfree, str);
7023 fprintf_unfiltered (gdb_stdlog,
7024 " Notification received: %s\n",
7025 str);
7026 do_cleanups (old_chain);
7027 }
7028
7029 handle_notification (*buf, val);
7030
7031 /* Notifications require no acknowledgement. */
7032
7033 if (expecting_notif)
7034 return -1;
7035 }
7036 }
7037 }
7038
7039 static int
7040 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7041 {
7042 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
7043 }
7044
7045 static int
7046 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
7047 {
7048 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
7049 }
7050
7051 \f
7052 static void
7053 remote_kill (struct target_ops *ops)
7054 {
7055 /* Use catch_errors so the user can quit from gdb even when we
7056 aren't on speaking terms with the remote system. */
7057 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
7058
7059 /* Don't wait for it to die. I'm not really sure it matters whether
7060 we do or not. For the existing stubs, kill is a noop. */
7061 target_mourn_inferior ();
7062 }
7063
7064 static int
7065 remote_vkill (int pid, struct remote_state *rs)
7066 {
7067 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7068 return -1;
7069
7070 /* Tell the remote target to detach. */
7071 sprintf (rs->buf, "vKill;%x", pid);
7072 putpkt (rs->buf);
7073 getpkt (&rs->buf, &rs->buf_size, 0);
7074
7075 if (packet_ok (rs->buf,
7076 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7077 return 0;
7078 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7079 return -1;
7080 else
7081 return 1;
7082 }
7083
7084 static void
7085 extended_remote_kill (struct target_ops *ops)
7086 {
7087 int res;
7088 int pid = ptid_get_pid (inferior_ptid);
7089 struct remote_state *rs = get_remote_state ();
7090
7091 res = remote_vkill (pid, rs);
7092 if (res == -1 && !remote_multi_process_p (rs))
7093 {
7094 /* Don't try 'k' on a multi-process aware stub -- it has no way
7095 to specify the pid. */
7096
7097 putpkt ("k");
7098 #if 0
7099 getpkt (&rs->buf, &rs->buf_size, 0);
7100 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7101 res = 1;
7102 #else
7103 /* Don't wait for it to die. I'm not really sure it matters whether
7104 we do or not. For the existing stubs, kill is a noop. */
7105 res = 0;
7106 #endif
7107 }
7108
7109 if (res != 0)
7110 error (_("Can't kill process"));
7111
7112 target_mourn_inferior ();
7113 }
7114
7115 static void
7116 remote_mourn (struct target_ops *ops)
7117 {
7118 remote_mourn_1 (ops);
7119 }
7120
7121 /* Worker function for remote_mourn. */
7122 static void
7123 remote_mourn_1 (struct target_ops *target)
7124 {
7125 unpush_target (target);
7126
7127 /* remote_close takes care of doing most of the clean up. */
7128 generic_mourn_inferior ();
7129 }
7130
7131 static void
7132 extended_remote_mourn_1 (struct target_ops *target)
7133 {
7134 struct remote_state *rs = get_remote_state ();
7135
7136 /* In case we got here due to an error, but we're going to stay
7137 connected. */
7138 rs->waiting_for_stop_reply = 0;
7139
7140 /* We're no longer interested in these events. */
7141 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
7142
7143 /* If the current general thread belonged to the process we just
7144 detached from or has exited, the remote side current general
7145 thread becomes undefined. Considering a case like this:
7146
7147 - We just got here due to a detach.
7148 - The process that we're detaching from happens to immediately
7149 report a global breakpoint being hit in non-stop mode, in the
7150 same thread we had selected before.
7151 - GDB attaches to this process again.
7152 - This event happens to be the next event we handle.
7153
7154 GDB would consider that the current general thread didn't need to
7155 be set on the stub side (with Hg), since for all it knew,
7156 GENERAL_THREAD hadn't changed.
7157
7158 Notice that although in all-stop mode, the remote server always
7159 sets the current thread to the thread reporting the stop event,
7160 that doesn't happen in non-stop mode; in non-stop, the stub *must
7161 not* change the current thread when reporting a breakpoint hit,
7162 due to the decoupling of event reporting and event handling.
7163
7164 To keep things simple, we always invalidate our notion of the
7165 current thread. */
7166 record_currthread (minus_one_ptid);
7167
7168 /* Unlike "target remote", we do not want to unpush the target; then
7169 the next time the user says "run", we won't be connected. */
7170
7171 /* Call common code to mark the inferior as not running. */
7172 generic_mourn_inferior ();
7173
7174 if (!have_inferiors ())
7175 {
7176 if (!remote_multi_process_p (rs))
7177 {
7178 /* Check whether the target is running now - some remote stubs
7179 automatically restart after kill. */
7180 putpkt ("?");
7181 getpkt (&rs->buf, &rs->buf_size, 0);
7182
7183 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7184 {
7185 /* Assume that the target has been restarted. Set inferior_ptid
7186 so that bits of core GDB realizes there's something here, e.g.,
7187 so that the user can say "kill" again. */
7188 inferior_ptid = magic_null_ptid;
7189 }
7190 }
7191 }
7192 }
7193
7194 static void
7195 extended_remote_mourn (struct target_ops *ops)
7196 {
7197 extended_remote_mourn_1 (ops);
7198 }
7199
7200 static int
7201 extended_remote_run (char *args)
7202 {
7203 struct remote_state *rs = get_remote_state ();
7204 int len;
7205
7206 /* If the user has disabled vRun support, or we have detected that
7207 support is not available, do not try it. */
7208 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7209 return -1;
7210
7211 strcpy (rs->buf, "vRun;");
7212 len = strlen (rs->buf);
7213
7214 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7215 error (_("Remote file name too long for run packet"));
7216 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7217
7218 gdb_assert (args != NULL);
7219 if (*args)
7220 {
7221 struct cleanup *back_to;
7222 int i;
7223 char **argv;
7224
7225 argv = gdb_buildargv (args);
7226 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7227 for (i = 0; argv[i] != NULL; i++)
7228 {
7229 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7230 error (_("Argument list too long for run packet"));
7231 rs->buf[len++] = ';';
7232 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7233 }
7234 do_cleanups (back_to);
7235 }
7236
7237 rs->buf[len++] = '\0';
7238
7239 putpkt (rs->buf);
7240 getpkt (&rs->buf, &rs->buf_size, 0);
7241
7242 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7243 {
7244 /* We have a wait response; we don't need it, though. All is well. */
7245 return 0;
7246 }
7247 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7248 /* It wasn't disabled before, but it is now. */
7249 return -1;
7250 else
7251 {
7252 if (remote_exec_file[0] == '\0')
7253 error (_("Running the default executable on the remote target failed; "
7254 "try \"set remote exec-file\"?"));
7255 else
7256 error (_("Running \"%s\" on the remote target failed"),
7257 remote_exec_file);
7258 }
7259 }
7260
7261 /* In the extended protocol we want to be able to do things like
7262 "run" and have them basically work as expected. So we need
7263 a special create_inferior function. We support changing the
7264 executable file and the command line arguments, but not the
7265 environment. */
7266
7267 static void
7268 extended_remote_create_inferior_1 (char *exec_file, char *args,
7269 char **env, int from_tty)
7270 {
7271 /* If running asynchronously, register the target file descriptor
7272 with the event loop. */
7273 if (target_can_async_p ())
7274 target_async (inferior_event_handler, 0);
7275
7276 /* Now restart the remote server. */
7277 if (extended_remote_run (args) == -1)
7278 {
7279 /* vRun was not supported. Fail if we need it to do what the
7280 user requested. */
7281 if (remote_exec_file[0])
7282 error (_("Remote target does not support \"set remote exec-file\""));
7283 if (args[0])
7284 error (_("Remote target does not support \"set args\" or run <ARGS>"));
7285
7286 /* Fall back to "R". */
7287 extended_remote_restart ();
7288 }
7289
7290 if (!have_inferiors ())
7291 {
7292 /* Clean up from the last time we ran, before we mark the target
7293 running again. This will mark breakpoints uninserted, and
7294 get_offsets may insert breakpoints. */
7295 init_thread_list ();
7296 init_wait_for_inferior ();
7297 }
7298
7299 /* Now mark the inferior as running before we do anything else. */
7300 inferior_ptid = magic_null_ptid;
7301
7302 /* Now, if we have thread information, update inferior_ptid. */
7303 inferior_ptid = remote_current_thread (inferior_ptid);
7304
7305 remote_add_inferior (ptid_get_pid (inferior_ptid), 0);
7306 add_thread_silent (inferior_ptid);
7307
7308 /* Get updated offsets, if the stub uses qOffsets. */
7309 get_offsets ();
7310 }
7311
7312 static void
7313 extended_remote_create_inferior (struct target_ops *ops,
7314 char *exec_file, char *args,
7315 char **env, int from_tty)
7316 {
7317 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
7318 }
7319 \f
7320
7321 /* Insert a breakpoint. On targets that have software breakpoint
7322 support, we ask the remote target to do the work; on targets
7323 which don't, we insert a traditional memory breakpoint. */
7324
7325 static int
7326 remote_insert_breakpoint (struct gdbarch *gdbarch,
7327 struct bp_target_info *bp_tgt)
7328 {
7329 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
7330 If it succeeds, then set the support to PACKET_ENABLE. If it
7331 fails, and the user has explicitly requested the Z support then
7332 report an error, otherwise, mark it disabled and go on. */
7333
7334 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7335 {
7336 CORE_ADDR addr = bp_tgt->placed_address;
7337 struct remote_state *rs;
7338 char *p;
7339 int bpsize;
7340
7341 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
7342
7343 rs = get_remote_state ();
7344 p = rs->buf;
7345
7346 *(p++) = 'Z';
7347 *(p++) = '0';
7348 *(p++) = ',';
7349 addr = (ULONGEST) remote_address_masked (addr);
7350 p += hexnumstr (p, addr);
7351 sprintf (p, ",%d", bpsize);
7352
7353 putpkt (rs->buf);
7354 getpkt (&rs->buf, &rs->buf_size, 0);
7355
7356 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
7357 {
7358 case PACKET_ERROR:
7359 return -1;
7360 case PACKET_OK:
7361 bp_tgt->placed_address = addr;
7362 bp_tgt->placed_size = bpsize;
7363 return 0;
7364 case PACKET_UNKNOWN:
7365 break;
7366 }
7367 }
7368
7369 return memory_insert_breakpoint (gdbarch, bp_tgt);
7370 }
7371
7372 static int
7373 remote_remove_breakpoint (struct gdbarch *gdbarch,
7374 struct bp_target_info *bp_tgt)
7375 {
7376 CORE_ADDR addr = bp_tgt->placed_address;
7377 struct remote_state *rs = get_remote_state ();
7378
7379 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7380 {
7381 char *p = rs->buf;
7382
7383 *(p++) = 'z';
7384 *(p++) = '0';
7385 *(p++) = ',';
7386
7387 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
7388 p += hexnumstr (p, addr);
7389 sprintf (p, ",%d", bp_tgt->placed_size);
7390
7391 putpkt (rs->buf);
7392 getpkt (&rs->buf, &rs->buf_size, 0);
7393
7394 return (rs->buf[0] == 'E');
7395 }
7396
7397 return memory_remove_breakpoint (gdbarch, bp_tgt);
7398 }
7399
7400 static int
7401 watchpoint_to_Z_packet (int type)
7402 {
7403 switch (type)
7404 {
7405 case hw_write:
7406 return Z_PACKET_WRITE_WP;
7407 break;
7408 case hw_read:
7409 return Z_PACKET_READ_WP;
7410 break;
7411 case hw_access:
7412 return Z_PACKET_ACCESS_WP;
7413 break;
7414 default:
7415 internal_error (__FILE__, __LINE__,
7416 _("hw_bp_to_z: bad watchpoint type %d"), type);
7417 }
7418 }
7419
7420 static int
7421 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
7422 {
7423 struct remote_state *rs = get_remote_state ();
7424 char *p;
7425 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7426
7427 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7428 return 1;
7429
7430 sprintf (rs->buf, "Z%x,", packet);
7431 p = strchr (rs->buf, '\0');
7432 addr = remote_address_masked (addr);
7433 p += hexnumstr (p, (ULONGEST) addr);
7434 sprintf (p, ",%x", len);
7435
7436 putpkt (rs->buf);
7437 getpkt (&rs->buf, &rs->buf_size, 0);
7438
7439 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7440 {
7441 case PACKET_ERROR:
7442 return -1;
7443 case PACKET_UNKNOWN:
7444 return 1;
7445 case PACKET_OK:
7446 return 0;
7447 }
7448 internal_error (__FILE__, __LINE__,
7449 _("remote_insert_watchpoint: reached end of function"));
7450 }
7451
7452
7453 static int
7454 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
7455 {
7456 struct remote_state *rs = get_remote_state ();
7457 char *p;
7458 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7459
7460 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7461 return -1;
7462
7463 sprintf (rs->buf, "z%x,", packet);
7464 p = strchr (rs->buf, '\0');
7465 addr = remote_address_masked (addr);
7466 p += hexnumstr (p, (ULONGEST) addr);
7467 sprintf (p, ",%x", len);
7468 putpkt (rs->buf);
7469 getpkt (&rs->buf, &rs->buf_size, 0);
7470
7471 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7472 {
7473 case PACKET_ERROR:
7474 case PACKET_UNKNOWN:
7475 return -1;
7476 case PACKET_OK:
7477 return 0;
7478 }
7479 internal_error (__FILE__, __LINE__,
7480 _("remote_remove_watchpoint: reached end of function"));
7481 }
7482
7483
7484 int remote_hw_watchpoint_limit = -1;
7485 int remote_hw_breakpoint_limit = -1;
7486
7487 static int
7488 remote_check_watch_resources (int type, int cnt, int ot)
7489 {
7490 if (type == bp_hardware_breakpoint)
7491 {
7492 if (remote_hw_breakpoint_limit == 0)
7493 return 0;
7494 else if (remote_hw_breakpoint_limit < 0)
7495 return 1;
7496 else if (cnt <= remote_hw_breakpoint_limit)
7497 return 1;
7498 }
7499 else
7500 {
7501 if (remote_hw_watchpoint_limit == 0)
7502 return 0;
7503 else if (remote_hw_watchpoint_limit < 0)
7504 return 1;
7505 else if (ot)
7506 return -1;
7507 else if (cnt <= remote_hw_watchpoint_limit)
7508 return 1;
7509 }
7510 return -1;
7511 }
7512
7513 static int
7514 remote_stopped_by_watchpoint (void)
7515 {
7516 return remote_stopped_by_watchpoint_p;
7517 }
7518
7519 static int
7520 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
7521 {
7522 int rc = 0;
7523 if (remote_stopped_by_watchpoint ())
7524 {
7525 *addr_p = remote_watch_data_address;
7526 rc = 1;
7527 }
7528
7529 return rc;
7530 }
7531
7532
7533 static int
7534 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
7535 struct bp_target_info *bp_tgt)
7536 {
7537 CORE_ADDR addr;
7538 struct remote_state *rs;
7539 char *p;
7540
7541 /* The length field should be set to the size of a breakpoint
7542 instruction, even though we aren't inserting one ourselves. */
7543
7544 gdbarch_remote_breakpoint_from_pc
7545 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
7546
7547 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7548 return -1;
7549
7550 rs = get_remote_state ();
7551 p = rs->buf;
7552
7553 *(p++) = 'Z';
7554 *(p++) = '1';
7555 *(p++) = ',';
7556
7557 addr = remote_address_masked (bp_tgt->placed_address);
7558 p += hexnumstr (p, (ULONGEST) addr);
7559 sprintf (p, ",%x", bp_tgt->placed_size);
7560
7561 putpkt (rs->buf);
7562 getpkt (&rs->buf, &rs->buf_size, 0);
7563
7564 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7565 {
7566 case PACKET_ERROR:
7567 case PACKET_UNKNOWN:
7568 return -1;
7569 case PACKET_OK:
7570 return 0;
7571 }
7572 internal_error (__FILE__, __LINE__,
7573 _("remote_insert_hw_breakpoint: reached end of function"));
7574 }
7575
7576
7577 static int
7578 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
7579 struct bp_target_info *bp_tgt)
7580 {
7581 CORE_ADDR addr;
7582 struct remote_state *rs = get_remote_state ();
7583 char *p = rs->buf;
7584
7585 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7586 return -1;
7587
7588 *(p++) = 'z';
7589 *(p++) = '1';
7590 *(p++) = ',';
7591
7592 addr = remote_address_masked (bp_tgt->placed_address);
7593 p += hexnumstr (p, (ULONGEST) addr);
7594 sprintf (p, ",%x", bp_tgt->placed_size);
7595
7596 putpkt (rs->buf);
7597 getpkt (&rs->buf, &rs->buf_size, 0);
7598
7599 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7600 {
7601 case PACKET_ERROR:
7602 case PACKET_UNKNOWN:
7603 return -1;
7604 case PACKET_OK:
7605 return 0;
7606 }
7607 internal_error (__FILE__, __LINE__,
7608 _("remote_remove_hw_breakpoint: reached end of function"));
7609 }
7610
7611 /* Table used by the crc32 function to calcuate the checksum. */
7612
7613 static unsigned long crc32_table[256] =
7614 {0, 0};
7615
7616 static unsigned long
7617 crc32 (const unsigned char *buf, int len, unsigned int crc)
7618 {
7619 if (!crc32_table[1])
7620 {
7621 /* Initialize the CRC table and the decoding table. */
7622 int i, j;
7623 unsigned int c;
7624
7625 for (i = 0; i < 256; i++)
7626 {
7627 for (c = i << 24, j = 8; j > 0; --j)
7628 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
7629 crc32_table[i] = c;
7630 }
7631 }
7632
7633 while (len--)
7634 {
7635 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
7636 buf++;
7637 }
7638 return crc;
7639 }
7640
7641 /* Verify memory using the "qCRC:" request. */
7642
7643 static int
7644 remote_verify_memory (struct target_ops *ops,
7645 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
7646 {
7647 struct remote_state *rs = get_remote_state ();
7648 unsigned long host_crc, target_crc;
7649 char *tmp;
7650
7651 /* FIXME: assumes lma can fit into long. */
7652 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
7653 (long) lma, (long) size);
7654 putpkt (rs->buf);
7655
7656 /* Be clever; compute the host_crc before waiting for target
7657 reply. */
7658 host_crc = crc32 (data, size, 0xffffffff);
7659
7660 getpkt (&rs->buf, &rs->buf_size, 0);
7661 if (rs->buf[0] == 'E')
7662 return -1;
7663
7664 if (rs->buf[0] != 'C')
7665 error (_("remote target does not support this operation"));
7666
7667 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
7668 target_crc = target_crc * 16 + fromhex (*tmp);
7669
7670 return (host_crc == target_crc);
7671 }
7672
7673 /* compare-sections command
7674
7675 With no arguments, compares each loadable section in the exec bfd
7676 with the same memory range on the target, and reports mismatches.
7677 Useful for verifying the image on the target against the exec file. */
7678
7679 static void
7680 compare_sections_command (char *args, int from_tty)
7681 {
7682 asection *s;
7683 struct cleanup *old_chain;
7684 char *sectdata;
7685 const char *sectname;
7686 bfd_size_type size;
7687 bfd_vma lma;
7688 int matched = 0;
7689 int mismatched = 0;
7690 int res;
7691
7692 if (!exec_bfd)
7693 error (_("command cannot be used without an exec file"));
7694
7695 for (s = exec_bfd->sections; s; s = s->next)
7696 {
7697 if (!(s->flags & SEC_LOAD))
7698 continue; /* skip non-loadable section */
7699
7700 size = bfd_get_section_size (s);
7701 if (size == 0)
7702 continue; /* skip zero-length section */
7703
7704 sectname = bfd_get_section_name (exec_bfd, s);
7705 if (args && strcmp (args, sectname) != 0)
7706 continue; /* not the section selected by user */
7707
7708 matched = 1; /* do this section */
7709 lma = s->lma;
7710
7711 sectdata = xmalloc (size);
7712 old_chain = make_cleanup (xfree, sectdata);
7713 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
7714
7715 res = target_verify_memory (sectdata, lma, size);
7716
7717 if (res == -1)
7718 error (_("target memory fault, section %s, range %s -- %s"), sectname,
7719 paddress (target_gdbarch, lma),
7720 paddress (target_gdbarch, lma + size));
7721
7722 printf_filtered ("Section %s, range %s -- %s: ", sectname,
7723 paddress (target_gdbarch, lma),
7724 paddress (target_gdbarch, lma + size));
7725 if (res)
7726 printf_filtered ("matched.\n");
7727 else
7728 {
7729 printf_filtered ("MIS-MATCHED!\n");
7730 mismatched++;
7731 }
7732
7733 do_cleanups (old_chain);
7734 }
7735 if (mismatched > 0)
7736 warning (_("One or more sections of the remote executable does not match\n\
7737 the loaded file\n"));
7738 if (args && !matched)
7739 printf_filtered (_("No loaded section named '%s'.\n"), args);
7740 }
7741
7742 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
7743 into remote target. The number of bytes written to the remote
7744 target is returned, or -1 for error. */
7745
7746 static LONGEST
7747 remote_write_qxfer (struct target_ops *ops, const char *object_name,
7748 const char *annex, const gdb_byte *writebuf,
7749 ULONGEST offset, LONGEST len,
7750 struct packet_config *packet)
7751 {
7752 int i, buf_len;
7753 ULONGEST n;
7754 struct remote_state *rs = get_remote_state ();
7755 int max_size = get_memory_write_packet_size ();
7756
7757 if (packet->support == PACKET_DISABLE)
7758 return -1;
7759
7760 /* Insert header. */
7761 i = snprintf (rs->buf, max_size,
7762 "qXfer:%s:write:%s:%s:",
7763 object_name, annex ? annex : "",
7764 phex_nz (offset, sizeof offset));
7765 max_size -= (i + 1);
7766
7767 /* Escape as much data as fits into rs->buf. */
7768 buf_len = remote_escape_output
7769 (writebuf, len, (rs->buf + i), &max_size, max_size);
7770
7771 if (putpkt_binary (rs->buf, i + buf_len) < 0
7772 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7773 || packet_ok (rs->buf, packet) != PACKET_OK)
7774 return -1;
7775
7776 unpack_varlen_hex (rs->buf, &n);
7777 return n;
7778 }
7779
7780 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
7781 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
7782 number of bytes read is returned, or 0 for EOF, or -1 for error.
7783 The number of bytes read may be less than LEN without indicating an
7784 EOF. PACKET is checked and updated to indicate whether the remote
7785 target supports this object. */
7786
7787 static LONGEST
7788 remote_read_qxfer (struct target_ops *ops, const char *object_name,
7789 const char *annex,
7790 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
7791 struct packet_config *packet)
7792 {
7793 static char *finished_object;
7794 static char *finished_annex;
7795 static ULONGEST finished_offset;
7796
7797 struct remote_state *rs = get_remote_state ();
7798 LONGEST i, n, packet_len;
7799
7800 if (packet->support == PACKET_DISABLE)
7801 return -1;
7802
7803 /* Check whether we've cached an end-of-object packet that matches
7804 this request. */
7805 if (finished_object)
7806 {
7807 if (strcmp (object_name, finished_object) == 0
7808 && strcmp (annex ? annex : "", finished_annex) == 0
7809 && offset == finished_offset)
7810 return 0;
7811
7812 /* Otherwise, we're now reading something different. Discard
7813 the cache. */
7814 xfree (finished_object);
7815 xfree (finished_annex);
7816 finished_object = NULL;
7817 finished_annex = NULL;
7818 }
7819
7820 /* Request only enough to fit in a single packet. The actual data
7821 may not, since we don't know how much of it will need to be escaped;
7822 the target is free to respond with slightly less data. We subtract
7823 five to account for the response type and the protocol frame. */
7824 n = min (get_remote_packet_size () - 5, len);
7825 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
7826 object_name, annex ? annex : "",
7827 phex_nz (offset, sizeof offset),
7828 phex_nz (n, sizeof n));
7829 i = putpkt (rs->buf);
7830 if (i < 0)
7831 return -1;
7832
7833 rs->buf[0] = '\0';
7834 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
7835 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
7836 return -1;
7837
7838 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
7839 error (_("Unknown remote qXfer reply: %s"), rs->buf);
7840
7841 /* 'm' means there is (or at least might be) more data after this
7842 batch. That does not make sense unless there's at least one byte
7843 of data in this reply. */
7844 if (rs->buf[0] == 'm' && packet_len == 1)
7845 error (_("Remote qXfer reply contained no data."));
7846
7847 /* Got some data. */
7848 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
7849
7850 /* 'l' is an EOF marker, possibly including a final block of data,
7851 or possibly empty. If we have the final block of a non-empty
7852 object, record this fact to bypass a subsequent partial read. */
7853 if (rs->buf[0] == 'l' && offset + i > 0)
7854 {
7855 finished_object = xstrdup (object_name);
7856 finished_annex = xstrdup (annex ? annex : "");
7857 finished_offset = offset + i;
7858 }
7859
7860 return i;
7861 }
7862
7863 static LONGEST
7864 remote_xfer_partial (struct target_ops *ops, enum target_object object,
7865 const char *annex, gdb_byte *readbuf,
7866 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
7867 {
7868 struct remote_state *rs;
7869 int i;
7870 char *p2;
7871 char query_type;
7872
7873 set_general_thread (inferior_ptid);
7874
7875 rs = get_remote_state ();
7876
7877 /* Handle memory using the standard memory routines. */
7878 if (object == TARGET_OBJECT_MEMORY)
7879 {
7880 int xfered;
7881 errno = 0;
7882
7883 /* If the remote target is connected but not running, we should
7884 pass this request down to a lower stratum (e.g. the executable
7885 file). */
7886 if (!target_has_execution)
7887 return 0;
7888
7889 if (writebuf != NULL)
7890 xfered = remote_write_bytes (offset, writebuf, len);
7891 else
7892 xfered = remote_read_bytes (offset, readbuf, len);
7893
7894 if (xfered > 0)
7895 return xfered;
7896 else if (xfered == 0 && errno == 0)
7897 return 0;
7898 else
7899 return -1;
7900 }
7901
7902 /* Handle SPU memory using qxfer packets. */
7903 if (object == TARGET_OBJECT_SPU)
7904 {
7905 if (readbuf)
7906 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
7907 &remote_protocol_packets
7908 [PACKET_qXfer_spu_read]);
7909 else
7910 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
7911 &remote_protocol_packets
7912 [PACKET_qXfer_spu_write]);
7913 }
7914
7915 /* Handle extra signal info using qxfer packets. */
7916 if (object == TARGET_OBJECT_SIGNAL_INFO)
7917 {
7918 if (readbuf)
7919 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
7920 &remote_protocol_packets
7921 [PACKET_qXfer_siginfo_read]);
7922 else
7923 return remote_write_qxfer (ops, "siginfo", annex, writebuf, offset, len,
7924 &remote_protocol_packets
7925 [PACKET_qXfer_siginfo_write]);
7926 }
7927
7928 /* Only handle flash writes. */
7929 if (writebuf != NULL)
7930 {
7931 LONGEST xfered;
7932
7933 switch (object)
7934 {
7935 case TARGET_OBJECT_FLASH:
7936 xfered = remote_flash_write (ops, offset, len, writebuf);
7937
7938 if (xfered > 0)
7939 return xfered;
7940 else if (xfered == 0 && errno == 0)
7941 return 0;
7942 else
7943 return -1;
7944
7945 default:
7946 return -1;
7947 }
7948 }
7949
7950 /* Map pre-existing objects onto letters. DO NOT do this for new
7951 objects!!! Instead specify new query packets. */
7952 switch (object)
7953 {
7954 case TARGET_OBJECT_AVR:
7955 query_type = 'R';
7956 break;
7957
7958 case TARGET_OBJECT_AUXV:
7959 gdb_assert (annex == NULL);
7960 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
7961 &remote_protocol_packets[PACKET_qXfer_auxv]);
7962
7963 case TARGET_OBJECT_AVAILABLE_FEATURES:
7964 return remote_read_qxfer
7965 (ops, "features", annex, readbuf, offset, len,
7966 &remote_protocol_packets[PACKET_qXfer_features]);
7967
7968 case TARGET_OBJECT_LIBRARIES:
7969 return remote_read_qxfer
7970 (ops, "libraries", annex, readbuf, offset, len,
7971 &remote_protocol_packets[PACKET_qXfer_libraries]);
7972
7973 case TARGET_OBJECT_MEMORY_MAP:
7974 gdb_assert (annex == NULL);
7975 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
7976 &remote_protocol_packets[PACKET_qXfer_memory_map]);
7977
7978 case TARGET_OBJECT_OSDATA:
7979 /* Should only get here if we're connected. */
7980 gdb_assert (remote_desc);
7981 return remote_read_qxfer
7982 (ops, "osdata", annex, readbuf, offset, len,
7983 &remote_protocol_packets[PACKET_qXfer_osdata]);
7984
7985 case TARGET_OBJECT_THREADS:
7986 gdb_assert (annex == NULL);
7987 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
7988 &remote_protocol_packets[PACKET_qXfer_threads]);
7989
7990 default:
7991 return -1;
7992 }
7993
7994 /* Note: a zero OFFSET and LEN can be used to query the minimum
7995 buffer size. */
7996 if (offset == 0 && len == 0)
7997 return (get_remote_packet_size ());
7998 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
7999 large enough let the caller deal with it. */
8000 if (len < get_remote_packet_size ())
8001 return -1;
8002 len = get_remote_packet_size ();
8003
8004 /* Except for querying the minimum buffer size, target must be open. */
8005 if (!remote_desc)
8006 error (_("remote query is only available after target open"));
8007
8008 gdb_assert (annex != NULL);
8009 gdb_assert (readbuf != NULL);
8010
8011 p2 = rs->buf;
8012 *p2++ = 'q';
8013 *p2++ = query_type;
8014
8015 /* We used one buffer char for the remote protocol q command and
8016 another for the query type. As the remote protocol encapsulation
8017 uses 4 chars plus one extra in case we are debugging
8018 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8019 string. */
8020 i = 0;
8021 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8022 {
8023 /* Bad caller may have sent forbidden characters. */
8024 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8025 *p2++ = annex[i];
8026 i++;
8027 }
8028 *p2 = '\0';
8029 gdb_assert (annex[i] == '\0');
8030
8031 i = putpkt (rs->buf);
8032 if (i < 0)
8033 return i;
8034
8035 getpkt (&rs->buf, &rs->buf_size, 0);
8036 strcpy ((char *) readbuf, rs->buf);
8037
8038 return strlen ((char *) readbuf);
8039 }
8040
8041 static int
8042 remote_search_memory (struct target_ops* ops,
8043 CORE_ADDR start_addr, ULONGEST search_space_len,
8044 const gdb_byte *pattern, ULONGEST pattern_len,
8045 CORE_ADDR *found_addrp)
8046 {
8047 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
8048 struct remote_state *rs = get_remote_state ();
8049 int max_size = get_memory_write_packet_size ();
8050 struct packet_config *packet =
8051 &remote_protocol_packets[PACKET_qSearch_memory];
8052 /* number of packet bytes used to encode the pattern,
8053 this could be more than PATTERN_LEN due to escape characters */
8054 int escaped_pattern_len;
8055 /* amount of pattern that was encodable in the packet */
8056 int used_pattern_len;
8057 int i;
8058 int found;
8059 ULONGEST found_addr;
8060
8061 /* Don't go to the target if we don't have to.
8062 This is done before checking packet->support to avoid the possibility that
8063 a success for this edge case means the facility works in general. */
8064 if (pattern_len > search_space_len)
8065 return 0;
8066 if (pattern_len == 0)
8067 {
8068 *found_addrp = start_addr;
8069 return 1;
8070 }
8071
8072 /* If we already know the packet isn't supported, fall back to the simple
8073 way of searching memory. */
8074
8075 if (packet->support == PACKET_DISABLE)
8076 {
8077 /* Target doesn't provided special support, fall back and use the
8078 standard support (copy memory and do the search here). */
8079 return simple_search_memory (ops, start_addr, search_space_len,
8080 pattern, pattern_len, found_addrp);
8081 }
8082
8083 /* Insert header. */
8084 i = snprintf (rs->buf, max_size,
8085 "qSearch:memory:%s;%s;",
8086 phex_nz (start_addr, addr_size),
8087 phex_nz (search_space_len, sizeof (search_space_len)));
8088 max_size -= (i + 1);
8089
8090 /* Escape as much data as fits into rs->buf. */
8091 escaped_pattern_len =
8092 remote_escape_output (pattern, pattern_len, (rs->buf + i),
8093 &used_pattern_len, max_size);
8094
8095 /* Bail if the pattern is too large. */
8096 if (used_pattern_len != pattern_len)
8097 error ("Pattern is too large to transmit to remote target.");
8098
8099 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8100 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8101 || packet_ok (rs->buf, packet) != PACKET_OK)
8102 {
8103 /* The request may not have worked because the command is not
8104 supported. If so, fall back to the simple way. */
8105 if (packet->support == PACKET_DISABLE)
8106 {
8107 return simple_search_memory (ops, start_addr, search_space_len,
8108 pattern, pattern_len, found_addrp);
8109 }
8110 return -1;
8111 }
8112
8113 if (rs->buf[0] == '0')
8114 found = 0;
8115 else if (rs->buf[0] == '1')
8116 {
8117 found = 1;
8118 if (rs->buf[1] != ',')
8119 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8120 unpack_varlen_hex (rs->buf + 2, &found_addr);
8121 *found_addrp = found_addr;
8122 }
8123 else
8124 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8125
8126 return found;
8127 }
8128
8129 static void
8130 remote_rcmd (char *command,
8131 struct ui_file *outbuf)
8132 {
8133 struct remote_state *rs = get_remote_state ();
8134 char *p = rs->buf;
8135
8136 if (!remote_desc)
8137 error (_("remote rcmd is only available after target open"));
8138
8139 /* Send a NULL command across as an empty command. */
8140 if (command == NULL)
8141 command = "";
8142
8143 /* The query prefix. */
8144 strcpy (rs->buf, "qRcmd,");
8145 p = strchr (rs->buf, '\0');
8146
8147 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
8148 error (_("\"monitor\" command ``%s'' is too long."), command);
8149
8150 /* Encode the actual command. */
8151 bin2hex ((gdb_byte *) command, p, 0);
8152
8153 if (putpkt (rs->buf) < 0)
8154 error (_("Communication problem with target."));
8155
8156 /* get/display the response */
8157 while (1)
8158 {
8159 char *buf;
8160
8161 /* XXX - see also remote_get_noisy_reply(). */
8162 rs->buf[0] = '\0';
8163 getpkt (&rs->buf, &rs->buf_size, 0);
8164 buf = rs->buf;
8165 if (buf[0] == '\0')
8166 error (_("Target does not support this command."));
8167 if (buf[0] == 'O' && buf[1] != 'K')
8168 {
8169 remote_console_output (buf + 1); /* 'O' message from stub. */
8170 continue;
8171 }
8172 if (strcmp (buf, "OK") == 0)
8173 break;
8174 if (strlen (buf) == 3 && buf[0] == 'E'
8175 && isdigit (buf[1]) && isdigit (buf[2]))
8176 {
8177 error (_("Protocol error with Rcmd"));
8178 }
8179 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
8180 {
8181 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
8182 fputc_unfiltered (c, outbuf);
8183 }
8184 break;
8185 }
8186 }
8187
8188 static VEC(mem_region_s) *
8189 remote_memory_map (struct target_ops *ops)
8190 {
8191 VEC(mem_region_s) *result = NULL;
8192 char *text = target_read_stralloc (&current_target,
8193 TARGET_OBJECT_MEMORY_MAP, NULL);
8194
8195 if (text)
8196 {
8197 struct cleanup *back_to = make_cleanup (xfree, text);
8198 result = parse_memory_map (text);
8199 do_cleanups (back_to);
8200 }
8201
8202 return result;
8203 }
8204
8205 static void
8206 packet_command (char *args, int from_tty)
8207 {
8208 struct remote_state *rs = get_remote_state ();
8209
8210 if (!remote_desc)
8211 error (_("command can only be used with remote target"));
8212
8213 if (!args)
8214 error (_("remote-packet command requires packet text as argument"));
8215
8216 puts_filtered ("sending: ");
8217 print_packet (args);
8218 puts_filtered ("\n");
8219 putpkt (args);
8220
8221 getpkt (&rs->buf, &rs->buf_size, 0);
8222 puts_filtered ("received: ");
8223 print_packet (rs->buf);
8224 puts_filtered ("\n");
8225 }
8226
8227 #if 0
8228 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
8229
8230 static void display_thread_info (struct gdb_ext_thread_info *info);
8231
8232 static void threadset_test_cmd (char *cmd, int tty);
8233
8234 static void threadalive_test (char *cmd, int tty);
8235
8236 static void threadlist_test_cmd (char *cmd, int tty);
8237
8238 int get_and_display_threadinfo (threadref *ref);
8239
8240 static void threadinfo_test_cmd (char *cmd, int tty);
8241
8242 static int thread_display_step (threadref *ref, void *context);
8243
8244 static void threadlist_update_test_cmd (char *cmd, int tty);
8245
8246 static void init_remote_threadtests (void);
8247
8248 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
8249
8250 static void
8251 threadset_test_cmd (char *cmd, int tty)
8252 {
8253 int sample_thread = SAMPLE_THREAD;
8254
8255 printf_filtered (_("Remote threadset test\n"));
8256 set_general_thread (sample_thread);
8257 }
8258
8259
8260 static void
8261 threadalive_test (char *cmd, int tty)
8262 {
8263 int sample_thread = SAMPLE_THREAD;
8264 int pid = ptid_get_pid (inferior_ptid);
8265 ptid_t ptid = ptid_build (pid, 0, sample_thread);
8266
8267 if (remote_thread_alive (ptid))
8268 printf_filtered ("PASS: Thread alive test\n");
8269 else
8270 printf_filtered ("FAIL: Thread alive test\n");
8271 }
8272
8273 void output_threadid (char *title, threadref *ref);
8274
8275 void
8276 output_threadid (char *title, threadref *ref)
8277 {
8278 char hexid[20];
8279
8280 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
8281 hexid[16] = 0;
8282 printf_filtered ("%s %s\n", title, (&hexid[0]));
8283 }
8284
8285 static void
8286 threadlist_test_cmd (char *cmd, int tty)
8287 {
8288 int startflag = 1;
8289 threadref nextthread;
8290 int done, result_count;
8291 threadref threadlist[3];
8292
8293 printf_filtered ("Remote Threadlist test\n");
8294 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
8295 &result_count, &threadlist[0]))
8296 printf_filtered ("FAIL: threadlist test\n");
8297 else
8298 {
8299 threadref *scan = threadlist;
8300 threadref *limit = scan + result_count;
8301
8302 while (scan < limit)
8303 output_threadid (" thread ", scan++);
8304 }
8305 }
8306
8307 void
8308 display_thread_info (struct gdb_ext_thread_info *info)
8309 {
8310 output_threadid ("Threadid: ", &info->threadid);
8311 printf_filtered ("Name: %s\n ", info->shortname);
8312 printf_filtered ("State: %s\n", info->display);
8313 printf_filtered ("other: %s\n\n", info->more_display);
8314 }
8315
8316 int
8317 get_and_display_threadinfo (threadref *ref)
8318 {
8319 int result;
8320 int set;
8321 struct gdb_ext_thread_info threadinfo;
8322
8323 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
8324 | TAG_MOREDISPLAY | TAG_DISPLAY;
8325 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
8326 display_thread_info (&threadinfo);
8327 return result;
8328 }
8329
8330 static void
8331 threadinfo_test_cmd (char *cmd, int tty)
8332 {
8333 int athread = SAMPLE_THREAD;
8334 threadref thread;
8335 int set;
8336
8337 int_to_threadref (&thread, athread);
8338 printf_filtered ("Remote Threadinfo test\n");
8339 if (!get_and_display_threadinfo (&thread))
8340 printf_filtered ("FAIL cannot get thread info\n");
8341 }
8342
8343 static int
8344 thread_display_step (threadref *ref, void *context)
8345 {
8346 /* output_threadid(" threadstep ",ref); *//* simple test */
8347 return get_and_display_threadinfo (ref);
8348 }
8349
8350 static void
8351 threadlist_update_test_cmd (char *cmd, int tty)
8352 {
8353 printf_filtered ("Remote Threadlist update test\n");
8354 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
8355 }
8356
8357 static void
8358 init_remote_threadtests (void)
8359 {
8360 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
8361 Fetch and print the remote list of thread identifiers, one pkt only"));
8362 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
8363 _("Fetch and display info about one thread"));
8364 add_com ("tset", class_obscure, threadset_test_cmd,
8365 _("Test setting to a different thread"));
8366 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
8367 _("Iterate through updating all remote thread info"));
8368 add_com ("talive", class_obscure, threadalive_test,
8369 _(" Remote thread alive test "));
8370 }
8371
8372 #endif /* 0 */
8373
8374 /* Convert a thread ID to a string. Returns the string in a static
8375 buffer. */
8376
8377 static char *
8378 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
8379 {
8380 static char buf[64];
8381 struct remote_state *rs = get_remote_state ();
8382
8383 if (ptid_is_pid (ptid))
8384 {
8385 /* Printing an inferior target id. */
8386
8387 /* When multi-process extensions are off, there's no way in the
8388 remote protocol to know the remote process id, if there's any
8389 at all. There's one exception --- when we're connected with
8390 target extended-remote, and we manually attached to a process
8391 with "attach PID". We don't record anywhere a flag that
8392 allows us to distinguish that case from the case of
8393 connecting with extended-remote and the stub already being
8394 attached to a process, and reporting yes to qAttached, hence
8395 no smart special casing here. */
8396 if (!remote_multi_process_p (rs))
8397 {
8398 xsnprintf (buf, sizeof buf, "Remote target");
8399 return buf;
8400 }
8401
8402 return normal_pid_to_str (ptid);
8403 }
8404 else
8405 {
8406 if (ptid_equal (magic_null_ptid, ptid))
8407 xsnprintf (buf, sizeof buf, "Thread <main>");
8408 else if (remote_multi_process_p (rs))
8409 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
8410 ptid_get_pid (ptid), ptid_get_tid (ptid));
8411 else
8412 xsnprintf (buf, sizeof buf, "Thread %ld",
8413 ptid_get_tid (ptid));
8414 return buf;
8415 }
8416 }
8417
8418 /* Get the address of the thread local variable in OBJFILE which is
8419 stored at OFFSET within the thread local storage for thread PTID. */
8420
8421 static CORE_ADDR
8422 remote_get_thread_local_address (struct target_ops *ops,
8423 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
8424 {
8425 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
8426 {
8427 struct remote_state *rs = get_remote_state ();
8428 char *p = rs->buf;
8429 char *endp = rs->buf + get_remote_packet_size ();
8430 enum packet_result result;
8431
8432 strcpy (p, "qGetTLSAddr:");
8433 p += strlen (p);
8434 p = write_ptid (p, endp, ptid);
8435 *p++ = ',';
8436 p += hexnumstr (p, offset);
8437 *p++ = ',';
8438 p += hexnumstr (p, lm);
8439 *p++ = '\0';
8440
8441 putpkt (rs->buf);
8442 getpkt (&rs->buf, &rs->buf_size, 0);
8443 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
8444 if (result == PACKET_OK)
8445 {
8446 ULONGEST result;
8447
8448 unpack_varlen_hex (rs->buf, &result);
8449 return result;
8450 }
8451 else if (result == PACKET_UNKNOWN)
8452 throw_error (TLS_GENERIC_ERROR,
8453 _("Remote target doesn't support qGetTLSAddr packet"));
8454 else
8455 throw_error (TLS_GENERIC_ERROR,
8456 _("Remote target failed to process qGetTLSAddr request"));
8457 }
8458 else
8459 throw_error (TLS_GENERIC_ERROR,
8460 _("TLS not supported or disabled on this target"));
8461 /* Not reached. */
8462 return 0;
8463 }
8464
8465 /* Provide thread local base, i.e. Thread Information Block address.
8466 Returns 1 if ptid is found and thread_local_base is non zero. */
8467
8468 int
8469 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
8470 {
8471 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
8472 {
8473 struct remote_state *rs = get_remote_state ();
8474 char *p = rs->buf;
8475 char *endp = rs->buf + get_remote_packet_size ();
8476 enum packet_result result;
8477
8478 strcpy (p, "qGetTIBAddr:");
8479 p += strlen (p);
8480 p = write_ptid (p, endp, ptid);
8481 *p++ = '\0';
8482
8483 putpkt (rs->buf);
8484 getpkt (&rs->buf, &rs->buf_size, 0);
8485 result = packet_ok (rs->buf,
8486 &remote_protocol_packets[PACKET_qGetTIBAddr]);
8487 if (result == PACKET_OK)
8488 {
8489 ULONGEST result;
8490
8491 unpack_varlen_hex (rs->buf, &result);
8492 if (addr)
8493 *addr = (CORE_ADDR) result;
8494 return 1;
8495 }
8496 else if (result == PACKET_UNKNOWN)
8497 error (_("Remote target doesn't support qGetTIBAddr packet"));
8498 else
8499 error (_("Remote target failed to process qGetTIBAddr request"));
8500 }
8501 else
8502 error (_("qGetTIBAddr not supported or disabled on this target"));
8503 /* Not reached. */
8504 return 0;
8505 }
8506
8507 /* Support for inferring a target description based on the current
8508 architecture and the size of a 'g' packet. While the 'g' packet
8509 can have any size (since optional registers can be left off the
8510 end), some sizes are easily recognizable given knowledge of the
8511 approximate architecture. */
8512
8513 struct remote_g_packet_guess
8514 {
8515 int bytes;
8516 const struct target_desc *tdesc;
8517 };
8518 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
8519 DEF_VEC_O(remote_g_packet_guess_s);
8520
8521 struct remote_g_packet_data
8522 {
8523 VEC(remote_g_packet_guess_s) *guesses;
8524 };
8525
8526 static struct gdbarch_data *remote_g_packet_data_handle;
8527
8528 static void *
8529 remote_g_packet_data_init (struct obstack *obstack)
8530 {
8531 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
8532 }
8533
8534 void
8535 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
8536 const struct target_desc *tdesc)
8537 {
8538 struct remote_g_packet_data *data
8539 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
8540 struct remote_g_packet_guess new_guess, *guess;
8541 int ix;
8542
8543 gdb_assert (tdesc != NULL);
8544
8545 for (ix = 0;
8546 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8547 ix++)
8548 if (guess->bytes == bytes)
8549 internal_error (__FILE__, __LINE__,
8550 "Duplicate g packet description added for size %d",
8551 bytes);
8552
8553 new_guess.bytes = bytes;
8554 new_guess.tdesc = tdesc;
8555 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
8556 }
8557
8558 /* Return 1 if remote_read_description would do anything on this target
8559 and architecture, 0 otherwise. */
8560
8561 static int
8562 remote_read_description_p (struct target_ops *target)
8563 {
8564 struct remote_g_packet_data *data
8565 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8566
8567 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8568 return 1;
8569
8570 return 0;
8571 }
8572
8573 static const struct target_desc *
8574 remote_read_description (struct target_ops *target)
8575 {
8576 struct remote_g_packet_data *data
8577 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8578
8579 /* Do not try this during initial connection, when we do not know
8580 whether there is a running but stopped thread. */
8581 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
8582 return NULL;
8583
8584 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8585 {
8586 struct remote_g_packet_guess *guess;
8587 int ix;
8588 int bytes = send_g_packet ();
8589
8590 for (ix = 0;
8591 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8592 ix++)
8593 if (guess->bytes == bytes)
8594 return guess->tdesc;
8595
8596 /* We discard the g packet. A minor optimization would be to
8597 hold on to it, and fill the register cache once we have selected
8598 an architecture, but it's too tricky to do safely. */
8599 }
8600
8601 return NULL;
8602 }
8603
8604 /* Remote file transfer support. This is host-initiated I/O, not
8605 target-initiated; for target-initiated, see remote-fileio.c. */
8606
8607 /* If *LEFT is at least the length of STRING, copy STRING to
8608 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8609 decrease *LEFT. Otherwise raise an error. */
8610
8611 static void
8612 remote_buffer_add_string (char **buffer, int *left, char *string)
8613 {
8614 int len = strlen (string);
8615
8616 if (len > *left)
8617 error (_("Packet too long for target."));
8618
8619 memcpy (*buffer, string, len);
8620 *buffer += len;
8621 *left -= len;
8622
8623 /* NUL-terminate the buffer as a convenience, if there is
8624 room. */
8625 if (*left)
8626 **buffer = '\0';
8627 }
8628
8629 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
8630 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8631 decrease *LEFT. Otherwise raise an error. */
8632
8633 static void
8634 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
8635 int len)
8636 {
8637 if (2 * len > *left)
8638 error (_("Packet too long for target."));
8639
8640 bin2hex (bytes, *buffer, len);
8641 *buffer += 2 * len;
8642 *left -= 2 * len;
8643
8644 /* NUL-terminate the buffer as a convenience, if there is
8645 room. */
8646 if (*left)
8647 **buffer = '\0';
8648 }
8649
8650 /* If *LEFT is large enough, convert VALUE to hex and add it to
8651 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8652 decrease *LEFT. Otherwise raise an error. */
8653
8654 static void
8655 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
8656 {
8657 int len = hexnumlen (value);
8658
8659 if (len > *left)
8660 error (_("Packet too long for target."));
8661
8662 hexnumstr (*buffer, value);
8663 *buffer += len;
8664 *left -= len;
8665
8666 /* NUL-terminate the buffer as a convenience, if there is
8667 room. */
8668 if (*left)
8669 **buffer = '\0';
8670 }
8671
8672 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
8673 value, *REMOTE_ERRNO to the remote error number or zero if none
8674 was included, and *ATTACHMENT to point to the start of the annex
8675 if any. The length of the packet isn't needed here; there may
8676 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
8677
8678 Return 0 if the packet could be parsed, -1 if it could not. If
8679 -1 is returned, the other variables may not be initialized. */
8680
8681 static int
8682 remote_hostio_parse_result (char *buffer, int *retcode,
8683 int *remote_errno, char **attachment)
8684 {
8685 char *p, *p2;
8686
8687 *remote_errno = 0;
8688 *attachment = NULL;
8689
8690 if (buffer[0] != 'F')
8691 return -1;
8692
8693 errno = 0;
8694 *retcode = strtol (&buffer[1], &p, 16);
8695 if (errno != 0 || p == &buffer[1])
8696 return -1;
8697
8698 /* Check for ",errno". */
8699 if (*p == ',')
8700 {
8701 errno = 0;
8702 *remote_errno = strtol (p + 1, &p2, 16);
8703 if (errno != 0 || p + 1 == p2)
8704 return -1;
8705 p = p2;
8706 }
8707
8708 /* Check for ";attachment". If there is no attachment, the
8709 packet should end here. */
8710 if (*p == ';')
8711 {
8712 *attachment = p + 1;
8713 return 0;
8714 }
8715 else if (*p == '\0')
8716 return 0;
8717 else
8718 return -1;
8719 }
8720
8721 /* Send a prepared I/O packet to the target and read its response.
8722 The prepared packet is in the global RS->BUF before this function
8723 is called, and the answer is there when we return.
8724
8725 COMMAND_BYTES is the length of the request to send, which may include
8726 binary data. WHICH_PACKET is the packet configuration to check
8727 before attempting a packet. If an error occurs, *REMOTE_ERRNO
8728 is set to the error number and -1 is returned. Otherwise the value
8729 returned by the function is returned.
8730
8731 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
8732 attachment is expected; an error will be reported if there's a
8733 mismatch. If one is found, *ATTACHMENT will be set to point into
8734 the packet buffer and *ATTACHMENT_LEN will be set to the
8735 attachment's length. */
8736
8737 static int
8738 remote_hostio_send_command (int command_bytes, int which_packet,
8739 int *remote_errno, char **attachment,
8740 int *attachment_len)
8741 {
8742 struct remote_state *rs = get_remote_state ();
8743 int ret, bytes_read;
8744 char *attachment_tmp;
8745
8746 if (!remote_desc
8747 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
8748 {
8749 *remote_errno = FILEIO_ENOSYS;
8750 return -1;
8751 }
8752
8753 putpkt_binary (rs->buf, command_bytes);
8754 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8755
8756 /* If it timed out, something is wrong. Don't try to parse the
8757 buffer. */
8758 if (bytes_read < 0)
8759 {
8760 *remote_errno = FILEIO_EINVAL;
8761 return -1;
8762 }
8763
8764 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
8765 {
8766 case PACKET_ERROR:
8767 *remote_errno = FILEIO_EINVAL;
8768 return -1;
8769 case PACKET_UNKNOWN:
8770 *remote_errno = FILEIO_ENOSYS;
8771 return -1;
8772 case PACKET_OK:
8773 break;
8774 }
8775
8776 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
8777 &attachment_tmp))
8778 {
8779 *remote_errno = FILEIO_EINVAL;
8780 return -1;
8781 }
8782
8783 /* Make sure we saw an attachment if and only if we expected one. */
8784 if ((attachment_tmp == NULL && attachment != NULL)
8785 || (attachment_tmp != NULL && attachment == NULL))
8786 {
8787 *remote_errno = FILEIO_EINVAL;
8788 return -1;
8789 }
8790
8791 /* If an attachment was found, it must point into the packet buffer;
8792 work out how many bytes there were. */
8793 if (attachment_tmp != NULL)
8794 {
8795 *attachment = attachment_tmp;
8796 *attachment_len = bytes_read - (*attachment - rs->buf);
8797 }
8798
8799 return ret;
8800 }
8801
8802 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
8803 remote file descriptor, or -1 if an error occurs (and set
8804 *REMOTE_ERRNO). */
8805
8806 static int
8807 remote_hostio_open (const char *filename, int flags, int mode,
8808 int *remote_errno)
8809 {
8810 struct remote_state *rs = get_remote_state ();
8811 char *p = rs->buf;
8812 int left = get_remote_packet_size () - 1;
8813
8814 remote_buffer_add_string (&p, &left, "vFile:open:");
8815
8816 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8817 strlen (filename));
8818 remote_buffer_add_string (&p, &left, ",");
8819
8820 remote_buffer_add_int (&p, &left, flags);
8821 remote_buffer_add_string (&p, &left, ",");
8822
8823 remote_buffer_add_int (&p, &left, mode);
8824
8825 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
8826 remote_errno, NULL, NULL);
8827 }
8828
8829 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
8830 Return the number of bytes written, or -1 if an error occurs (and
8831 set *REMOTE_ERRNO). */
8832
8833 static int
8834 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
8835 ULONGEST offset, int *remote_errno)
8836 {
8837 struct remote_state *rs = get_remote_state ();
8838 char *p = rs->buf;
8839 int left = get_remote_packet_size ();
8840 int out_len;
8841
8842 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
8843
8844 remote_buffer_add_int (&p, &left, fd);
8845 remote_buffer_add_string (&p, &left, ",");
8846
8847 remote_buffer_add_int (&p, &left, offset);
8848 remote_buffer_add_string (&p, &left, ",");
8849
8850 p += remote_escape_output (write_buf, len, p, &out_len,
8851 get_remote_packet_size () - (p - rs->buf));
8852
8853 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
8854 remote_errno, NULL, NULL);
8855 }
8856
8857 /* Read up to LEN bytes FD on the remote target into READ_BUF
8858 Return the number of bytes read, or -1 if an error occurs (and
8859 set *REMOTE_ERRNO). */
8860
8861 static int
8862 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
8863 ULONGEST offset, int *remote_errno)
8864 {
8865 struct remote_state *rs = get_remote_state ();
8866 char *p = rs->buf;
8867 char *attachment;
8868 int left = get_remote_packet_size ();
8869 int ret, attachment_len;
8870 int read_len;
8871
8872 remote_buffer_add_string (&p, &left, "vFile:pread:");
8873
8874 remote_buffer_add_int (&p, &left, fd);
8875 remote_buffer_add_string (&p, &left, ",");
8876
8877 remote_buffer_add_int (&p, &left, len);
8878 remote_buffer_add_string (&p, &left, ",");
8879
8880 remote_buffer_add_int (&p, &left, offset);
8881
8882 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
8883 remote_errno, &attachment,
8884 &attachment_len);
8885
8886 if (ret < 0)
8887 return ret;
8888
8889 read_len = remote_unescape_input (attachment, attachment_len,
8890 read_buf, len);
8891 if (read_len != ret)
8892 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
8893
8894 return ret;
8895 }
8896
8897 /* Close FD on the remote target. Return 0, or -1 if an error occurs
8898 (and set *REMOTE_ERRNO). */
8899
8900 static int
8901 remote_hostio_close (int fd, int *remote_errno)
8902 {
8903 struct remote_state *rs = get_remote_state ();
8904 char *p = rs->buf;
8905 int left = get_remote_packet_size () - 1;
8906
8907 remote_buffer_add_string (&p, &left, "vFile:close:");
8908
8909 remote_buffer_add_int (&p, &left, fd);
8910
8911 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
8912 remote_errno, NULL, NULL);
8913 }
8914
8915 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
8916 occurs (and set *REMOTE_ERRNO). */
8917
8918 static int
8919 remote_hostio_unlink (const char *filename, int *remote_errno)
8920 {
8921 struct remote_state *rs = get_remote_state ();
8922 char *p = rs->buf;
8923 int left = get_remote_packet_size () - 1;
8924
8925 remote_buffer_add_string (&p, &left, "vFile:unlink:");
8926
8927 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8928 strlen (filename));
8929
8930 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
8931 remote_errno, NULL, NULL);
8932 }
8933
8934 static int
8935 remote_fileio_errno_to_host (int errnum)
8936 {
8937 switch (errnum)
8938 {
8939 case FILEIO_EPERM:
8940 return EPERM;
8941 case FILEIO_ENOENT:
8942 return ENOENT;
8943 case FILEIO_EINTR:
8944 return EINTR;
8945 case FILEIO_EIO:
8946 return EIO;
8947 case FILEIO_EBADF:
8948 return EBADF;
8949 case FILEIO_EACCES:
8950 return EACCES;
8951 case FILEIO_EFAULT:
8952 return EFAULT;
8953 case FILEIO_EBUSY:
8954 return EBUSY;
8955 case FILEIO_EEXIST:
8956 return EEXIST;
8957 case FILEIO_ENODEV:
8958 return ENODEV;
8959 case FILEIO_ENOTDIR:
8960 return ENOTDIR;
8961 case FILEIO_EISDIR:
8962 return EISDIR;
8963 case FILEIO_EINVAL:
8964 return EINVAL;
8965 case FILEIO_ENFILE:
8966 return ENFILE;
8967 case FILEIO_EMFILE:
8968 return EMFILE;
8969 case FILEIO_EFBIG:
8970 return EFBIG;
8971 case FILEIO_ENOSPC:
8972 return ENOSPC;
8973 case FILEIO_ESPIPE:
8974 return ESPIPE;
8975 case FILEIO_EROFS:
8976 return EROFS;
8977 case FILEIO_ENOSYS:
8978 return ENOSYS;
8979 case FILEIO_ENAMETOOLONG:
8980 return ENAMETOOLONG;
8981 }
8982 return -1;
8983 }
8984
8985 static char *
8986 remote_hostio_error (int errnum)
8987 {
8988 int host_error = remote_fileio_errno_to_host (errnum);
8989
8990 if (host_error == -1)
8991 error (_("Unknown remote I/O error %d"), errnum);
8992 else
8993 error (_("Remote I/O error: %s"), safe_strerror (host_error));
8994 }
8995
8996 static void
8997 remote_hostio_close_cleanup (void *opaque)
8998 {
8999 int fd = *(int *) opaque;
9000 int remote_errno;
9001
9002 remote_hostio_close (fd, &remote_errno);
9003 }
9004
9005
9006 static void *
9007 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9008 {
9009 const char *filename = bfd_get_filename (abfd);
9010 int fd, remote_errno;
9011 int *stream;
9012
9013 gdb_assert (remote_filename_p (filename));
9014
9015 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
9016 if (fd == -1)
9017 {
9018 errno = remote_fileio_errno_to_host (remote_errno);
9019 bfd_set_error (bfd_error_system_call);
9020 return NULL;
9021 }
9022
9023 stream = xmalloc (sizeof (int));
9024 *stream = fd;
9025 return stream;
9026 }
9027
9028 static int
9029 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9030 {
9031 int fd = *(int *)stream;
9032 int remote_errno;
9033
9034 xfree (stream);
9035
9036 /* Ignore errors on close; these may happen if the remote
9037 connection was already torn down. */
9038 remote_hostio_close (fd, &remote_errno);
9039
9040 return 1;
9041 }
9042
9043 static file_ptr
9044 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9045 file_ptr nbytes, file_ptr offset)
9046 {
9047 int fd = *(int *)stream;
9048 int remote_errno;
9049 file_ptr pos, bytes;
9050
9051 pos = 0;
9052 while (nbytes > pos)
9053 {
9054 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
9055 offset + pos, &remote_errno);
9056 if (bytes == 0)
9057 /* Success, but no bytes, means end-of-file. */
9058 break;
9059 if (bytes == -1)
9060 {
9061 errno = remote_fileio_errno_to_host (remote_errno);
9062 bfd_set_error (bfd_error_system_call);
9063 return -1;
9064 }
9065
9066 pos += bytes;
9067 }
9068
9069 return pos;
9070 }
9071
9072 static int
9073 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9074 {
9075 /* FIXME: We should probably implement remote_hostio_stat. */
9076 sb->st_size = INT_MAX;
9077 return 0;
9078 }
9079
9080 int
9081 remote_filename_p (const char *filename)
9082 {
9083 return strncmp (filename, "remote:", 7) == 0;
9084 }
9085
9086 bfd *
9087 remote_bfd_open (const char *remote_file, const char *target)
9088 {
9089 return bfd_openr_iovec (remote_file, target,
9090 remote_bfd_iovec_open, NULL,
9091 remote_bfd_iovec_pread,
9092 remote_bfd_iovec_close,
9093 remote_bfd_iovec_stat);
9094 }
9095
9096 void
9097 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
9098 {
9099 struct cleanup *back_to, *close_cleanup;
9100 int retcode, fd, remote_errno, bytes, io_size;
9101 FILE *file;
9102 gdb_byte *buffer;
9103 int bytes_in_buffer;
9104 int saw_eof;
9105 ULONGEST offset;
9106
9107 if (!remote_desc)
9108 error (_("command can only be used with remote target"));
9109
9110 file = fopen (local_file, "rb");
9111 if (file == NULL)
9112 perror_with_name (local_file);
9113 back_to = make_cleanup_fclose (file);
9114
9115 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
9116 | FILEIO_O_TRUNC),
9117 0700, &remote_errno);
9118 if (fd == -1)
9119 remote_hostio_error (remote_errno);
9120
9121 /* Send up to this many bytes at once. They won't all fit in the
9122 remote packet limit, so we'll transfer slightly fewer. */
9123 io_size = get_remote_packet_size ();
9124 buffer = xmalloc (io_size);
9125 make_cleanup (xfree, buffer);
9126
9127 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9128
9129 bytes_in_buffer = 0;
9130 saw_eof = 0;
9131 offset = 0;
9132 while (bytes_in_buffer || !saw_eof)
9133 {
9134 if (!saw_eof)
9135 {
9136 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
9137 file);
9138 if (bytes == 0)
9139 {
9140 if (ferror (file))
9141 error (_("Error reading %s."), local_file);
9142 else
9143 {
9144 /* EOF. Unless there is something still in the
9145 buffer from the last iteration, we are done. */
9146 saw_eof = 1;
9147 if (bytes_in_buffer == 0)
9148 break;
9149 }
9150 }
9151 }
9152 else
9153 bytes = 0;
9154
9155 bytes += bytes_in_buffer;
9156 bytes_in_buffer = 0;
9157
9158 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
9159
9160 if (retcode < 0)
9161 remote_hostio_error (remote_errno);
9162 else if (retcode == 0)
9163 error (_("Remote write of %d bytes returned 0!"), bytes);
9164 else if (retcode < bytes)
9165 {
9166 /* Short write. Save the rest of the read data for the next
9167 write. */
9168 bytes_in_buffer = bytes - retcode;
9169 memmove (buffer, buffer + retcode, bytes_in_buffer);
9170 }
9171
9172 offset += retcode;
9173 }
9174
9175 discard_cleanups (close_cleanup);
9176 if (remote_hostio_close (fd, &remote_errno))
9177 remote_hostio_error (remote_errno);
9178
9179 if (from_tty)
9180 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
9181 do_cleanups (back_to);
9182 }
9183
9184 void
9185 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
9186 {
9187 struct cleanup *back_to, *close_cleanup;
9188 int fd, remote_errno, bytes, io_size;
9189 FILE *file;
9190 gdb_byte *buffer;
9191 ULONGEST offset;
9192
9193 if (!remote_desc)
9194 error (_("command can only be used with remote target"));
9195
9196 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
9197 if (fd == -1)
9198 remote_hostio_error (remote_errno);
9199
9200 file = fopen (local_file, "wb");
9201 if (file == NULL)
9202 perror_with_name (local_file);
9203 back_to = make_cleanup_fclose (file);
9204
9205 /* Send up to this many bytes at once. They won't all fit in the
9206 remote packet limit, so we'll transfer slightly fewer. */
9207 io_size = get_remote_packet_size ();
9208 buffer = xmalloc (io_size);
9209 make_cleanup (xfree, buffer);
9210
9211 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9212
9213 offset = 0;
9214 while (1)
9215 {
9216 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
9217 if (bytes == 0)
9218 /* Success, but no bytes, means end-of-file. */
9219 break;
9220 if (bytes == -1)
9221 remote_hostio_error (remote_errno);
9222
9223 offset += bytes;
9224
9225 bytes = fwrite (buffer, 1, bytes, file);
9226 if (bytes == 0)
9227 perror_with_name (local_file);
9228 }
9229
9230 discard_cleanups (close_cleanup);
9231 if (remote_hostio_close (fd, &remote_errno))
9232 remote_hostio_error (remote_errno);
9233
9234 if (from_tty)
9235 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
9236 do_cleanups (back_to);
9237 }
9238
9239 void
9240 remote_file_delete (const char *remote_file, int from_tty)
9241 {
9242 int retcode, remote_errno;
9243
9244 if (!remote_desc)
9245 error (_("command can only be used with remote target"));
9246
9247 retcode = remote_hostio_unlink (remote_file, &remote_errno);
9248 if (retcode == -1)
9249 remote_hostio_error (remote_errno);
9250
9251 if (from_tty)
9252 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
9253 }
9254
9255 static void
9256 remote_put_command (char *args, int from_tty)
9257 {
9258 struct cleanup *back_to;
9259 char **argv;
9260
9261 if (args == NULL)
9262 error_no_arg (_("file to put"));
9263
9264 argv = gdb_buildargv (args);
9265 back_to = make_cleanup_freeargv (argv);
9266 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9267 error (_("Invalid parameters to remote put"));
9268
9269 remote_file_put (argv[0], argv[1], from_tty);
9270
9271 do_cleanups (back_to);
9272 }
9273
9274 static void
9275 remote_get_command (char *args, int from_tty)
9276 {
9277 struct cleanup *back_to;
9278 char **argv;
9279
9280 if (args == NULL)
9281 error_no_arg (_("file to get"));
9282
9283 argv = gdb_buildargv (args);
9284 back_to = make_cleanup_freeargv (argv);
9285 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9286 error (_("Invalid parameters to remote get"));
9287
9288 remote_file_get (argv[0], argv[1], from_tty);
9289
9290 do_cleanups (back_to);
9291 }
9292
9293 static void
9294 remote_delete_command (char *args, int from_tty)
9295 {
9296 struct cleanup *back_to;
9297 char **argv;
9298
9299 if (args == NULL)
9300 error_no_arg (_("file to delete"));
9301
9302 argv = gdb_buildargv (args);
9303 back_to = make_cleanup_freeargv (argv);
9304 if (argv[0] == NULL || argv[1] != NULL)
9305 error (_("Invalid parameters to remote delete"));
9306
9307 remote_file_delete (argv[0], from_tty);
9308
9309 do_cleanups (back_to);
9310 }
9311
9312 static void
9313 remote_command (char *args, int from_tty)
9314 {
9315 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
9316 }
9317
9318 static int
9319 remote_can_execute_reverse (void)
9320 {
9321 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
9322 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
9323 return 1;
9324 else
9325 return 0;
9326 }
9327
9328 static int
9329 remote_supports_non_stop (void)
9330 {
9331 return 1;
9332 }
9333
9334 static int
9335 remote_supports_multi_process (void)
9336 {
9337 struct remote_state *rs = get_remote_state ();
9338 return remote_multi_process_p (rs);
9339 }
9340
9341 int
9342 remote_supports_cond_tracepoints (void)
9343 {
9344 struct remote_state *rs = get_remote_state ();
9345 return rs->cond_tracepoints;
9346 }
9347
9348 int
9349 remote_supports_fast_tracepoints (void)
9350 {
9351 struct remote_state *rs = get_remote_state ();
9352 return rs->fast_tracepoints;
9353 }
9354
9355 static void
9356 remote_trace_init (void)
9357 {
9358 putpkt ("QTinit");
9359 remote_get_noisy_reply (&target_buf, &target_buf_size);
9360 if (strcmp (target_buf, "OK") != 0)
9361 error (_("Target does not support this command."));
9362 }
9363
9364 static void free_actions_list (char **actions_list);
9365 static void free_actions_list_cleanup_wrapper (void *);
9366 static void
9367 free_actions_list_cleanup_wrapper (void *al)
9368 {
9369 free_actions_list (al);
9370 }
9371
9372 static void
9373 free_actions_list (char **actions_list)
9374 {
9375 int ndx;
9376
9377 if (actions_list == 0)
9378 return;
9379
9380 for (ndx = 0; actions_list[ndx]; ndx++)
9381 xfree (actions_list[ndx]);
9382
9383 xfree (actions_list);
9384 }
9385
9386 /* Recursive routine to walk through command list including loops, and
9387 download packets for each command. */
9388
9389 static void
9390 remote_download_command_source (int num, ULONGEST addr,
9391 struct command_line *cmds)
9392 {
9393 struct remote_state *rs = get_remote_state ();
9394 struct command_line *cmd;
9395
9396 for (cmd = cmds; cmd; cmd = cmd->next)
9397 {
9398 QUIT; /* allow user to bail out with ^C */
9399 strcpy (rs->buf, "QTDPsrc:");
9400 encode_source_string (num, addr, "cmd", cmd->line,
9401 rs->buf + strlen (rs->buf),
9402 rs->buf_size - strlen (rs->buf));
9403 putpkt (rs->buf);
9404 remote_get_noisy_reply (&target_buf, &target_buf_size);
9405 if (strcmp (target_buf, "OK"))
9406 warning (_("Target does not support source download."));
9407
9408 if (cmd->control_type == while_control
9409 || cmd->control_type == while_stepping_control)
9410 {
9411 remote_download_command_source (num, addr, *cmd->body_list);
9412
9413 QUIT; /* allow user to bail out with ^C */
9414 strcpy (rs->buf, "QTDPsrc:");
9415 encode_source_string (num, addr, "cmd", "end",
9416 rs->buf + strlen (rs->buf),
9417 rs->buf_size - strlen (rs->buf));
9418 putpkt (rs->buf);
9419 remote_get_noisy_reply (&target_buf, &target_buf_size);
9420 if (strcmp (target_buf, "OK"))
9421 warning (_("Target does not support source download."));
9422 }
9423 }
9424 }
9425
9426 static void
9427 remote_download_tracepoint (struct breakpoint *t)
9428 {
9429 struct bp_location *loc;
9430 CORE_ADDR tpaddr;
9431 char addrbuf[40];
9432 char buf[2048];
9433 char **tdp_actions;
9434 char **stepping_actions;
9435 int ndx;
9436 struct cleanup *old_chain = NULL;
9437 struct agent_expr *aexpr;
9438 struct cleanup *aexpr_chain = NULL;
9439 char *pkt;
9440
9441 /* Iterate over all the tracepoint locations. It's up to the target to
9442 notice multiple tracepoint packets with the same number but different
9443 addresses, and treat them as multiple locations. */
9444 for (loc = t->loc; loc; loc = loc->next)
9445 {
9446 encode_actions (t, loc, &tdp_actions, &stepping_actions);
9447 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
9448 tdp_actions);
9449 (void) make_cleanup (free_actions_list_cleanup_wrapper, stepping_actions);
9450
9451 tpaddr = loc->address;
9452 sprintf_vma (addrbuf, tpaddr);
9453 sprintf (buf, "QTDP:%x:%s:%c:%lx:%x", t->number,
9454 addrbuf, /* address */
9455 (t->enable_state == bp_enabled ? 'E' : 'D'),
9456 t->step_count, t->pass_count);
9457 /* Fast tracepoints are mostly handled by the target, but we can
9458 tell the target how big of an instruction block should be moved
9459 around. */
9460 if (t->type == bp_fast_tracepoint)
9461 {
9462 /* Only test for support at download time; we may not know
9463 target capabilities at definition time. */
9464 if (remote_supports_fast_tracepoints ())
9465 {
9466 int isize;
9467
9468 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch,
9469 tpaddr, &isize, NULL))
9470 sprintf (buf + strlen (buf), ":F%x", isize);
9471 else
9472 /* If it passed validation at definition but fails now,
9473 something is very wrong. */
9474 internal_error (__FILE__, __LINE__,
9475 "Fast tracepoint not valid during download");
9476 }
9477 else
9478 /* Fast tracepoints are functionally identical to regular
9479 tracepoints, so don't take lack of support as a reason to
9480 give up on the trace run. */
9481 warning (_("Target does not support fast tracepoints, downloading %d as regular tracepoint"), t->number);
9482 }
9483 /* If the tracepoint has a conditional, make it into an agent
9484 expression and append to the definition. */
9485 if (loc->cond)
9486 {
9487 /* Only test support at download time, we may not know target
9488 capabilities at definition time. */
9489 if (remote_supports_cond_tracepoints ())
9490 {
9491 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
9492 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
9493 sprintf (buf + strlen (buf), ":X%x,", aexpr->len);
9494 pkt = buf + strlen (buf);
9495 for (ndx = 0; ndx < aexpr->len; ++ndx)
9496 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
9497 *pkt = '\0';
9498 do_cleanups (aexpr_chain);
9499 }
9500 else
9501 warning (_("Target does not support conditional tracepoints, ignoring tp %d cond"), t->number);
9502 }
9503
9504 if (t->commands || *default_collect)
9505 strcat (buf, "-");
9506 putpkt (buf);
9507 remote_get_noisy_reply (&target_buf, &target_buf_size);
9508 if (strcmp (target_buf, "OK"))
9509 error (_("Target does not support tracepoints."));
9510
9511 /* do_single_steps (t); */
9512 if (tdp_actions)
9513 {
9514 for (ndx = 0; tdp_actions[ndx]; ndx++)
9515 {
9516 QUIT; /* allow user to bail out with ^C */
9517 sprintf (buf, "QTDP:-%x:%s:%s%c",
9518 t->number, addrbuf, /* address */
9519 tdp_actions[ndx],
9520 ((tdp_actions[ndx + 1] || stepping_actions)
9521 ? '-' : 0));
9522 putpkt (buf);
9523 remote_get_noisy_reply (&target_buf,
9524 &target_buf_size);
9525 if (strcmp (target_buf, "OK"))
9526 error (_("Error on target while setting tracepoints."));
9527 }
9528 }
9529 if (stepping_actions)
9530 {
9531 for (ndx = 0; stepping_actions[ndx]; ndx++)
9532 {
9533 QUIT; /* allow user to bail out with ^C */
9534 sprintf (buf, "QTDP:-%x:%s:%s%s%s",
9535 t->number, addrbuf, /* address */
9536 ((ndx == 0) ? "S" : ""),
9537 stepping_actions[ndx],
9538 (stepping_actions[ndx + 1] ? "-" : ""));
9539 putpkt (buf);
9540 remote_get_noisy_reply (&target_buf,
9541 &target_buf_size);
9542 if (strcmp (target_buf, "OK"))
9543 error (_("Error on target while setting tracepoints."));
9544 }
9545 }
9546
9547 if (remote_protocol_packets[PACKET_TracepointSource].support == PACKET_ENABLE)
9548 {
9549 if (t->addr_string)
9550 {
9551 strcpy (buf, "QTDPsrc:");
9552 encode_source_string (t->number, loc->address,
9553 "at", t->addr_string, buf + strlen (buf),
9554 2048 - strlen (buf));
9555
9556 putpkt (buf);
9557 remote_get_noisy_reply (&target_buf, &target_buf_size);
9558 if (strcmp (target_buf, "OK"))
9559 warning (_("Target does not support source download."));
9560 }
9561 if (t->cond_string)
9562 {
9563 strcpy (buf, "QTDPsrc:");
9564 encode_source_string (t->number, loc->address,
9565 "cond", t->cond_string, buf + strlen (buf),
9566 2048 - strlen (buf));
9567 putpkt (buf);
9568 remote_get_noisy_reply (&target_buf, &target_buf_size);
9569 if (strcmp (target_buf, "OK"))
9570 warning (_("Target does not support source download."));
9571 }
9572 remote_download_command_source (t->number, loc->address,
9573 breakpoint_commands (t));
9574 }
9575
9576 do_cleanups (old_chain);
9577 }
9578 }
9579
9580 static void
9581 remote_download_trace_state_variable (struct trace_state_variable *tsv)
9582 {
9583 struct remote_state *rs = get_remote_state ();
9584 char *p;
9585
9586 sprintf (rs->buf, "QTDV:%x:%s:%x:",
9587 tsv->number, phex ((ULONGEST) tsv->initial_value, 8), tsv->builtin);
9588 p = rs->buf + strlen (rs->buf);
9589 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
9590 error (_("Trace state variable name too long for tsv definition packet"));
9591 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
9592 *p++ = '\0';
9593 putpkt (rs->buf);
9594 remote_get_noisy_reply (&target_buf, &target_buf_size);
9595 if (*target_buf == '\0')
9596 error (_("Target does not support this command."));
9597 if (strcmp (target_buf, "OK") != 0)
9598 error (_("Error on target while downloading trace state variable."));
9599 }
9600
9601 static void
9602 remote_trace_set_readonly_regions (void)
9603 {
9604 asection *s;
9605 bfd_size_type size;
9606 bfd_vma lma;
9607 int anysecs = 0;
9608
9609 if (!exec_bfd)
9610 return; /* No information to give. */
9611
9612 strcpy (target_buf, "QTro");
9613 for (s = exec_bfd->sections; s; s = s->next)
9614 {
9615 char tmp1[40], tmp2[40];
9616
9617 if ((s->flags & SEC_LOAD) == 0 ||
9618 /* (s->flags & SEC_CODE) == 0 || */
9619 (s->flags & SEC_READONLY) == 0)
9620 continue;
9621
9622 anysecs = 1;
9623 lma = s->lma;
9624 size = bfd_get_section_size (s);
9625 sprintf_vma (tmp1, lma);
9626 sprintf_vma (tmp2, lma + size);
9627 sprintf (target_buf + strlen (target_buf),
9628 ":%s,%s", tmp1, tmp2);
9629 }
9630 if (anysecs)
9631 {
9632 putpkt (target_buf);
9633 getpkt (&target_buf, &target_buf_size, 0);
9634 }
9635 }
9636
9637 static void
9638 remote_trace_start (void)
9639 {
9640 putpkt ("QTStart");
9641 remote_get_noisy_reply (&target_buf, &target_buf_size);
9642 if (*target_buf == '\0')
9643 error (_("Target does not support this command."));
9644 if (strcmp (target_buf, "OK") != 0)
9645 error (_("Bogus reply from target: %s"), target_buf);
9646 }
9647
9648 static int
9649 remote_get_trace_status (struct trace_status *ts)
9650 {
9651 char *p;
9652 /* FIXME we need to get register block size some other way */
9653 extern int trace_regblock_size;
9654 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
9655
9656 putpkt ("qTStatus");
9657 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
9658
9659 /* If the remote target doesn't do tracing, flag it. */
9660 if (*p == '\0')
9661 return -1;
9662
9663 /* We're working with a live target. */
9664 ts->from_file = 0;
9665
9666 /* Set some defaults. */
9667 ts->running_known = 0;
9668 ts->stop_reason = trace_stop_reason_unknown;
9669 ts->traceframe_count = -1;
9670 ts->buffer_free = 0;
9671
9672 if (*p++ != 'T')
9673 error (_("Bogus trace status reply from target: %s"), target_buf);
9674
9675 parse_trace_status (p, ts);
9676
9677 return ts->running;
9678 }
9679
9680 static void
9681 remote_trace_stop (void)
9682 {
9683 putpkt ("QTStop");
9684 remote_get_noisy_reply (&target_buf, &target_buf_size);
9685 if (*target_buf == '\0')
9686 error (_("Target does not support this command."));
9687 if (strcmp (target_buf, "OK") != 0)
9688 error (_("Bogus reply from target: %s"), target_buf);
9689 }
9690
9691 static int
9692 remote_trace_find (enum trace_find_type type, int num,
9693 ULONGEST addr1, ULONGEST addr2,
9694 int *tpp)
9695 {
9696 struct remote_state *rs = get_remote_state ();
9697 char *p, *reply;
9698 int target_frameno = -1, target_tracept = -1;
9699
9700 p = rs->buf;
9701 strcpy (p, "QTFrame:");
9702 p = strchr (p, '\0');
9703 switch (type)
9704 {
9705 case tfind_number:
9706 sprintf (p, "%x", num);
9707 break;
9708 case tfind_pc:
9709 sprintf (p, "pc:%s", phex_nz (addr1, 0));
9710 break;
9711 case tfind_tp:
9712 sprintf (p, "tdp:%x", num);
9713 break;
9714 case tfind_range:
9715 sprintf (p, "range:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
9716 break;
9717 case tfind_outside:
9718 sprintf (p, "outside:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
9719 break;
9720 default:
9721 error ("Unknown trace find type %d", type);
9722 }
9723
9724 putpkt (rs->buf);
9725 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
9726 if (*reply == '\0')
9727 error (_("Target does not support this command."));
9728
9729 while (reply && *reply)
9730 switch (*reply)
9731 {
9732 case 'F':
9733 p = ++reply;
9734 target_frameno = (int) strtol (p, &reply, 16);
9735 if (reply == p)
9736 error (_("Unable to parse trace frame number"));
9737 if (target_frameno == -1)
9738 return -1;
9739 break;
9740 case 'T':
9741 p = ++reply;
9742 target_tracept = (int) strtol (p, &reply, 16);
9743 if (reply == p)
9744 error (_("Unable to parse tracepoint number"));
9745 break;
9746 case 'O': /* "OK"? */
9747 if (reply[1] == 'K' && reply[2] == '\0')
9748 reply += 2;
9749 else
9750 error (_("Bogus reply from target: %s"), reply);
9751 break;
9752 default:
9753 error (_("Bogus reply from target: %s"), reply);
9754 }
9755 if (tpp)
9756 *tpp = target_tracept;
9757 return target_frameno;
9758 }
9759
9760 static int
9761 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
9762 {
9763 struct remote_state *rs = get_remote_state ();
9764 char *reply;
9765 ULONGEST uval;
9766
9767 sprintf (rs->buf, "qTV:%x", tsvnum);
9768 putpkt (rs->buf);
9769 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9770 if (reply && *reply)
9771 {
9772 if (*reply == 'V')
9773 {
9774 unpack_varlen_hex (reply + 1, &uval);
9775 *val = (LONGEST) uval;
9776 return 1;
9777 }
9778 }
9779 return 0;
9780 }
9781
9782 static int
9783 remote_save_trace_data (const char *filename)
9784 {
9785 struct remote_state *rs = get_remote_state ();
9786 char *p, *reply;
9787
9788 p = rs->buf;
9789 strcpy (p, "QTSave:");
9790 p += strlen (p);
9791 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
9792 error (_("Remote file name too long for trace save packet"));
9793 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
9794 *p++ = '\0';
9795 putpkt (rs->buf);
9796 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9797 if (*reply != '\0')
9798 error (_("Target does not support this command."));
9799 if (strcmp (reply, "OK") != 0)
9800 error (_("Bogus reply from target: %s"), reply);
9801 return 0;
9802 }
9803
9804 /* This is basically a memory transfer, but needs to be its own packet
9805 because we don't know how the target actually organizes its trace
9806 memory, plus we want to be able to ask for as much as possible, but
9807 not be unhappy if we don't get as much as we ask for. */
9808
9809 static LONGEST
9810 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
9811 {
9812 struct remote_state *rs = get_remote_state ();
9813 char *reply;
9814 char *p;
9815 int rslt;
9816
9817 p = rs->buf;
9818 strcpy (p, "qTBuffer:");
9819 p += strlen (p);
9820 p += hexnumstr (p, offset);
9821 *p++ = ',';
9822 p += hexnumstr (p, len);
9823 *p++ = '\0';
9824
9825 putpkt (rs->buf);
9826 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9827 if (reply && *reply)
9828 {
9829 /* 'l' by itself means we're at the end of the buffer and
9830 there is nothing more to get. */
9831 if (*reply == 'l')
9832 return 0;
9833
9834 /* Convert the reply into binary. Limit the number of bytes to
9835 convert according to our passed-in buffer size, rather than
9836 what was returned in the packet; if the target is
9837 unexpectedly generous and gives us a bigger reply than we
9838 asked for, we don't want to crash. */
9839 rslt = hex2bin (target_buf, buf, len);
9840 return rslt;
9841 }
9842
9843 /* Something went wrong, flag as an error. */
9844 return -1;
9845 }
9846
9847 static void
9848 remote_set_disconnected_tracing (int val)
9849 {
9850 struct remote_state *rs = get_remote_state ();
9851
9852 if (rs->disconnected_tracing)
9853 {
9854 char *reply;
9855
9856 sprintf (rs->buf, "QTDisconnected:%x", val);
9857 putpkt (rs->buf);
9858 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9859 if (*reply == '\0')
9860 error (_("Target does not support this command."));
9861 if (strcmp (reply, "OK") != 0)
9862 error (_("Bogus reply from target: %s"), reply);
9863 }
9864 else if (val)
9865 warning (_("Target does not support disconnected tracing."));
9866 }
9867
9868 static int
9869 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
9870 {
9871 struct thread_info *info = find_thread_ptid (ptid);
9872 if (info && info->private)
9873 return info->private->core;
9874 return -1;
9875 }
9876
9877 static void
9878 remote_set_circular_trace_buffer (int val)
9879 {
9880 struct remote_state *rs = get_remote_state ();
9881 char *reply;
9882
9883 sprintf (rs->buf, "QTBuffer:circular:%x", val);
9884 putpkt (rs->buf);
9885 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9886 if (*reply == '\0')
9887 error (_("Target does not support this command."));
9888 if (strcmp (reply, "OK") != 0)
9889 error (_("Bogus reply from target: %s"), reply);
9890 }
9891
9892 static void
9893 init_remote_ops (void)
9894 {
9895 remote_ops.to_shortname = "remote";
9896 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
9897 remote_ops.to_doc =
9898 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
9899 Specify the serial device it is connected to\n\
9900 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
9901 remote_ops.to_open = remote_open;
9902 remote_ops.to_close = remote_close;
9903 remote_ops.to_detach = remote_detach;
9904 remote_ops.to_disconnect = remote_disconnect;
9905 remote_ops.to_resume = remote_resume;
9906 remote_ops.to_wait = remote_wait;
9907 remote_ops.to_fetch_registers = remote_fetch_registers;
9908 remote_ops.to_store_registers = remote_store_registers;
9909 remote_ops.to_prepare_to_store = remote_prepare_to_store;
9910 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
9911 remote_ops.to_files_info = remote_files_info;
9912 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
9913 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
9914 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
9915 remote_ops.to_stopped_data_address = remote_stopped_data_address;
9916 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
9917 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
9918 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
9919 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
9920 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
9921 remote_ops.to_kill = remote_kill;
9922 remote_ops.to_load = generic_load;
9923 remote_ops.to_mourn_inferior = remote_mourn;
9924 remote_ops.to_notice_signals = remote_notice_signals;
9925 remote_ops.to_thread_alive = remote_thread_alive;
9926 remote_ops.to_find_new_threads = remote_threads_info;
9927 remote_ops.to_pid_to_str = remote_pid_to_str;
9928 remote_ops.to_extra_thread_info = remote_threads_extra_info;
9929 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
9930 remote_ops.to_stop = remote_stop;
9931 remote_ops.to_xfer_partial = remote_xfer_partial;
9932 remote_ops.to_rcmd = remote_rcmd;
9933 remote_ops.to_log_command = serial_log_command;
9934 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
9935 remote_ops.to_stratum = process_stratum;
9936 remote_ops.to_has_all_memory = default_child_has_all_memory;
9937 remote_ops.to_has_memory = default_child_has_memory;
9938 remote_ops.to_has_stack = default_child_has_stack;
9939 remote_ops.to_has_registers = default_child_has_registers;
9940 remote_ops.to_has_execution = default_child_has_execution;
9941 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
9942 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
9943 remote_ops.to_magic = OPS_MAGIC;
9944 remote_ops.to_memory_map = remote_memory_map;
9945 remote_ops.to_flash_erase = remote_flash_erase;
9946 remote_ops.to_flash_done = remote_flash_done;
9947 remote_ops.to_read_description = remote_read_description;
9948 remote_ops.to_search_memory = remote_search_memory;
9949 remote_ops.to_can_async_p = remote_can_async_p;
9950 remote_ops.to_is_async_p = remote_is_async_p;
9951 remote_ops.to_async = remote_async;
9952 remote_ops.to_async_mask = remote_async_mask;
9953 remote_ops.to_terminal_inferior = remote_terminal_inferior;
9954 remote_ops.to_terminal_ours = remote_terminal_ours;
9955 remote_ops.to_supports_non_stop = remote_supports_non_stop;
9956 remote_ops.to_supports_multi_process = remote_supports_multi_process;
9957 remote_ops.to_trace_init = remote_trace_init;
9958 remote_ops.to_download_tracepoint = remote_download_tracepoint;
9959 remote_ops.to_download_trace_state_variable = remote_download_trace_state_variable;
9960 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
9961 remote_ops.to_trace_start = remote_trace_start;
9962 remote_ops.to_get_trace_status = remote_get_trace_status;
9963 remote_ops.to_trace_stop = remote_trace_stop;
9964 remote_ops.to_trace_find = remote_trace_find;
9965 remote_ops.to_get_trace_state_variable_value = remote_get_trace_state_variable_value;
9966 remote_ops.to_save_trace_data = remote_save_trace_data;
9967 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
9968 remote_ops.to_upload_trace_state_variables = remote_upload_trace_state_variables;
9969 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
9970 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
9971 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
9972 remote_ops.to_core_of_thread = remote_core_of_thread;
9973 remote_ops.to_verify_memory = remote_verify_memory;
9974 remote_ops.to_get_tib_address = remote_get_tib_address;
9975 }
9976
9977 /* Set up the extended remote vector by making a copy of the standard
9978 remote vector and adding to it. */
9979
9980 static void
9981 init_extended_remote_ops (void)
9982 {
9983 extended_remote_ops = remote_ops;
9984
9985 extended_remote_ops.to_shortname = "extended-remote";
9986 extended_remote_ops.to_longname =
9987 "Extended remote serial target in gdb-specific protocol";
9988 extended_remote_ops.to_doc =
9989 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
9990 Specify the serial device it is connected to (e.g. /dev/ttya).";
9991 extended_remote_ops.to_open = extended_remote_open;
9992 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
9993 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
9994 extended_remote_ops.to_detach = extended_remote_detach;
9995 extended_remote_ops.to_attach = extended_remote_attach;
9996 extended_remote_ops.to_kill = extended_remote_kill;
9997 }
9998
9999 static int
10000 remote_can_async_p (void)
10001 {
10002 if (!target_async_permitted)
10003 /* We only enable async when the user specifically asks for it. */
10004 return 0;
10005
10006 /* We're async whenever the serial device is. */
10007 return remote_async_mask_value && serial_can_async_p (remote_desc);
10008 }
10009
10010 static int
10011 remote_is_async_p (void)
10012 {
10013 if (!target_async_permitted)
10014 /* We only enable async when the user specifically asks for it. */
10015 return 0;
10016
10017 /* We're async whenever the serial device is. */
10018 return remote_async_mask_value && serial_is_async_p (remote_desc);
10019 }
10020
10021 /* Pass the SERIAL event on and up to the client. One day this code
10022 will be able to delay notifying the client of an event until the
10023 point where an entire packet has been received. */
10024
10025 static void (*async_client_callback) (enum inferior_event_type event_type,
10026 void *context);
10027 static void *async_client_context;
10028 static serial_event_ftype remote_async_serial_handler;
10029
10030 static void
10031 remote_async_serial_handler (struct serial *scb, void *context)
10032 {
10033 /* Don't propogate error information up to the client. Instead let
10034 the client find out about the error by querying the target. */
10035 async_client_callback (INF_REG_EVENT, async_client_context);
10036 }
10037
10038 static void
10039 remote_async_inferior_event_handler (gdb_client_data data)
10040 {
10041 inferior_event_handler (INF_REG_EVENT, NULL);
10042 }
10043
10044 static void
10045 remote_async_get_pending_events_handler (gdb_client_data data)
10046 {
10047 remote_get_pending_stop_replies ();
10048 }
10049
10050 static void
10051 remote_async (void (*callback) (enum inferior_event_type event_type,
10052 void *context), void *context)
10053 {
10054 if (remote_async_mask_value == 0)
10055 internal_error (__FILE__, __LINE__,
10056 _("Calling remote_async when async is masked"));
10057
10058 if (callback != NULL)
10059 {
10060 serial_async (remote_desc, remote_async_serial_handler, NULL);
10061 async_client_callback = callback;
10062 async_client_context = context;
10063 }
10064 else
10065 serial_async (remote_desc, NULL, NULL);
10066 }
10067
10068 static int
10069 remote_async_mask (int new_mask)
10070 {
10071 int curr_mask = remote_async_mask_value;
10072 remote_async_mask_value = new_mask;
10073 return curr_mask;
10074 }
10075
10076 static void
10077 set_remote_cmd (char *args, int from_tty)
10078 {
10079 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
10080 }
10081
10082 static void
10083 show_remote_cmd (char *args, int from_tty)
10084 {
10085 /* We can't just use cmd_show_list here, because we want to skip
10086 the redundant "show remote Z-packet" and the legacy aliases. */
10087 struct cleanup *showlist_chain;
10088 struct cmd_list_element *list = remote_show_cmdlist;
10089
10090 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
10091 for (; list != NULL; list = list->next)
10092 if (strcmp (list->name, "Z-packet") == 0)
10093 continue;
10094 else if (list->type == not_set_cmd)
10095 /* Alias commands are exactly like the original, except they
10096 don't have the normal type. */
10097 continue;
10098 else
10099 {
10100 struct cleanup *option_chain
10101 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
10102 ui_out_field_string (uiout, "name", list->name);
10103 ui_out_text (uiout, ": ");
10104 if (list->type == show_cmd)
10105 do_setshow_command ((char *) NULL, from_tty, list);
10106 else
10107 cmd_func (list, NULL, from_tty);
10108 /* Close the tuple. */
10109 do_cleanups (option_chain);
10110 }
10111
10112 /* Close the tuple. */
10113 do_cleanups (showlist_chain);
10114 }
10115
10116
10117 /* Function to be called whenever a new objfile (shlib) is detected. */
10118 static void
10119 remote_new_objfile (struct objfile *objfile)
10120 {
10121 if (remote_desc != 0) /* Have a remote connection. */
10122 remote_check_symbols (objfile);
10123 }
10124
10125 /* Pull all the tracepoints defined on the target and create local
10126 data structures representing them. We don't want to create real
10127 tracepoints yet, we don't want to mess up the user's existing
10128 collection. */
10129
10130 static int
10131 remote_upload_tracepoints (struct uploaded_tp **utpp)
10132 {
10133 struct remote_state *rs = get_remote_state ();
10134 char *p;
10135
10136 /* Ask for a first packet of tracepoint definition. */
10137 putpkt ("qTfP");
10138 getpkt (&rs->buf, &rs->buf_size, 0);
10139 p = rs->buf;
10140 while (*p && *p != 'l')
10141 {
10142 parse_tracepoint_definition (p, utpp);
10143 /* Ask for another packet of tracepoint definition. */
10144 putpkt ("qTsP");
10145 getpkt (&rs->buf, &rs->buf_size, 0);
10146 p = rs->buf;
10147 }
10148 return 0;
10149 }
10150
10151 static int
10152 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
10153 {
10154 struct remote_state *rs = get_remote_state ();
10155 char *p;
10156
10157 /* Ask for a first packet of variable definition. */
10158 putpkt ("qTfV");
10159 getpkt (&rs->buf, &rs->buf_size, 0);
10160 p = rs->buf;
10161 while (*p && *p != 'l')
10162 {
10163 parse_tsv_definition (p, utsvp);
10164 /* Ask for another packet of variable definition. */
10165 putpkt ("qTsV");
10166 getpkt (&rs->buf, &rs->buf_size, 0);
10167 p = rs->buf;
10168 }
10169 return 0;
10170 }
10171
10172 void
10173 _initialize_remote (void)
10174 {
10175 struct remote_state *rs;
10176 struct cmd_list_element *cmd;
10177 char *cmd_name;
10178
10179 /* architecture specific data */
10180 remote_gdbarch_data_handle =
10181 gdbarch_data_register_post_init (init_remote_state);
10182 remote_g_packet_data_handle =
10183 gdbarch_data_register_pre_init (remote_g_packet_data_init);
10184
10185 /* Initialize the per-target state. At the moment there is only one
10186 of these, not one per target. Only one target is active at a
10187 time. The default buffer size is unimportant; it will be expanded
10188 whenever a larger buffer is needed. */
10189 rs = get_remote_state_raw ();
10190 rs->buf_size = 400;
10191 rs->buf = xmalloc (rs->buf_size);
10192
10193 init_remote_ops ();
10194 add_target (&remote_ops);
10195
10196 init_extended_remote_ops ();
10197 add_target (&extended_remote_ops);
10198
10199 /* Hook into new objfile notification. */
10200 observer_attach_new_objfile (remote_new_objfile);
10201
10202 /* Set up signal handlers. */
10203 sigint_remote_token =
10204 create_async_signal_handler (async_remote_interrupt, NULL);
10205 sigint_remote_twice_token =
10206 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
10207
10208 #if 0
10209 init_remote_threadtests ();
10210 #endif
10211
10212 /* set/show remote ... */
10213
10214 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
10215 Remote protocol specific variables\n\
10216 Configure various remote-protocol specific variables such as\n\
10217 the packets being used"),
10218 &remote_set_cmdlist, "set remote ",
10219 0 /* allow-unknown */, &setlist);
10220 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
10221 Remote protocol specific variables\n\
10222 Configure various remote-protocol specific variables such as\n\
10223 the packets being used"),
10224 &remote_show_cmdlist, "show remote ",
10225 0 /* allow-unknown */, &showlist);
10226
10227 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
10228 Compare section data on target to the exec file.\n\
10229 Argument is a single section name (default: all loaded sections)."),
10230 &cmdlist);
10231
10232 add_cmd ("packet", class_maintenance, packet_command, _("\
10233 Send an arbitrary packet to a remote target.\n\
10234 maintenance packet TEXT\n\
10235 If GDB is talking to an inferior via the GDB serial protocol, then\n\
10236 this command sends the string TEXT to the inferior, and displays the\n\
10237 response packet. GDB supplies the initial `$' character, and the\n\
10238 terminating `#' character and checksum."),
10239 &maintenancelist);
10240
10241 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
10242 Set whether to send break if interrupted."), _("\
10243 Show whether to send break if interrupted."), _("\
10244 If set, a break, instead of a cntrl-c, is sent to the remote target."),
10245 set_remotebreak, show_remotebreak,
10246 &setlist, &showlist);
10247 cmd_name = "remotebreak";
10248 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
10249 deprecate_cmd (cmd, "set remote interrupt-sequence");
10250 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
10251 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
10252 deprecate_cmd (cmd, "show remote interrupt-sequence");
10253
10254 add_setshow_enum_cmd ("interrupt-sequence", class_support,
10255 interrupt_sequence_modes, &interrupt_sequence_mode, _("\
10256 Set interrupt sequence to remote target."), _("\
10257 Show interrupt sequence to remote target."), _("\
10258 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
10259 NULL, show_interrupt_sequence,
10260 &remote_set_cmdlist,
10261 &remote_show_cmdlist);
10262
10263 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
10264 &interrupt_on_connect, _("\
10265 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10266 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10267 If set, interrupt sequence is sent to remote target."),
10268 NULL, NULL,
10269 &remote_set_cmdlist, &remote_show_cmdlist);
10270
10271 /* Install commands for configuring memory read/write packets. */
10272
10273 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
10274 Set the maximum number of bytes per memory write packet (deprecated)."),
10275 &setlist);
10276 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
10277 Show the maximum number of bytes per memory write packet (deprecated)."),
10278 &showlist);
10279 add_cmd ("memory-write-packet-size", no_class,
10280 set_memory_write_packet_size, _("\
10281 Set the maximum number of bytes per memory-write packet.\n\
10282 Specify the number of bytes in a packet or 0 (zero) for the\n\
10283 default packet size. The actual limit is further reduced\n\
10284 dependent on the target. Specify ``fixed'' to disable the\n\
10285 further restriction and ``limit'' to enable that restriction."),
10286 &remote_set_cmdlist);
10287 add_cmd ("memory-read-packet-size", no_class,
10288 set_memory_read_packet_size, _("\
10289 Set the maximum number of bytes per memory-read packet.\n\
10290 Specify the number of bytes in a packet or 0 (zero) for the\n\
10291 default packet size. The actual limit is further reduced\n\
10292 dependent on the target. Specify ``fixed'' to disable the\n\
10293 further restriction and ``limit'' to enable that restriction."),
10294 &remote_set_cmdlist);
10295 add_cmd ("memory-write-packet-size", no_class,
10296 show_memory_write_packet_size,
10297 _("Show the maximum number of bytes per memory-write packet."),
10298 &remote_show_cmdlist);
10299 add_cmd ("memory-read-packet-size", no_class,
10300 show_memory_read_packet_size,
10301 _("Show the maximum number of bytes per memory-read packet."),
10302 &remote_show_cmdlist);
10303
10304 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
10305 &remote_hw_watchpoint_limit, _("\
10306 Set the maximum number of target hardware watchpoints."), _("\
10307 Show the maximum number of target hardware watchpoints."), _("\
10308 Specify a negative limit for unlimited."),
10309 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
10310 &remote_set_cmdlist, &remote_show_cmdlist);
10311 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
10312 &remote_hw_breakpoint_limit, _("\
10313 Set the maximum number of target hardware breakpoints."), _("\
10314 Show the maximum number of target hardware breakpoints."), _("\
10315 Specify a negative limit for unlimited."),
10316 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
10317 &remote_set_cmdlist, &remote_show_cmdlist);
10318
10319 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
10320 &remote_address_size, _("\
10321 Set the maximum size of the address (in bits) in a memory packet."), _("\
10322 Show the maximum size of the address (in bits) in a memory packet."), NULL,
10323 NULL,
10324 NULL, /* FIXME: i18n: */
10325 &setlist, &showlist);
10326
10327 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
10328 "X", "binary-download", 1);
10329
10330 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
10331 "vCont", "verbose-resume", 0);
10332
10333 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
10334 "QPassSignals", "pass-signals", 0);
10335
10336 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
10337 "qSymbol", "symbol-lookup", 0);
10338
10339 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
10340 "P", "set-register", 1);
10341
10342 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
10343 "p", "fetch-register", 1);
10344
10345 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
10346 "Z0", "software-breakpoint", 0);
10347
10348 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
10349 "Z1", "hardware-breakpoint", 0);
10350
10351 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
10352 "Z2", "write-watchpoint", 0);
10353
10354 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
10355 "Z3", "read-watchpoint", 0);
10356
10357 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
10358 "Z4", "access-watchpoint", 0);
10359
10360 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
10361 "qXfer:auxv:read", "read-aux-vector", 0);
10362
10363 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
10364 "qXfer:features:read", "target-features", 0);
10365
10366 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
10367 "qXfer:libraries:read", "library-info", 0);
10368
10369 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
10370 "qXfer:memory-map:read", "memory-map", 0);
10371
10372 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
10373 "qXfer:spu:read", "read-spu-object", 0);
10374
10375 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
10376 "qXfer:spu:write", "write-spu-object", 0);
10377
10378 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
10379 "qXfer:osdata:read", "osdata", 0);
10380
10381 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
10382 "qXfer:threads:read", "threads", 0);
10383
10384 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
10385 "qXfer:siginfo:read", "read-siginfo-object", 0);
10386
10387 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
10388 "qXfer:siginfo:write", "write-siginfo-object", 0);
10389
10390 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
10391 "qGetTLSAddr", "get-thread-local-storage-address",
10392 0);
10393
10394 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
10395 "qGetTIBAddr", "get-thread-information-block-address",
10396 0);
10397
10398 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
10399 "bc", "reverse-continue", 0);
10400
10401 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
10402 "bs", "reverse-step", 0);
10403
10404 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
10405 "qSupported", "supported-packets", 0);
10406
10407 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
10408 "qSearch:memory", "search-memory", 0);
10409
10410 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
10411 "vFile:open", "hostio-open", 0);
10412
10413 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
10414 "vFile:pread", "hostio-pread", 0);
10415
10416 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
10417 "vFile:pwrite", "hostio-pwrite", 0);
10418
10419 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
10420 "vFile:close", "hostio-close", 0);
10421
10422 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
10423 "vFile:unlink", "hostio-unlink", 0);
10424
10425 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
10426 "vAttach", "attach", 0);
10427
10428 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
10429 "vRun", "run", 0);
10430
10431 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
10432 "QStartNoAckMode", "noack", 0);
10433
10434 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
10435 "vKill", "kill", 0);
10436
10437 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
10438 "qAttached", "query-attached", 0);
10439
10440 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
10441 "ConditionalTracepoints", "conditional-tracepoints", 0);
10442 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
10443 "FastTracepoints", "fast-tracepoints", 0);
10444
10445 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
10446 "TracepointSource", "TracepointSource", 0);
10447
10448 /* Keep the old ``set remote Z-packet ...'' working. Each individual
10449 Z sub-packet has its own set and show commands, but users may
10450 have sets to this variable in their .gdbinit files (or in their
10451 documentation). */
10452 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
10453 &remote_Z_packet_detect, _("\
10454 Set use of remote protocol `Z' packets"), _("\
10455 Show use of remote protocol `Z' packets "), _("\
10456 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
10457 packets."),
10458 set_remote_protocol_Z_packet_cmd,
10459 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
10460 &remote_set_cmdlist, &remote_show_cmdlist);
10461
10462 add_prefix_cmd ("remote", class_files, remote_command, _("\
10463 Manipulate files on the remote system\n\
10464 Transfer files to and from the remote target system."),
10465 &remote_cmdlist, "remote ",
10466 0 /* allow-unknown */, &cmdlist);
10467
10468 add_cmd ("put", class_files, remote_put_command,
10469 _("Copy a local file to the remote system."),
10470 &remote_cmdlist);
10471
10472 add_cmd ("get", class_files, remote_get_command,
10473 _("Copy a remote file to the local system."),
10474 &remote_cmdlist);
10475
10476 add_cmd ("delete", class_files, remote_delete_command,
10477 _("Delete a remote file."),
10478 &remote_cmdlist);
10479
10480 remote_exec_file = xstrdup ("");
10481 add_setshow_string_noescape_cmd ("exec-file", class_files,
10482 &remote_exec_file, _("\
10483 Set the remote pathname for \"run\""), _("\
10484 Show the remote pathname for \"run\""), NULL, NULL, NULL,
10485 &remote_set_cmdlist, &remote_show_cmdlist);
10486
10487 /* Eventually initialize fileio. See fileio.c */
10488 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
10489
10490 /* Take advantage of the fact that the LWP field is not used, to tag
10491 special ptids with it set to != 0. */
10492 magic_null_ptid = ptid_build (42000, 1, -1);
10493 not_sent_ptid = ptid_build (42000, 1, -2);
10494 any_thread_ptid = ptid_build (42000, 1, 0);
10495
10496 target_buf_size = 2048;
10497 target_buf = xmalloc (target_buf_size);
10498 }
10499