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