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