2e2871d2fc28d0c4e0714a3671de41c5bccecd5d
[deliverable/binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
4 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
5 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 2 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, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 Boston, MA 02110-1301, USA. */
23
24 /* See the GDB User Guide for details of the GDB remote protocol. */
25
26 #include "defs.h"
27 #include "gdb_string.h"
28 #include <ctype.h>
29 #include <fcntl.h>
30 #include "inferior.h"
31 #include "bfd.h"
32 #include "symfile.h"
33 #include "exceptions.h"
34 #include "target.h"
35 /*#include "terminal.h" */
36 #include "gdbcmd.h"
37 #include "objfiles.h"
38 #include "gdb-stabs.h"
39 #include "gdbthread.h"
40 #include "remote.h"
41 #include "regcache.h"
42 #include "value.h"
43 #include "gdb_assert.h"
44 #include "observer.h"
45 #include "solib.h"
46 #include "cli/cli-decode.h"
47 #include "cli/cli-setshow.h"
48
49 #include <ctype.h>
50 #include <sys/time.h>
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62
63 /* The size to align memory write packets, when practical. The protocol
64 does not guarantee any alignment, and gdb will generate short
65 writes and unaligned writes, but even as a best-effort attempt this
66 can improve bulk transfers. For instance, if a write is misaligned
67 relative to the target's data bus, the stub may need to make an extra
68 round trip fetching data from the target. This doesn't make a
69 huge difference, but it's easy to do, so we try to be helpful.
70
71 The alignment chosen is arbitrary; usually data bus width is
72 important here, not the possibly larger cache line size. */
73 enum { REMOTE_ALIGN_WRITES = 16 };
74
75 /* Prototypes for local functions. */
76 static void cleanup_sigint_signal_handler (void *dummy);
77 static void initialize_sigint_signal_handler (void);
78 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
79
80 static void handle_remote_sigint (int);
81 static void handle_remote_sigint_twice (int);
82 static void async_remote_interrupt (gdb_client_data);
83 void async_remote_interrupt_twice (gdb_client_data);
84
85 static void build_remote_gdbarch_data (void);
86
87 static void remote_files_info (struct target_ops *ignore);
88
89 static void remote_prepare_to_store (void);
90
91 static void remote_fetch_registers (int regno);
92
93 static void remote_resume (ptid_t ptid, int step,
94 enum target_signal siggnal);
95 static void remote_async_resume (ptid_t ptid, int step,
96 enum target_signal siggnal);
97 static void remote_open (char *name, int from_tty);
98 static void remote_async_open (char *name, int from_tty);
99
100 static void extended_remote_open (char *name, int from_tty);
101 static void extended_remote_async_open (char *name, int from_tty);
102
103 static void remote_open_1 (char *, int, struct target_ops *, int extended_p,
104 int async_p);
105
106 static void remote_close (int quitting);
107
108 static void remote_store_registers (int regno);
109
110 static void remote_mourn (void);
111 static void remote_async_mourn (void);
112
113 static void extended_remote_restart (void);
114
115 static void extended_remote_mourn (void);
116
117 static void remote_mourn_1 (struct target_ops *);
118
119 static void remote_send (char **buf, long *sizeof_buf_p);
120
121 static int readchar (int timeout);
122
123 static ptid_t remote_wait (ptid_t ptid,
124 struct target_waitstatus *status);
125 static ptid_t remote_async_wait (ptid_t ptid,
126 struct target_waitstatus *status);
127
128 static void remote_kill (void);
129 static void remote_async_kill (void);
130
131 static int tohex (int nib);
132
133 static void remote_detach (char *args, int from_tty);
134
135 static void remote_interrupt (int signo);
136
137 static void remote_interrupt_twice (int signo);
138
139 static void interrupt_query (void);
140
141 static void set_thread (int, int);
142
143 static int remote_thread_alive (ptid_t);
144
145 static void get_offsets (void);
146
147 static void skip_frame (void);
148
149 static long read_frame (char **buf_p, long *sizeof_buf);
150
151 static int hexnumlen (ULONGEST num);
152
153 static void init_remote_ops (void);
154
155 static void init_extended_remote_ops (void);
156
157 static void remote_stop (void);
158
159 static int ishex (int ch, int *val);
160
161 static int stubhex (int ch);
162
163 static int hexnumstr (char *, ULONGEST);
164
165 static int hexnumnstr (char *, ULONGEST, int);
166
167 static CORE_ADDR remote_address_masked (CORE_ADDR);
168
169 static void print_packet (char *);
170
171 static unsigned long crc32 (unsigned char *, int, unsigned int);
172
173 static void compare_sections_command (char *, int);
174
175 static void packet_command (char *, int);
176
177 static int stub_unpack_int (char *buff, int fieldlength);
178
179 static ptid_t remote_current_thread (ptid_t oldptid);
180
181 static void remote_find_new_threads (void);
182
183 static void record_currthread (int currthread);
184
185 static int fromhex (int a);
186
187 static int hex2bin (const char *hex, gdb_byte *bin, int count);
188
189 static int bin2hex (const gdb_byte *bin, char *hex, int count);
190
191 static int putpkt_binary (char *buf, int cnt);
192
193 static void check_binary_download (CORE_ADDR addr);
194
195 struct packet_config;
196
197 static void show_packet_config_cmd (struct packet_config *config);
198
199 static void update_packet_config (struct packet_config *config);
200
201 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
202 struct cmd_list_element *c);
203
204 static void show_remote_protocol_packet_cmd (struct ui_file *file,
205 int from_tty,
206 struct cmd_list_element *c,
207 const char *value);
208
209 void _initialize_remote (void);
210
211 /* For "set remote" and "show remote". */
212
213 static struct cmd_list_element *remote_set_cmdlist;
214 static struct cmd_list_element *remote_show_cmdlist;
215
216 /* Description of the remote protocol state for the currently
217 connected target. This is per-target state, and independent of the
218 selected architecture. */
219
220 struct remote_state
221 {
222 /* A buffer to use for incoming packets, and its current size. The
223 buffer is grown dynamically for larger incoming packets.
224 Outgoing packets may also be constructed in this buffer.
225 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
226 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
227 packets. */
228 char *buf;
229 long buf_size;
230
231 /* If we negotiated packet size explicitly (and thus can bypass
232 heuristics for the largest packet size that will not overflow
233 a buffer in the stub), this will be set to that packet size.
234 Otherwise zero, meaning to use the guessed size. */
235 long explicit_packet_size;
236 };
237
238 /* This data could be associated with a target, but we do not always
239 have access to the current target when we need it, so for now it is
240 static. This will be fine for as long as only one target is in use
241 at a time. */
242 static struct remote_state remote_state;
243
244 static struct remote_state *
245 get_remote_state (void)
246 {
247 return &remote_state;
248 }
249
250 /* Description of the remote protocol for a given architecture. */
251
252 struct packet_reg
253 {
254 long offset; /* Offset into G packet. */
255 long regnum; /* GDB's internal register number. */
256 LONGEST pnum; /* Remote protocol register number. */
257 int in_g_packet; /* Always part of G packet. */
258 /* long size in bytes; == register_size (current_gdbarch, regnum);
259 at present. */
260 /* char *name; == REGISTER_NAME (regnum); at present. */
261 };
262
263 struct remote_arch_state
264 {
265 /* Description of the remote protocol registers. */
266 long sizeof_g_packet;
267
268 /* Description of the remote protocol registers indexed by REGNUM
269 (making an array of NUM_REGS + NUM_PSEUDO_REGS in size). */
270 struct packet_reg *regs;
271
272 /* This is the size (in chars) of the first response to the ``g''
273 packet. It is used as a heuristic when determining the maximum
274 size of memory-read and memory-write packets. A target will
275 typically only reserve a buffer large enough to hold the ``g''
276 packet. The size does not include packet overhead (headers and
277 trailers). */
278 long actual_register_packet_size;
279
280 /* This is the maximum size (in chars) of a non read/write packet.
281 It is also used as a cap on the size of read/write packets. */
282 long remote_packet_size;
283 };
284
285
286 /* Handle for retreving the remote protocol data from gdbarch. */
287 static struct gdbarch_data *remote_gdbarch_data_handle;
288
289 static struct remote_arch_state *
290 get_remote_arch_state (void)
291 {
292 return gdbarch_data (current_gdbarch, remote_gdbarch_data_handle);
293 }
294
295 static void *
296 init_remote_state (struct gdbarch *gdbarch)
297 {
298 int regnum;
299 struct remote_state *rs = get_remote_state ();
300 struct remote_arch_state *rsa;
301
302 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
303
304 rsa->sizeof_g_packet = 0;
305
306 /* Assume a 1:1 regnum<->pnum table. */
307 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch, NUM_REGS + NUM_PSEUDO_REGS,
308 struct packet_reg);
309 for (regnum = 0; regnum < NUM_REGS + NUM_PSEUDO_REGS; regnum++)
310 {
311 struct packet_reg *r = &rsa->regs[regnum];
312 r->pnum = regnum;
313 r->regnum = regnum;
314 r->offset = DEPRECATED_REGISTER_BYTE (regnum);
315 r->in_g_packet = (regnum < NUM_REGS);
316 /* ...name = REGISTER_NAME (regnum); */
317
318 /* Compute packet size by accumulating the size of all registers. */
319 if (regnum < NUM_REGS)
320 rsa->sizeof_g_packet += register_size (current_gdbarch, regnum);
321 }
322
323 /* Default maximum number of characters in a packet body. Many
324 remote stubs have a hardwired buffer size of 400 bytes
325 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
326 as the maximum packet-size to ensure that the packet and an extra
327 NUL character can always fit in the buffer. This stops GDB
328 trashing stubs that try to squeeze an extra NUL into what is
329 already a full buffer (As of 1999-12-04 that was most stubs). */
330 rsa->remote_packet_size = 400 - 1;
331
332 /* This one is filled in when a ``g'' packet is received. */
333 rsa->actual_register_packet_size = 0;
334
335 /* Should rsa->sizeof_g_packet needs more space than the
336 default, adjust the size accordingly. Remember that each byte is
337 encoded as two characters. 32 is the overhead for the packet
338 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
339 (``$NN:G...#NN'') is a better guess, the below has been padded a
340 little. */
341 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
342 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
343
344 /* Make sure that the packet buffer is plenty big enough for
345 this architecture. */
346 if (rs->buf_size < rsa->remote_packet_size)
347 {
348 rs->buf_size = 2 * rsa->remote_packet_size;
349 rs->buf = xrealloc (rs->buf, rs->buf_size);
350 }
351
352 return rsa;
353 }
354
355 /* Return the current allowed size of a remote packet. This is
356 inferred from the current architecture, and should be used to
357 limit the length of outgoing packets. */
358 static long
359 get_remote_packet_size (void)
360 {
361 struct remote_state *rs = get_remote_state ();
362 struct remote_arch_state *rsa = get_remote_arch_state ();
363
364 if (rs->explicit_packet_size)
365 return rs->explicit_packet_size;
366
367 return rsa->remote_packet_size;
368 }
369
370 static struct packet_reg *
371 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
372 {
373 if (regnum < 0 && regnum >= NUM_REGS + NUM_PSEUDO_REGS)
374 return NULL;
375 else
376 {
377 struct packet_reg *r = &rsa->regs[regnum];
378 gdb_assert (r->regnum == regnum);
379 return r;
380 }
381 }
382
383 static struct packet_reg *
384 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
385 {
386 int i;
387 for (i = 0; i < NUM_REGS + NUM_PSEUDO_REGS; i++)
388 {
389 struct packet_reg *r = &rsa->regs[i];
390 if (r->pnum == pnum)
391 return r;
392 }
393 return NULL;
394 }
395
396 /* FIXME: graces/2002-08-08: These variables should eventually be
397 bound to an instance of the target object (as in gdbarch-tdep()),
398 when such a thing exists. */
399
400 /* This is set to the data address of the access causing the target
401 to stop for a watchpoint. */
402 static CORE_ADDR remote_watch_data_address;
403
404 /* This is non-zero if target stopped for a watchpoint. */
405 static int remote_stopped_by_watchpoint_p;
406
407 static struct target_ops remote_ops;
408
409 static struct target_ops extended_remote_ops;
410
411 /* Temporary target ops. Just like the remote_ops and
412 extended_remote_ops, but with asynchronous support. */
413 static struct target_ops remote_async_ops;
414
415 static struct target_ops extended_async_remote_ops;
416
417 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
418 ``forever'' still use the normal timeout mechanism. This is
419 currently used by the ASYNC code to guarentee that target reads
420 during the initial connect always time-out. Once getpkt has been
421 modified to return a timeout indication and, in turn
422 remote_wait()/wait_for_inferior() have gained a timeout parameter
423 this can go away. */
424 static int wait_forever_enabled_p = 1;
425
426
427 /* This variable chooses whether to send a ^C or a break when the user
428 requests program interruption. Although ^C is usually what remote
429 systems expect, and that is the default here, sometimes a break is
430 preferable instead. */
431
432 static int remote_break;
433
434 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
435 remote_open knows that we don't have a file open when the program
436 starts. */
437 static struct serial *remote_desc = NULL;
438
439 /* This variable sets the number of bits in an address that are to be
440 sent in a memory ("M" or "m") packet. Normally, after stripping
441 leading zeros, the entire address would be sent. This variable
442 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
443 initial implementation of remote.c restricted the address sent in
444 memory packets to ``host::sizeof long'' bytes - (typically 32
445 bits). Consequently, for 64 bit targets, the upper 32 bits of an
446 address was never sent. Since fixing this bug may cause a break in
447 some remote targets this variable is principly provided to
448 facilitate backward compatibility. */
449
450 static int remote_address_size;
451
452 /* Tempoary to track who currently owns the terminal. See
453 target_async_terminal_* for more details. */
454
455 static int remote_async_terminal_ours_p;
456
457 \f
458 /* User configurable variables for the number of characters in a
459 memory read/write packet. MIN (rsa->remote_packet_size,
460 rsa->sizeof_g_packet) is the default. Some targets need smaller
461 values (fifo overruns, et.al.) and some users need larger values
462 (speed up transfers). The variables ``preferred_*'' (the user
463 request), ``current_*'' (what was actually set) and ``forced_*''
464 (Positive - a soft limit, negative - a hard limit). */
465
466 struct memory_packet_config
467 {
468 char *name;
469 long size;
470 int fixed_p;
471 };
472
473 /* Compute the current size of a read/write packet. Since this makes
474 use of ``actual_register_packet_size'' the computation is dynamic. */
475
476 static long
477 get_memory_packet_size (struct memory_packet_config *config)
478 {
479 struct remote_state *rs = get_remote_state ();
480 struct remote_arch_state *rsa = get_remote_arch_state ();
481
482 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
483 law?) that some hosts don't cope very well with large alloca()
484 calls. Eventually the alloca() code will be replaced by calls to
485 xmalloc() and make_cleanups() allowing this restriction to either
486 be lifted or removed. */
487 #ifndef MAX_REMOTE_PACKET_SIZE
488 #define MAX_REMOTE_PACKET_SIZE 16384
489 #endif
490 /* NOTE: 20 ensures we can write at least one byte. */
491 #ifndef MIN_REMOTE_PACKET_SIZE
492 #define MIN_REMOTE_PACKET_SIZE 20
493 #endif
494 long what_they_get;
495 if (config->fixed_p)
496 {
497 if (config->size <= 0)
498 what_they_get = MAX_REMOTE_PACKET_SIZE;
499 else
500 what_they_get = config->size;
501 }
502 else
503 {
504 what_they_get = get_remote_packet_size ();
505 /* Limit the packet to the size specified by the user. */
506 if (config->size > 0
507 && what_they_get > config->size)
508 what_they_get = config->size;
509
510 /* Limit it to the size of the targets ``g'' response unless we have
511 permission from the stub to use a larger packet size. */
512 if (rs->explicit_packet_size == 0
513 && rsa->actual_register_packet_size > 0
514 && what_they_get > rsa->actual_register_packet_size)
515 what_they_get = rsa->actual_register_packet_size;
516 }
517 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
518 what_they_get = MAX_REMOTE_PACKET_SIZE;
519 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
520 what_they_get = MIN_REMOTE_PACKET_SIZE;
521
522 /* Make sure there is room in the global buffer for this packet
523 (including its trailing NUL byte). */
524 if (rs->buf_size < what_they_get + 1)
525 {
526 rs->buf_size = 2 * what_they_get;
527 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
528 }
529
530 return what_they_get;
531 }
532
533 /* Update the size of a read/write packet. If they user wants
534 something really big then do a sanity check. */
535
536 static void
537 set_memory_packet_size (char *args, struct memory_packet_config *config)
538 {
539 int fixed_p = config->fixed_p;
540 long size = config->size;
541 if (args == NULL)
542 error (_("Argument required (integer, `fixed' or `limited')."));
543 else if (strcmp (args, "hard") == 0
544 || strcmp (args, "fixed") == 0)
545 fixed_p = 1;
546 else if (strcmp (args, "soft") == 0
547 || strcmp (args, "limit") == 0)
548 fixed_p = 0;
549 else
550 {
551 char *end;
552 size = strtoul (args, &end, 0);
553 if (args == end)
554 error (_("Invalid %s (bad syntax)."), config->name);
555 #if 0
556 /* Instead of explicitly capping the size of a packet to
557 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
558 instead allowed to set the size to something arbitrarily
559 large. */
560 if (size > MAX_REMOTE_PACKET_SIZE)
561 error (_("Invalid %s (too large)."), config->name);
562 #endif
563 }
564 /* Extra checks? */
565 if (fixed_p && !config->fixed_p)
566 {
567 if (! query (_("The target may not be able to correctly handle a %s\n"
568 "of %ld bytes. Change the packet size? "),
569 config->name, size))
570 error (_("Packet size not changed."));
571 }
572 /* Update the config. */
573 config->fixed_p = fixed_p;
574 config->size = size;
575 }
576
577 static void
578 show_memory_packet_size (struct memory_packet_config *config)
579 {
580 printf_filtered (_("The %s is %ld. "), config->name, config->size);
581 if (config->fixed_p)
582 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
583 get_memory_packet_size (config));
584 else
585 printf_filtered (_("Packets are limited to %ld bytes.\n"),
586 get_memory_packet_size (config));
587 }
588
589 static struct memory_packet_config memory_write_packet_config =
590 {
591 "memory-write-packet-size",
592 };
593
594 static void
595 set_memory_write_packet_size (char *args, int from_tty)
596 {
597 set_memory_packet_size (args, &memory_write_packet_config);
598 }
599
600 static void
601 show_memory_write_packet_size (char *args, int from_tty)
602 {
603 show_memory_packet_size (&memory_write_packet_config);
604 }
605
606 static long
607 get_memory_write_packet_size (void)
608 {
609 return get_memory_packet_size (&memory_write_packet_config);
610 }
611
612 static struct memory_packet_config memory_read_packet_config =
613 {
614 "memory-read-packet-size",
615 };
616
617 static void
618 set_memory_read_packet_size (char *args, int from_tty)
619 {
620 set_memory_packet_size (args, &memory_read_packet_config);
621 }
622
623 static void
624 show_memory_read_packet_size (char *args, int from_tty)
625 {
626 show_memory_packet_size (&memory_read_packet_config);
627 }
628
629 static long
630 get_memory_read_packet_size (void)
631 {
632 long size = get_memory_packet_size (&memory_read_packet_config);
633 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
634 extra buffer size argument before the memory read size can be
635 increased beyond this. */
636 if (size > get_remote_packet_size ())
637 size = get_remote_packet_size ();
638 return size;
639 }
640
641 \f
642 /* Generic configuration support for packets the stub optionally
643 supports. Allows the user to specify the use of the packet as well
644 as allowing GDB to auto-detect support in the remote stub. */
645
646 enum packet_support
647 {
648 PACKET_SUPPORT_UNKNOWN = 0,
649 PACKET_ENABLE,
650 PACKET_DISABLE
651 };
652
653 struct packet_config
654 {
655 const char *name;
656 const char *title;
657 enum auto_boolean detect;
658 enum packet_support support;
659 };
660
661 /* Analyze a packet's return value and update the packet config
662 accordingly. */
663
664 enum packet_result
665 {
666 PACKET_ERROR,
667 PACKET_OK,
668 PACKET_UNKNOWN
669 };
670
671 static void
672 update_packet_config (struct packet_config *config)
673 {
674 switch (config->detect)
675 {
676 case AUTO_BOOLEAN_TRUE:
677 config->support = PACKET_ENABLE;
678 break;
679 case AUTO_BOOLEAN_FALSE:
680 config->support = PACKET_DISABLE;
681 break;
682 case AUTO_BOOLEAN_AUTO:
683 config->support = PACKET_SUPPORT_UNKNOWN;
684 break;
685 }
686 }
687
688 static void
689 show_packet_config_cmd (struct packet_config *config)
690 {
691 char *support = "internal-error";
692 switch (config->support)
693 {
694 case PACKET_ENABLE:
695 support = "enabled";
696 break;
697 case PACKET_DISABLE:
698 support = "disabled";
699 break;
700 case PACKET_SUPPORT_UNKNOWN:
701 support = "unknown";
702 break;
703 }
704 switch (config->detect)
705 {
706 case AUTO_BOOLEAN_AUTO:
707 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
708 config->name, support);
709 break;
710 case AUTO_BOOLEAN_TRUE:
711 case AUTO_BOOLEAN_FALSE:
712 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
713 config->name, support);
714 break;
715 }
716 }
717
718 static void
719 add_packet_config_cmd (struct packet_config *config, const char *name,
720 const char *title, int legacy)
721 {
722 char *set_doc;
723 char *show_doc;
724 char *cmd_name;
725
726 config->name = name;
727 config->title = title;
728 config->detect = AUTO_BOOLEAN_AUTO;
729 config->support = PACKET_SUPPORT_UNKNOWN;
730 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
731 name, title);
732 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
733 name, title);
734 /* set/show TITLE-packet {auto,on,off} */
735 cmd_name = xstrprintf ("%s-packet", title);
736 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
737 &config->detect, set_doc, show_doc, NULL, /* help_doc */
738 set_remote_protocol_packet_cmd,
739 show_remote_protocol_packet_cmd,
740 &remote_set_cmdlist, &remote_show_cmdlist);
741 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
742 if (legacy)
743 {
744 char *legacy_name;
745 legacy_name = xstrprintf ("%s-packet", name);
746 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
747 &remote_set_cmdlist);
748 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
749 &remote_show_cmdlist);
750 }
751 }
752
753 static enum packet_result
754 packet_ok (const char *buf, struct packet_config *config)
755 {
756 if (buf[0] != '\0')
757 {
758 /* The stub recognized the packet request. Check that the
759 operation succeeded. */
760 switch (config->support)
761 {
762 case PACKET_SUPPORT_UNKNOWN:
763 if (remote_debug)
764 fprintf_unfiltered (gdb_stdlog,
765 "Packet %s (%s) is supported\n",
766 config->name, config->title);
767 config->support = PACKET_ENABLE;
768 break;
769 case PACKET_DISABLE:
770 internal_error (__FILE__, __LINE__,
771 _("packet_ok: attempt to use a disabled packet"));
772 break;
773 case PACKET_ENABLE:
774 break;
775 }
776 if (buf[0] == 'O' && buf[1] == 'K' && buf[2] == '\0')
777 /* "OK" - definitly OK. */
778 return PACKET_OK;
779 if (buf[0] == 'E'
780 && isxdigit (buf[1]) && isxdigit (buf[2])
781 && buf[3] == '\0')
782 /* "Enn" - definitly an error. */
783 return PACKET_ERROR;
784 /* The packet may or may not be OK. Just assume it is. */
785 return PACKET_OK;
786 }
787 else
788 {
789 /* The stub does not support the packet. */
790 switch (config->support)
791 {
792 case PACKET_ENABLE:
793 if (config->detect == AUTO_BOOLEAN_AUTO)
794 /* If the stub previously indicated that the packet was
795 supported then there is a protocol error.. */
796 error (_("Protocol error: %s (%s) conflicting enabled responses."),
797 config->name, config->title);
798 else
799 /* The user set it wrong. */
800 error (_("Enabled packet %s (%s) not recognized by stub"),
801 config->name, config->title);
802 break;
803 case PACKET_SUPPORT_UNKNOWN:
804 if (remote_debug)
805 fprintf_unfiltered (gdb_stdlog,
806 "Packet %s (%s) is NOT supported\n",
807 config->name, config->title);
808 config->support = PACKET_DISABLE;
809 break;
810 case PACKET_DISABLE:
811 break;
812 }
813 return PACKET_UNKNOWN;
814 }
815 }
816
817 enum {
818 PACKET_vCont = 0,
819 PACKET_X,
820 PACKET_qSymbol,
821 PACKET_P,
822 PACKET_p,
823 PACKET_Z0,
824 PACKET_Z1,
825 PACKET_Z2,
826 PACKET_Z3,
827 PACKET_Z4,
828 PACKET_qXfer_auxv,
829 PACKET_qGetTLSAddr,
830 PACKET_qSupported,
831 PACKET_MAX
832 };
833
834 static struct packet_config remote_protocol_packets[PACKET_MAX];
835
836 static void
837 set_remote_protocol_packet_cmd (char *args, int from_tty,
838 struct cmd_list_element *c)
839 {
840 struct packet_config *packet;
841
842 for (packet = remote_protocol_packets;
843 packet < &remote_protocol_packets[PACKET_MAX];
844 packet++)
845 {
846 if (&packet->detect == c->var)
847 {
848 update_packet_config (packet);
849 return;
850 }
851 }
852 internal_error (__FILE__, __LINE__, "Could not find config for %s",
853 c->name);
854 }
855
856 static void
857 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
858 struct cmd_list_element *c,
859 const char *value)
860 {
861 struct packet_config *packet;
862
863 for (packet = remote_protocol_packets;
864 packet < &remote_protocol_packets[PACKET_MAX];
865 packet++)
866 {
867 if (&packet->detect == c->var)
868 {
869 show_packet_config_cmd (packet);
870 return;
871 }
872 }
873 internal_error (__FILE__, __LINE__, "Could not find config for %s",
874 c->name);
875 }
876
877 /* Should we try one of the 'Z' requests? */
878
879 enum Z_packet_type
880 {
881 Z_PACKET_SOFTWARE_BP,
882 Z_PACKET_HARDWARE_BP,
883 Z_PACKET_WRITE_WP,
884 Z_PACKET_READ_WP,
885 Z_PACKET_ACCESS_WP,
886 NR_Z_PACKET_TYPES
887 };
888
889 /* For compatibility with older distributions. Provide a ``set remote
890 Z-packet ...'' command that updates all the Z packet types. */
891
892 static enum auto_boolean remote_Z_packet_detect;
893
894 static void
895 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
896 struct cmd_list_element *c)
897 {
898 int i;
899 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
900 {
901 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
902 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
903 }
904 }
905
906 static void
907 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
908 struct cmd_list_element *c,
909 const char *value)
910 {
911 int i;
912 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
913 {
914 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
915 }
916 }
917
918 /* Should we try the 'ThreadInfo' query packet?
919
920 This variable (NOT available to the user: auto-detect only!)
921 determines whether GDB will use the new, simpler "ThreadInfo"
922 query or the older, more complex syntax for thread queries.
923 This is an auto-detect variable (set to true at each connect,
924 and set to false when the target fails to recognize it). */
925
926 static int use_threadinfo_query;
927 static int use_threadextra_query;
928
929 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
930 static void *sigint_remote_twice_token;
931 static void *sigint_remote_token;
932
933 /* These are pointers to hook functions that may be set in order to
934 modify resume/wait behavior for a particular architecture. */
935
936 void (*deprecated_target_resume_hook) (void);
937 void (*deprecated_target_wait_loop_hook) (void);
938 \f
939
940
941 /* These are the threads which we last sent to the remote system.
942 -1 for all or -2 for not sent yet. */
943 static int general_thread;
944 static int continue_thread;
945
946 /* Call this function as a result of
947 1) A halt indication (T packet) containing a thread id
948 2) A direct query of currthread
949 3) Successful execution of set thread
950 */
951
952 static void
953 record_currthread (int currthread)
954 {
955 general_thread = currthread;
956
957 /* If this is a new thread, add it to GDB's thread list.
958 If we leave it up to WFI to do this, bad things will happen. */
959 if (!in_thread_list (pid_to_ptid (currthread)))
960 {
961 add_thread (pid_to_ptid (currthread));
962 ui_out_text (uiout, "[New ");
963 ui_out_text (uiout, target_pid_to_str (pid_to_ptid (currthread)));
964 ui_out_text (uiout, "]\n");
965 }
966 }
967
968 #define MAGIC_NULL_PID 42000
969
970 static void
971 set_thread (int th, int gen)
972 {
973 struct remote_state *rs = get_remote_state ();
974 char *buf = rs->buf;
975 int state = gen ? general_thread : continue_thread;
976
977 if (state == th)
978 return;
979
980 buf[0] = 'H';
981 buf[1] = gen ? 'g' : 'c';
982 if (th == MAGIC_NULL_PID)
983 {
984 buf[2] = '0';
985 buf[3] = '\0';
986 }
987 else if (th < 0)
988 xsnprintf (&buf[2], get_remote_packet_size () - 2, "-%x", -th);
989 else
990 xsnprintf (&buf[2], get_remote_packet_size () - 2, "%x", th);
991 putpkt (buf);
992 getpkt (&rs->buf, &rs->buf_size, 0);
993 if (gen)
994 general_thread = th;
995 else
996 continue_thread = th;
997 }
998 \f
999 /* Return nonzero if the thread TH is still alive on the remote system. */
1000
1001 static int
1002 remote_thread_alive (ptid_t ptid)
1003 {
1004 struct remote_state *rs = get_remote_state ();
1005 int tid = PIDGET (ptid);
1006
1007 if (tid < 0)
1008 xsnprintf (rs->buf, get_remote_packet_size (), "T-%08x", -tid);
1009 else
1010 xsnprintf (rs->buf, get_remote_packet_size (), "T%08x", tid);
1011 putpkt (rs->buf);
1012 getpkt (&rs->buf, &rs->buf_size, 0);
1013 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1014 }
1015
1016 /* About these extended threadlist and threadinfo packets. They are
1017 variable length packets but, the fields within them are often fixed
1018 length. They are redundent enough to send over UDP as is the
1019 remote protocol in general. There is a matching unit test module
1020 in libstub. */
1021
1022 #define OPAQUETHREADBYTES 8
1023
1024 /* a 64 bit opaque identifier */
1025 typedef unsigned char threadref[OPAQUETHREADBYTES];
1026
1027 /* WARNING: This threadref data structure comes from the remote O.S.,
1028 libstub protocol encoding, and remote.c. it is not particularly
1029 changable. */
1030
1031 /* Right now, the internal structure is int. We want it to be bigger.
1032 Plan to fix this.
1033 */
1034
1035 typedef int gdb_threadref; /* Internal GDB thread reference. */
1036
1037 /* gdb_ext_thread_info is an internal GDB data structure which is
1038 equivalent to the reply of the remote threadinfo packet. */
1039
1040 struct gdb_ext_thread_info
1041 {
1042 threadref threadid; /* External form of thread reference. */
1043 int active; /* Has state interesting to GDB?
1044 regs, stack. */
1045 char display[256]; /* Brief state display, name,
1046 blocked/suspended. */
1047 char shortname[32]; /* To be used to name threads. */
1048 char more_display[256]; /* Long info, statistics, queue depth,
1049 whatever. */
1050 };
1051
1052 /* The volume of remote transfers can be limited by submitting
1053 a mask containing bits specifying the desired information.
1054 Use a union of these values as the 'selection' parameter to
1055 get_thread_info. FIXME: Make these TAG names more thread specific.
1056 */
1057
1058 #define TAG_THREADID 1
1059 #define TAG_EXISTS 2
1060 #define TAG_DISPLAY 4
1061 #define TAG_THREADNAME 8
1062 #define TAG_MOREDISPLAY 16
1063
1064 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1065
1066 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1067
1068 static char *unpack_nibble (char *buf, int *val);
1069
1070 static char *pack_nibble (char *buf, int nibble);
1071
1072 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1073
1074 static char *unpack_byte (char *buf, int *value);
1075
1076 static char *pack_int (char *buf, int value);
1077
1078 static char *unpack_int (char *buf, int *value);
1079
1080 static char *unpack_string (char *src, char *dest, int length);
1081
1082 static char *pack_threadid (char *pkt, threadref *id);
1083
1084 static char *unpack_threadid (char *inbuf, threadref *id);
1085
1086 void int_to_threadref (threadref *id, int value);
1087
1088 static int threadref_to_int (threadref *ref);
1089
1090 static void copy_threadref (threadref *dest, threadref *src);
1091
1092 static int threadmatch (threadref *dest, threadref *src);
1093
1094 static char *pack_threadinfo_request (char *pkt, int mode,
1095 threadref *id);
1096
1097 static int remote_unpack_thread_info_response (char *pkt,
1098 threadref *expectedref,
1099 struct gdb_ext_thread_info
1100 *info);
1101
1102
1103 static int remote_get_threadinfo (threadref *threadid,
1104 int fieldset, /*TAG mask */
1105 struct gdb_ext_thread_info *info);
1106
1107 static char *pack_threadlist_request (char *pkt, int startflag,
1108 int threadcount,
1109 threadref *nextthread);
1110
1111 static int parse_threadlist_response (char *pkt,
1112 int result_limit,
1113 threadref *original_echo,
1114 threadref *resultlist,
1115 int *doneflag);
1116
1117 static int remote_get_threadlist (int startflag,
1118 threadref *nextthread,
1119 int result_limit,
1120 int *done,
1121 int *result_count,
1122 threadref *threadlist);
1123
1124 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1125
1126 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1127 void *context, int looplimit);
1128
1129 static int remote_newthread_step (threadref *ref, void *context);
1130
1131 /* Encode 64 bits in 16 chars of hex. */
1132
1133 static const char hexchars[] = "0123456789abcdef";
1134
1135 static int
1136 ishex (int ch, int *val)
1137 {
1138 if ((ch >= 'a') && (ch <= 'f'))
1139 {
1140 *val = ch - 'a' + 10;
1141 return 1;
1142 }
1143 if ((ch >= 'A') && (ch <= 'F'))
1144 {
1145 *val = ch - 'A' + 10;
1146 return 1;
1147 }
1148 if ((ch >= '0') && (ch <= '9'))
1149 {
1150 *val = ch - '0';
1151 return 1;
1152 }
1153 return 0;
1154 }
1155
1156 static int
1157 stubhex (int ch)
1158 {
1159 if (ch >= 'a' && ch <= 'f')
1160 return ch - 'a' + 10;
1161 if (ch >= '0' && ch <= '9')
1162 return ch - '0';
1163 if (ch >= 'A' && ch <= 'F')
1164 return ch - 'A' + 10;
1165 return -1;
1166 }
1167
1168 static int
1169 stub_unpack_int (char *buff, int fieldlength)
1170 {
1171 int nibble;
1172 int retval = 0;
1173
1174 while (fieldlength)
1175 {
1176 nibble = stubhex (*buff++);
1177 retval |= nibble;
1178 fieldlength--;
1179 if (fieldlength)
1180 retval = retval << 4;
1181 }
1182 return retval;
1183 }
1184
1185 char *
1186 unpack_varlen_hex (char *buff, /* packet to parse */
1187 ULONGEST *result)
1188 {
1189 int nibble;
1190 ULONGEST retval = 0;
1191
1192 while (ishex (*buff, &nibble))
1193 {
1194 buff++;
1195 retval = retval << 4;
1196 retval |= nibble & 0x0f;
1197 }
1198 *result = retval;
1199 return buff;
1200 }
1201
1202 static char *
1203 unpack_nibble (char *buf, int *val)
1204 {
1205 ishex (*buf++, val);
1206 return buf;
1207 }
1208
1209 static char *
1210 pack_nibble (char *buf, int nibble)
1211 {
1212 *buf++ = hexchars[(nibble & 0x0f)];
1213 return buf;
1214 }
1215
1216 static char *
1217 pack_hex_byte (char *pkt, int byte)
1218 {
1219 *pkt++ = hexchars[(byte >> 4) & 0xf];
1220 *pkt++ = hexchars[(byte & 0xf)];
1221 return pkt;
1222 }
1223
1224 static char *
1225 unpack_byte (char *buf, int *value)
1226 {
1227 *value = stub_unpack_int (buf, 2);
1228 return buf + 2;
1229 }
1230
1231 static char *
1232 pack_int (char *buf, int value)
1233 {
1234 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1235 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1236 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1237 buf = pack_hex_byte (buf, (value & 0xff));
1238 return buf;
1239 }
1240
1241 static char *
1242 unpack_int (char *buf, int *value)
1243 {
1244 *value = stub_unpack_int (buf, 8);
1245 return buf + 8;
1246 }
1247
1248 #if 0 /* Currently unused, uncomment when needed. */
1249 static char *pack_string (char *pkt, char *string);
1250
1251 static char *
1252 pack_string (char *pkt, char *string)
1253 {
1254 char ch;
1255 int len;
1256
1257 len = strlen (string);
1258 if (len > 200)
1259 len = 200; /* Bigger than most GDB packets, junk??? */
1260 pkt = pack_hex_byte (pkt, len);
1261 while (len-- > 0)
1262 {
1263 ch = *string++;
1264 if ((ch == '\0') || (ch == '#'))
1265 ch = '*'; /* Protect encapsulation. */
1266 *pkt++ = ch;
1267 }
1268 return pkt;
1269 }
1270 #endif /* 0 (unused) */
1271
1272 static char *
1273 unpack_string (char *src, char *dest, int length)
1274 {
1275 while (length--)
1276 *dest++ = *src++;
1277 *dest = '\0';
1278 return src;
1279 }
1280
1281 static char *
1282 pack_threadid (char *pkt, threadref *id)
1283 {
1284 char *limit;
1285 unsigned char *altid;
1286
1287 altid = (unsigned char *) id;
1288 limit = pkt + BUF_THREAD_ID_SIZE;
1289 while (pkt < limit)
1290 pkt = pack_hex_byte (pkt, *altid++);
1291 return pkt;
1292 }
1293
1294
1295 static char *
1296 unpack_threadid (char *inbuf, threadref *id)
1297 {
1298 char *altref;
1299 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1300 int x, y;
1301
1302 altref = (char *) id;
1303
1304 while (inbuf < limit)
1305 {
1306 x = stubhex (*inbuf++);
1307 y = stubhex (*inbuf++);
1308 *altref++ = (x << 4) | y;
1309 }
1310 return inbuf;
1311 }
1312
1313 /* Externally, threadrefs are 64 bits but internally, they are still
1314 ints. This is due to a mismatch of specifications. We would like
1315 to use 64bit thread references internally. This is an adapter
1316 function. */
1317
1318 void
1319 int_to_threadref (threadref *id, int value)
1320 {
1321 unsigned char *scan;
1322
1323 scan = (unsigned char *) id;
1324 {
1325 int i = 4;
1326 while (i--)
1327 *scan++ = 0;
1328 }
1329 *scan++ = (value >> 24) & 0xff;
1330 *scan++ = (value >> 16) & 0xff;
1331 *scan++ = (value >> 8) & 0xff;
1332 *scan++ = (value & 0xff);
1333 }
1334
1335 static int
1336 threadref_to_int (threadref *ref)
1337 {
1338 int i, value = 0;
1339 unsigned char *scan;
1340
1341 scan = *ref;
1342 scan += 4;
1343 i = 4;
1344 while (i-- > 0)
1345 value = (value << 8) | ((*scan++) & 0xff);
1346 return value;
1347 }
1348
1349 static void
1350 copy_threadref (threadref *dest, threadref *src)
1351 {
1352 int i;
1353 unsigned char *csrc, *cdest;
1354
1355 csrc = (unsigned char *) src;
1356 cdest = (unsigned char *) dest;
1357 i = 8;
1358 while (i--)
1359 *cdest++ = *csrc++;
1360 }
1361
1362 static int
1363 threadmatch (threadref *dest, threadref *src)
1364 {
1365 /* Things are broken right now, so just assume we got a match. */
1366 #if 0
1367 unsigned char *srcp, *destp;
1368 int i, result;
1369 srcp = (char *) src;
1370 destp = (char *) dest;
1371
1372 result = 1;
1373 while (i-- > 0)
1374 result &= (*srcp++ == *destp++) ? 1 : 0;
1375 return result;
1376 #endif
1377 return 1;
1378 }
1379
1380 /*
1381 threadid:1, # always request threadid
1382 context_exists:2,
1383 display:4,
1384 unique_name:8,
1385 more_display:16
1386 */
1387
1388 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1389
1390 static char *
1391 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1392 {
1393 *pkt++ = 'q'; /* Info Query */
1394 *pkt++ = 'P'; /* process or thread info */
1395 pkt = pack_int (pkt, mode); /* mode */
1396 pkt = pack_threadid (pkt, id); /* threadid */
1397 *pkt = '\0'; /* terminate */
1398 return pkt;
1399 }
1400
1401 /* These values tag the fields in a thread info response packet. */
1402 /* Tagging the fields allows us to request specific fields and to
1403 add more fields as time goes by. */
1404
1405 #define TAG_THREADID 1 /* Echo the thread identifier. */
1406 #define TAG_EXISTS 2 /* Is this process defined enough to
1407 fetch registers and its stack? */
1408 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1409 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
1410 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1411 the process. */
1412
1413 static int
1414 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1415 struct gdb_ext_thread_info *info)
1416 {
1417 struct remote_state *rs = get_remote_state ();
1418 int mask, length;
1419 int tag;
1420 threadref ref;
1421 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
1422 int retval = 1;
1423
1424 /* info->threadid = 0; FIXME: implement zero_threadref. */
1425 info->active = 0;
1426 info->display[0] = '\0';
1427 info->shortname[0] = '\0';
1428 info->more_display[0] = '\0';
1429
1430 /* Assume the characters indicating the packet type have been
1431 stripped. */
1432 pkt = unpack_int (pkt, &mask); /* arg mask */
1433 pkt = unpack_threadid (pkt, &ref);
1434
1435 if (mask == 0)
1436 warning (_("Incomplete response to threadinfo request."));
1437 if (!threadmatch (&ref, expectedref))
1438 { /* This is an answer to a different request. */
1439 warning (_("ERROR RMT Thread info mismatch."));
1440 return 0;
1441 }
1442 copy_threadref (&info->threadid, &ref);
1443
1444 /* Loop on tagged fields , try to bail if somthing goes wrong. */
1445
1446 /* Packets are terminated with nulls. */
1447 while ((pkt < limit) && mask && *pkt)
1448 {
1449 pkt = unpack_int (pkt, &tag); /* tag */
1450 pkt = unpack_byte (pkt, &length); /* length */
1451 if (!(tag & mask)) /* Tags out of synch with mask. */
1452 {
1453 warning (_("ERROR RMT: threadinfo tag mismatch."));
1454 retval = 0;
1455 break;
1456 }
1457 if (tag == TAG_THREADID)
1458 {
1459 if (length != 16)
1460 {
1461 warning (_("ERROR RMT: length of threadid is not 16."));
1462 retval = 0;
1463 break;
1464 }
1465 pkt = unpack_threadid (pkt, &ref);
1466 mask = mask & ~TAG_THREADID;
1467 continue;
1468 }
1469 if (tag == TAG_EXISTS)
1470 {
1471 info->active = stub_unpack_int (pkt, length);
1472 pkt += length;
1473 mask = mask & ~(TAG_EXISTS);
1474 if (length > 8)
1475 {
1476 warning (_("ERROR RMT: 'exists' length too long."));
1477 retval = 0;
1478 break;
1479 }
1480 continue;
1481 }
1482 if (tag == TAG_THREADNAME)
1483 {
1484 pkt = unpack_string (pkt, &info->shortname[0], length);
1485 mask = mask & ~TAG_THREADNAME;
1486 continue;
1487 }
1488 if (tag == TAG_DISPLAY)
1489 {
1490 pkt = unpack_string (pkt, &info->display[0], length);
1491 mask = mask & ~TAG_DISPLAY;
1492 continue;
1493 }
1494 if (tag == TAG_MOREDISPLAY)
1495 {
1496 pkt = unpack_string (pkt, &info->more_display[0], length);
1497 mask = mask & ~TAG_MOREDISPLAY;
1498 continue;
1499 }
1500 warning (_("ERROR RMT: unknown thread info tag."));
1501 break; /* Not a tag we know about. */
1502 }
1503 return retval;
1504 }
1505
1506 static int
1507 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
1508 struct gdb_ext_thread_info *info)
1509 {
1510 struct remote_state *rs = get_remote_state ();
1511 int result;
1512
1513 pack_threadinfo_request (rs->buf, fieldset, threadid);
1514 putpkt (rs->buf);
1515 getpkt (&rs->buf, &rs->buf_size, 0);
1516 result = remote_unpack_thread_info_response (rs->buf + 2,
1517 threadid, info);
1518 return result;
1519 }
1520
1521 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1522
1523 static char *
1524 pack_threadlist_request (char *pkt, int startflag, int threadcount,
1525 threadref *nextthread)
1526 {
1527 *pkt++ = 'q'; /* info query packet */
1528 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1529 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1530 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1531 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1532 *pkt = '\0';
1533 return pkt;
1534 }
1535
1536 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1537
1538 static int
1539 parse_threadlist_response (char *pkt, int result_limit,
1540 threadref *original_echo, threadref *resultlist,
1541 int *doneflag)
1542 {
1543 struct remote_state *rs = get_remote_state ();
1544 char *limit;
1545 int count, resultcount, done;
1546
1547 resultcount = 0;
1548 /* Assume the 'q' and 'M chars have been stripped. */
1549 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
1550 /* done parse past here */
1551 pkt = unpack_byte (pkt, &count); /* count field */
1552 pkt = unpack_nibble (pkt, &done);
1553 /* The first threadid is the argument threadid. */
1554 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1555 while ((count-- > 0) && (pkt < limit))
1556 {
1557 pkt = unpack_threadid (pkt, resultlist++);
1558 if (resultcount++ >= result_limit)
1559 break;
1560 }
1561 if (doneflag)
1562 *doneflag = done;
1563 return resultcount;
1564 }
1565
1566 static int
1567 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1568 int *done, int *result_count, threadref *threadlist)
1569 {
1570 struct remote_state *rs = get_remote_state ();
1571 static threadref echo_nextthread;
1572 int result = 1;
1573
1574 /* Trancate result limit to be smaller than the packet size. */
1575 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1576 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
1577
1578 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1579 putpkt (rs->buf);
1580 getpkt (&rs->buf, &rs->buf_size, 0);
1581
1582 *result_count =
1583 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
1584 threadlist, done);
1585
1586 if (!threadmatch (&echo_nextthread, nextthread))
1587 {
1588 /* FIXME: This is a good reason to drop the packet. */
1589 /* Possably, there is a duplicate response. */
1590 /* Possabilities :
1591 retransmit immediatly - race conditions
1592 retransmit after timeout - yes
1593 exit
1594 wait for packet, then exit
1595 */
1596 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
1597 return 0; /* I choose simply exiting. */
1598 }
1599 if (*result_count <= 0)
1600 {
1601 if (*done != 1)
1602 {
1603 warning (_("RMT ERROR : failed to get remote thread list."));
1604 result = 0;
1605 }
1606 return result; /* break; */
1607 }
1608 if (*result_count > result_limit)
1609 {
1610 *result_count = 0;
1611 warning (_("RMT ERROR: threadlist response longer than requested."));
1612 return 0;
1613 }
1614 return result;
1615 }
1616
1617 /* This is the interface between remote and threads, remotes upper
1618 interface. */
1619
1620 /* remote_find_new_threads retrieves the thread list and for each
1621 thread in the list, looks up the thread in GDB's internal list,
1622 ading the thread if it does not already exist. This involves
1623 getting partial thread lists from the remote target so, polling the
1624 quit_flag is required. */
1625
1626
1627 /* About this many threadisds fit in a packet. */
1628
1629 #define MAXTHREADLISTRESULTS 32
1630
1631 static int
1632 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
1633 int looplimit)
1634 {
1635 int done, i, result_count;
1636 int startflag = 1;
1637 int result = 1;
1638 int loopcount = 0;
1639 static threadref nextthread;
1640 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1641
1642 done = 0;
1643 while (!done)
1644 {
1645 if (loopcount++ > looplimit)
1646 {
1647 result = 0;
1648 warning (_("Remote fetch threadlist -infinite loop-."));
1649 break;
1650 }
1651 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1652 &done, &result_count, resultthreadlist))
1653 {
1654 result = 0;
1655 break;
1656 }
1657 /* Clear for later iterations. */
1658 startflag = 0;
1659 /* Setup to resume next batch of thread references, set nextthread. */
1660 if (result_count >= 1)
1661 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1662 i = 0;
1663 while (result_count--)
1664 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1665 break;
1666 }
1667 return result;
1668 }
1669
1670 static int
1671 remote_newthread_step (threadref *ref, void *context)
1672 {
1673 ptid_t ptid;
1674
1675 ptid = pid_to_ptid (threadref_to_int (ref));
1676
1677 if (!in_thread_list (ptid))
1678 add_thread (ptid);
1679 return 1; /* continue iterator */
1680 }
1681
1682 #define CRAZY_MAX_THREADS 1000
1683
1684 static ptid_t
1685 remote_current_thread (ptid_t oldpid)
1686 {
1687 struct remote_state *rs = get_remote_state ();
1688
1689 putpkt ("qC");
1690 getpkt (&rs->buf, &rs->buf_size, 0);
1691 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
1692 /* Use strtoul here, so we'll correctly parse values whose highest
1693 bit is set. The protocol carries them as a simple series of
1694 hex digits; in the absence of a sign, strtol will see such
1695 values as positive numbers out of range for signed 'long', and
1696 return LONG_MAX to indicate an overflow. */
1697 return pid_to_ptid (strtoul (&rs->buf[2], NULL, 16));
1698 else
1699 return oldpid;
1700 }
1701
1702 /* Find new threads for info threads command.
1703 * Original version, using John Metzler's thread protocol.
1704 */
1705
1706 static void
1707 remote_find_new_threads (void)
1708 {
1709 remote_threadlist_iterator (remote_newthread_step, 0,
1710 CRAZY_MAX_THREADS);
1711 if (PIDGET (inferior_ptid) == MAGIC_NULL_PID) /* ack ack ack */
1712 inferior_ptid = remote_current_thread (inferior_ptid);
1713 }
1714
1715 /*
1716 * Find all threads for info threads command.
1717 * Uses new thread protocol contributed by Cisco.
1718 * Falls back and attempts to use the older method (above)
1719 * if the target doesn't respond to the new method.
1720 */
1721
1722 static void
1723 remote_threads_info (void)
1724 {
1725 struct remote_state *rs = get_remote_state ();
1726 char *bufp;
1727 int tid;
1728
1729 if (remote_desc == 0) /* paranoia */
1730 error (_("Command can only be used when connected to the remote target."));
1731
1732 if (use_threadinfo_query)
1733 {
1734 putpkt ("qfThreadInfo");
1735 getpkt (&rs->buf, &rs->buf_size, 0);
1736 bufp = rs->buf;
1737 if (bufp[0] != '\0') /* q packet recognized */
1738 {
1739 while (*bufp++ == 'm') /* reply contains one or more TID */
1740 {
1741 do
1742 {
1743 /* Use strtoul here, so we'll correctly parse values
1744 whose highest bit is set. The protocol carries
1745 them as a simple series of hex digits; in the
1746 absence of a sign, strtol will see such values as
1747 positive numbers out of range for signed 'long',
1748 and return LONG_MAX to indicate an overflow. */
1749 tid = strtoul (bufp, &bufp, 16);
1750 if (tid != 0 && !in_thread_list (pid_to_ptid (tid)))
1751 add_thread (pid_to_ptid (tid));
1752 }
1753 while (*bufp++ == ','); /* comma-separated list */
1754 putpkt ("qsThreadInfo");
1755 getpkt (&rs->buf, &rs->buf_size, 0);
1756 bufp = rs->buf;
1757 }
1758 return; /* done */
1759 }
1760 }
1761
1762 /* Else fall back to old method based on jmetzler protocol. */
1763 use_threadinfo_query = 0;
1764 remote_find_new_threads ();
1765 return;
1766 }
1767
1768 /*
1769 * Collect a descriptive string about the given thread.
1770 * The target may say anything it wants to about the thread
1771 * (typically info about its blocked / runnable state, name, etc.).
1772 * This string will appear in the info threads display.
1773 *
1774 * Optional: targets are not required to implement this function.
1775 */
1776
1777 static char *
1778 remote_threads_extra_info (struct thread_info *tp)
1779 {
1780 struct remote_state *rs = get_remote_state ();
1781 int result;
1782 int set;
1783 threadref id;
1784 struct gdb_ext_thread_info threadinfo;
1785 static char display_buf[100]; /* arbitrary... */
1786 int n = 0; /* position in display_buf */
1787
1788 if (remote_desc == 0) /* paranoia */
1789 internal_error (__FILE__, __LINE__,
1790 _("remote_threads_extra_info"));
1791
1792 if (use_threadextra_query)
1793 {
1794 xsnprintf (rs->buf, get_remote_packet_size (), "qThreadExtraInfo,%x",
1795 PIDGET (tp->ptid));
1796 putpkt (rs->buf);
1797 getpkt (&rs->buf, &rs->buf_size, 0);
1798 if (rs->buf[0] != 0)
1799 {
1800 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
1801 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
1802 display_buf [result] = '\0';
1803 return display_buf;
1804 }
1805 }
1806
1807 /* If the above query fails, fall back to the old method. */
1808 use_threadextra_query = 0;
1809 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
1810 | TAG_MOREDISPLAY | TAG_DISPLAY;
1811 int_to_threadref (&id, PIDGET (tp->ptid));
1812 if (remote_get_threadinfo (&id, set, &threadinfo))
1813 if (threadinfo.active)
1814 {
1815 if (*threadinfo.shortname)
1816 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
1817 " Name: %s,", threadinfo.shortname);
1818 if (*threadinfo.display)
1819 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
1820 " State: %s,", threadinfo.display);
1821 if (*threadinfo.more_display)
1822 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
1823 " Priority: %s", threadinfo.more_display);
1824
1825 if (n > 0)
1826 {
1827 /* For purely cosmetic reasons, clear up trailing commas. */
1828 if (',' == display_buf[n-1])
1829 display_buf[n-1] = ' ';
1830 return display_buf;
1831 }
1832 }
1833 return NULL;
1834 }
1835 \f
1836
1837 /* Restart the remote side; this is an extended protocol operation. */
1838
1839 static void
1840 extended_remote_restart (void)
1841 {
1842 struct remote_state *rs = get_remote_state ();
1843
1844 /* Send the restart command; for reasons I don't understand the
1845 remote side really expects a number after the "R". */
1846 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
1847 putpkt (rs->buf);
1848
1849 remote_fileio_reset ();
1850
1851 /* Now query for status so this looks just like we restarted
1852 gdbserver from scratch. */
1853 putpkt ("?");
1854 getpkt (&rs->buf, &rs->buf_size, 0);
1855 }
1856 \f
1857 /* Clean up connection to a remote debugger. */
1858
1859 static void
1860 remote_close (int quitting)
1861 {
1862 if (remote_desc)
1863 serial_close (remote_desc);
1864 remote_desc = NULL;
1865 }
1866
1867 /* Query the remote side for the text, data and bss offsets. */
1868
1869 static void
1870 get_offsets (void)
1871 {
1872 struct remote_state *rs = get_remote_state ();
1873 char *buf;
1874 char *ptr;
1875 int lose;
1876 CORE_ADDR text_addr, data_addr, bss_addr;
1877 struct section_offsets *offs;
1878
1879 putpkt ("qOffsets");
1880 getpkt (&rs->buf, &rs->buf_size, 0);
1881 buf = rs->buf;
1882
1883 if (buf[0] == '\000')
1884 return; /* Return silently. Stub doesn't support
1885 this command. */
1886 if (buf[0] == 'E')
1887 {
1888 warning (_("Remote failure reply: %s"), buf);
1889 return;
1890 }
1891
1892 /* Pick up each field in turn. This used to be done with scanf, but
1893 scanf will make trouble if CORE_ADDR size doesn't match
1894 conversion directives correctly. The following code will work
1895 with any size of CORE_ADDR. */
1896 text_addr = data_addr = bss_addr = 0;
1897 ptr = buf;
1898 lose = 0;
1899
1900 if (strncmp (ptr, "Text=", 5) == 0)
1901 {
1902 ptr += 5;
1903 /* Don't use strtol, could lose on big values. */
1904 while (*ptr && *ptr != ';')
1905 text_addr = (text_addr << 4) + fromhex (*ptr++);
1906 }
1907 else
1908 lose = 1;
1909
1910 if (!lose && strncmp (ptr, ";Data=", 6) == 0)
1911 {
1912 ptr += 6;
1913 while (*ptr && *ptr != ';')
1914 data_addr = (data_addr << 4) + fromhex (*ptr++);
1915 }
1916 else
1917 lose = 1;
1918
1919 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
1920 {
1921 ptr += 5;
1922 while (*ptr && *ptr != ';')
1923 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
1924 }
1925 else
1926 lose = 1;
1927
1928 if (lose)
1929 error (_("Malformed response to offset query, %s"), buf);
1930
1931 if (symfile_objfile == NULL)
1932 return;
1933
1934 offs = ((struct section_offsets *)
1935 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
1936 memcpy (offs, symfile_objfile->section_offsets,
1937 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
1938
1939 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
1940
1941 /* This is a temporary kludge to force data and bss to use the same offsets
1942 because that's what nlmconv does now. The real solution requires changes
1943 to the stub and remote.c that I don't have time to do right now. */
1944
1945 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
1946 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
1947
1948 objfile_relocate (symfile_objfile, offs);
1949 }
1950
1951 /* Stub for catch_errors. */
1952
1953 static int
1954 remote_start_remote_dummy (struct ui_out *uiout, void *dummy)
1955 {
1956 start_remote (); /* Initialize gdb process mechanisms. */
1957 /* NOTE: Return something >=0. A -ve value is reserved for
1958 catch_exceptions. */
1959 return 1;
1960 }
1961
1962 static void
1963 remote_start_remote (struct ui_out *uiout, void *dummy)
1964 {
1965 immediate_quit++; /* Allow user to interrupt it. */
1966
1967 /* Ack any packet which the remote side has already sent. */
1968 serial_write (remote_desc, "+", 1);
1969
1970 /* Let the stub know that we want it to return the thread. */
1971 set_thread (-1, 0);
1972
1973 inferior_ptid = remote_current_thread (inferior_ptid);
1974
1975 get_offsets (); /* Get text, data & bss offsets. */
1976
1977 putpkt ("?"); /* Initiate a query from remote machine. */
1978 immediate_quit--;
1979
1980 remote_start_remote_dummy (uiout, dummy);
1981 }
1982
1983 /* Open a connection to a remote debugger.
1984 NAME is the filename used for communication. */
1985
1986 static void
1987 remote_open (char *name, int from_tty)
1988 {
1989 remote_open_1 (name, from_tty, &remote_ops, 0, 0);
1990 }
1991
1992 /* Just like remote_open, but with asynchronous support. */
1993 static void
1994 remote_async_open (char *name, int from_tty)
1995 {
1996 remote_open_1 (name, from_tty, &remote_async_ops, 0, 1);
1997 }
1998
1999 /* Open a connection to a remote debugger using the extended
2000 remote gdb protocol. NAME is the filename used for communication. */
2001
2002 static void
2003 extended_remote_open (char *name, int from_tty)
2004 {
2005 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */,
2006 0 /* async_p */);
2007 }
2008
2009 /* Just like extended_remote_open, but with asynchronous support. */
2010 static void
2011 extended_remote_async_open (char *name, int from_tty)
2012 {
2013 remote_open_1 (name, from_tty, &extended_async_remote_ops,
2014 1 /*extended_p */, 1 /* async_p */);
2015 }
2016
2017 /* Generic code for opening a connection to a remote target. */
2018
2019 static void
2020 init_all_packet_configs (void)
2021 {
2022 int i;
2023 for (i = 0; i < PACKET_MAX; i++)
2024 update_packet_config (&remote_protocol_packets[i]);
2025 }
2026
2027 /* Symbol look-up. */
2028
2029 static void
2030 remote_check_symbols (struct objfile *objfile)
2031 {
2032 struct remote_state *rs = get_remote_state ();
2033 char *msg, *reply, *tmp;
2034 struct minimal_symbol *sym;
2035 int end;
2036
2037 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2038 return;
2039
2040 /* Allocate a message buffer. We can't reuse the input buffer in RS,
2041 because we need both at the same time. */
2042 msg = alloca (get_remote_packet_size ());
2043
2044 /* Invite target to request symbol lookups. */
2045
2046 putpkt ("qSymbol::");
2047 getpkt (&rs->buf, &rs->buf_size, 0);
2048 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2049 reply = rs->buf;
2050
2051 while (strncmp (reply, "qSymbol:", 8) == 0)
2052 {
2053 tmp = &reply[8];
2054 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2055 msg[end] = '\0';
2056 sym = lookup_minimal_symbol (msg, NULL, NULL);
2057 if (sym == NULL)
2058 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2059 else
2060 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2061 paddr_nz (SYMBOL_VALUE_ADDRESS (sym)),
2062 &reply[8]);
2063 putpkt (msg);
2064 getpkt (&rs->buf, &rs->buf_size, 0);
2065 reply = rs->buf;
2066 }
2067 }
2068
2069 static struct serial *
2070 remote_serial_open (char *name)
2071 {
2072 static int udp_warning = 0;
2073
2074 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
2075 of in ser-tcp.c, because it is the remote protocol assuming that the
2076 serial connection is reliable and not the serial connection promising
2077 to be. */
2078 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2079 {
2080 warning (_("\
2081 The remote protocol may be unreliable over UDP.\n\
2082 Some events may be lost, rendering further debugging impossible."));
2083 udp_warning = 1;
2084 }
2085
2086 return serial_open (name);
2087 }
2088
2089 /* This type describes each known response to the qSupported
2090 packet. */
2091 struct protocol_feature
2092 {
2093 /* The name of this protocol feature. */
2094 const char *name;
2095
2096 /* The default for this protocol feature. */
2097 enum packet_support default_support;
2098
2099 /* The function to call when this feature is reported, or after
2100 qSupported processing if the feature is not supported.
2101 The first argument points to this structure. The second
2102 argument indicates whether the packet requested support be
2103 enabled, disabled, or probed (or the default, if this function
2104 is being called at the end of processing and this feature was
2105 not reported). The third argument may be NULL; if not NULL, it
2106 is a NUL-terminated string taken from the packet following
2107 this feature's name and an equals sign. */
2108 void (*func) (const struct protocol_feature *, enum packet_support,
2109 const char *);
2110
2111 /* The corresponding packet for this feature. Only used if
2112 FUNC is remote_supported_packet. */
2113 int packet;
2114 };
2115
2116 static void
2117 remote_supported_packet (const struct protocol_feature *feature,
2118 enum packet_support support,
2119 const char *argument)
2120 {
2121 if (argument)
2122 {
2123 warning (_("Remote qSupported response supplied an unexpected value for"
2124 " \"%s\"."), feature->name);
2125 return;
2126 }
2127
2128 if (remote_protocol_packets[feature->packet].support
2129 == PACKET_SUPPORT_UNKNOWN)
2130 remote_protocol_packets[feature->packet].support = support;
2131 }
2132
2133 static void
2134 remote_packet_size (const struct protocol_feature *feature,
2135 enum packet_support support, const char *value)
2136 {
2137 struct remote_state *rs = get_remote_state ();
2138
2139 int packet_size;
2140 char *value_end;
2141
2142 if (support != PACKET_ENABLE)
2143 return;
2144
2145 if (value == NULL || *value == '\0')
2146 {
2147 warning (_("Remote target reported \"%s\" without a size."),
2148 feature->name);
2149 return;
2150 }
2151
2152 errno = 0;
2153 packet_size = strtol (value, &value_end, 16);
2154 if (errno != 0 || *value_end != '\0' || packet_size < 0)
2155 {
2156 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2157 feature->name, value);
2158 return;
2159 }
2160
2161 if (packet_size > MAX_REMOTE_PACKET_SIZE)
2162 {
2163 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2164 packet_size, MAX_REMOTE_PACKET_SIZE);
2165 packet_size = MAX_REMOTE_PACKET_SIZE;
2166 }
2167
2168 /* Record the new maximum packet size. */
2169 rs->explicit_packet_size = packet_size;
2170 }
2171
2172 static struct protocol_feature remote_protocol_features[] = {
2173 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
2174 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
2175 PACKET_qXfer_auxv }
2176 };
2177
2178 static void
2179 remote_query_supported (void)
2180 {
2181 struct remote_state *rs = get_remote_state ();
2182 char *next;
2183 int i;
2184 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
2185
2186 /* The packet support flags are handled differently for this packet
2187 than for most others. We treat an error, a disabled packet, and
2188 an empty response identically: any features which must be reported
2189 to be used will be automatically disabled. An empty buffer
2190 accomplishes this, since that is also the representation for a list
2191 containing no features. */
2192
2193 rs->buf[0] = 0;
2194 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
2195 {
2196 putpkt ("qSupported");
2197 getpkt (&rs->buf, &rs->buf_size, 0);
2198
2199 /* If an error occured, warn, but do not return - just reset the
2200 buffer to empty and go on to disable features. */
2201 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
2202 == PACKET_ERROR)
2203 {
2204 warning (_("Remote failure reply: %s"), rs->buf);
2205 rs->buf[0] = 0;
2206 }
2207 }
2208
2209 memset (seen, 0, sizeof (seen));
2210
2211 next = rs->buf;
2212 while (*next)
2213 {
2214 enum packet_support is_supported;
2215 char *p, *end, *name_end, *value;
2216
2217 /* First separate out this item from the rest of the packet. If
2218 there's another item after this, we overwrite the separator
2219 (terminated strings are much easier to work with). */
2220 p = next;
2221 end = strchr (p, ';');
2222 if (end == NULL)
2223 {
2224 end = p + strlen (p);
2225 next = end;
2226 }
2227 else
2228 {
2229 if (end == p)
2230 {
2231 warning (_("empty item in \"qSupported\" response"));
2232 continue;
2233 }
2234
2235 *end = '\0';
2236 next = end + 1;
2237 }
2238
2239 name_end = strchr (p, '=');
2240 if (name_end)
2241 {
2242 /* This is a name=value entry. */
2243 is_supported = PACKET_ENABLE;
2244 value = name_end + 1;
2245 *name_end = '\0';
2246 }
2247 else
2248 {
2249 value = NULL;
2250 switch (end[-1])
2251 {
2252 case '+':
2253 is_supported = PACKET_ENABLE;
2254 break;
2255
2256 case '-':
2257 is_supported = PACKET_DISABLE;
2258 break;
2259
2260 case '?':
2261 is_supported = PACKET_SUPPORT_UNKNOWN;
2262 break;
2263
2264 default:
2265 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
2266 continue;
2267 }
2268 end[-1] = '\0';
2269 }
2270
2271 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2272 if (strcmp (remote_protocol_features[i].name, p) == 0)
2273 {
2274 const struct protocol_feature *feature;
2275
2276 seen[i] = 1;
2277 feature = &remote_protocol_features[i];
2278 feature->func (feature, is_supported, value);
2279 break;
2280 }
2281 }
2282
2283 /* If we increased the packet size, make sure to increase the global
2284 buffer size also. We delay this until after parsing the entire
2285 qSupported packet, because this is the same buffer we were
2286 parsing. */
2287 if (rs->buf_size < rs->explicit_packet_size)
2288 {
2289 rs->buf_size = rs->explicit_packet_size;
2290 rs->buf = xrealloc (rs->buf, rs->buf_size);
2291 }
2292
2293 /* Handle the defaults for unmentioned features. */
2294 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2295 if (!seen[i])
2296 {
2297 const struct protocol_feature *feature;
2298
2299 feature = &remote_protocol_features[i];
2300 feature->func (feature, feature->default_support, NULL);
2301 }
2302 }
2303
2304
2305 static void
2306 remote_open_1 (char *name, int from_tty, struct target_ops *target,
2307 int extended_p, int async_p)
2308 {
2309 struct remote_state *rs = get_remote_state ();
2310 if (name == 0)
2311 error (_("To open a remote debug connection, you need to specify what\n"
2312 "serial device is attached to the remote system\n"
2313 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
2314
2315 /* See FIXME above. */
2316 if (!async_p)
2317 wait_forever_enabled_p = 1;
2318
2319 target_preopen (from_tty);
2320
2321 unpush_target (target);
2322
2323 remote_fileio_reset ();
2324 reopen_exec_file ();
2325 reread_symbols ();
2326
2327 remote_desc = remote_serial_open (name);
2328 if (!remote_desc)
2329 perror_with_name (name);
2330
2331 if (baud_rate != -1)
2332 {
2333 if (serial_setbaudrate (remote_desc, baud_rate))
2334 {
2335 /* The requested speed could not be set. Error out to
2336 top level after closing remote_desc. Take care to
2337 set remote_desc to NULL to avoid closing remote_desc
2338 more than once. */
2339 serial_close (remote_desc);
2340 remote_desc = NULL;
2341 perror_with_name (name);
2342 }
2343 }
2344
2345 serial_raw (remote_desc);
2346
2347 /* If there is something sitting in the buffer we might take it as a
2348 response to a command, which would be bad. */
2349 serial_flush_input (remote_desc);
2350
2351 if (from_tty)
2352 {
2353 puts_filtered ("Remote debugging using ");
2354 puts_filtered (name);
2355 puts_filtered ("\n");
2356 }
2357 push_target (target); /* Switch to using remote target now. */
2358
2359 /* Reset the target state; these things will be queried either by
2360 remote_query_supported or as they are needed. */
2361 init_all_packet_configs ();
2362 rs->explicit_packet_size = 0;
2363
2364 general_thread = -2;
2365 continue_thread = -2;
2366
2367 /* Probe for ability to use "ThreadInfo" query, as required. */
2368 use_threadinfo_query = 1;
2369 use_threadextra_query = 1;
2370
2371 /* The first packet we send to the target is the optional "supported
2372 packets" request. If the target can answer this, it will tell us
2373 which later probes to skip. */
2374 remote_query_supported ();
2375
2376 /* Without this, some commands which require an active target (such
2377 as kill) won't work. This variable serves (at least) double duty
2378 as both the pid of the target process (if it has such), and as a
2379 flag indicating that a target is active. These functions should
2380 be split out into seperate variables, especially since GDB will
2381 someday have a notion of debugging several processes. */
2382
2383 inferior_ptid = pid_to_ptid (MAGIC_NULL_PID);
2384
2385 if (async_p)
2386 {
2387 /* With this target we start out by owning the terminal. */
2388 remote_async_terminal_ours_p = 1;
2389
2390 /* FIXME: cagney/1999-09-23: During the initial connection it is
2391 assumed that the target is already ready and able to respond to
2392 requests. Unfortunately remote_start_remote() eventually calls
2393 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
2394 around this. Eventually a mechanism that allows
2395 wait_for_inferior() to expect/get timeouts will be
2396 implemented. */
2397 wait_forever_enabled_p = 0;
2398 }
2399
2400 /* First delete any symbols previously loaded from shared libraries. */
2401 no_shared_libraries (NULL, 0);
2402
2403 /* Start the remote connection. If error() or QUIT, discard this
2404 target (we'd otherwise be in an inconsistent state) and then
2405 propogate the error on up the exception chain. This ensures that
2406 the caller doesn't stumble along blindly assuming that the
2407 function succeeded. The CLI doesn't have this problem but other
2408 UI's, such as MI do.
2409
2410 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
2411 this function should return an error indication letting the
2412 caller restore the previous state. Unfortunately the command
2413 ``target remote'' is directly wired to this function making that
2414 impossible. On a positive note, the CLI side of this problem has
2415 been fixed - the function set_cmd_context() makes it possible for
2416 all the ``target ....'' commands to share a common callback
2417 function. See cli-dump.c. */
2418 {
2419 struct gdb_exception ex
2420 = catch_exception (uiout, remote_start_remote, NULL, RETURN_MASK_ALL);
2421 if (ex.reason < 0)
2422 {
2423 pop_target ();
2424 if (async_p)
2425 wait_forever_enabled_p = 1;
2426 throw_exception (ex);
2427 }
2428 }
2429
2430 if (async_p)
2431 wait_forever_enabled_p = 1;
2432
2433 if (extended_p)
2434 {
2435 /* Tell the remote that we are using the extended protocol. */
2436 putpkt ("!");
2437 getpkt (&rs->buf, &rs->buf_size, 0);
2438 }
2439
2440 post_create_inferior (&current_target, from_tty);
2441
2442 if (exec_bfd) /* No use without an exec file. */
2443 remote_check_symbols (symfile_objfile);
2444 }
2445
2446 /* This takes a program previously attached to and detaches it. After
2447 this is done, GDB can be used to debug some other program. We
2448 better not have left any breakpoints in the target program or it'll
2449 die when it hits one. */
2450
2451 static void
2452 remote_detach (char *args, int from_tty)
2453 {
2454 struct remote_state *rs = get_remote_state ();
2455
2456 if (args)
2457 error (_("Argument given to \"detach\" when remotely debugging."));
2458
2459 /* Tell the remote target to detach. */
2460 strcpy (rs->buf, "D");
2461 remote_send (&rs->buf, &rs->buf_size);
2462
2463 /* Unregister the file descriptor from the event loop. */
2464 if (target_is_async_p ())
2465 serial_async (remote_desc, NULL, 0);
2466
2467 target_mourn_inferior ();
2468 if (from_tty)
2469 puts_filtered ("Ending remote debugging.\n");
2470 }
2471
2472 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
2473
2474 static void
2475 remote_disconnect (struct target_ops *target, char *args, int from_tty)
2476 {
2477 if (args)
2478 error (_("Argument given to \"detach\" when remotely debugging."));
2479
2480 /* Unregister the file descriptor from the event loop. */
2481 if (target_is_async_p ())
2482 serial_async (remote_desc, NULL, 0);
2483
2484 target_mourn_inferior ();
2485 if (from_tty)
2486 puts_filtered ("Ending remote debugging.\n");
2487 }
2488
2489 /* Convert hex digit A to a number. */
2490
2491 static int
2492 fromhex (int a)
2493 {
2494 if (a >= '0' && a <= '9')
2495 return a - '0';
2496 else if (a >= 'a' && a <= 'f')
2497 return a - 'a' + 10;
2498 else if (a >= 'A' && a <= 'F')
2499 return a - 'A' + 10;
2500 else
2501 error (_("Reply contains invalid hex digit %d"), a);
2502 }
2503
2504 static int
2505 hex2bin (const char *hex, gdb_byte *bin, int count)
2506 {
2507 int i;
2508
2509 for (i = 0; i < count; i++)
2510 {
2511 if (hex[0] == 0 || hex[1] == 0)
2512 {
2513 /* Hex string is short, or of uneven length.
2514 Return the count that has been converted so far. */
2515 return i;
2516 }
2517 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
2518 hex += 2;
2519 }
2520 return i;
2521 }
2522
2523 /* Convert number NIB to a hex digit. */
2524
2525 static int
2526 tohex (int nib)
2527 {
2528 if (nib < 10)
2529 return '0' + nib;
2530 else
2531 return 'a' + nib - 10;
2532 }
2533
2534 static int
2535 bin2hex (const gdb_byte *bin, char *hex, int count)
2536 {
2537 int i;
2538 /* May use a length, or a nul-terminated string as input. */
2539 if (count == 0)
2540 count = strlen ((char *) bin);
2541
2542 for (i = 0; i < count; i++)
2543 {
2544 *hex++ = tohex ((*bin >> 4) & 0xf);
2545 *hex++ = tohex (*bin++ & 0xf);
2546 }
2547 *hex = 0;
2548 return i;
2549 }
2550 \f
2551 /* Check for the availability of vCont. This function should also check
2552 the response. */
2553
2554 static void
2555 remote_vcont_probe (struct remote_state *rs)
2556 {
2557 char *buf;
2558
2559 strcpy (rs->buf, "vCont?");
2560 putpkt (rs->buf);
2561 getpkt (&rs->buf, &rs->buf_size, 0);
2562 buf = rs->buf;
2563
2564 /* Make sure that the features we assume are supported. */
2565 if (strncmp (buf, "vCont", 5) == 0)
2566 {
2567 char *p = &buf[5];
2568 int support_s, support_S, support_c, support_C;
2569
2570 support_s = 0;
2571 support_S = 0;
2572 support_c = 0;
2573 support_C = 0;
2574 while (p && *p == ';')
2575 {
2576 p++;
2577 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
2578 support_s = 1;
2579 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
2580 support_S = 1;
2581 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
2582 support_c = 1;
2583 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
2584 support_C = 1;
2585
2586 p = strchr (p, ';');
2587 }
2588
2589 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
2590 BUF will make packet_ok disable the packet. */
2591 if (!support_s || !support_S || !support_c || !support_C)
2592 buf[0] = 0;
2593 }
2594
2595 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
2596 }
2597
2598 /* Resume the remote inferior by using a "vCont" packet. The thread
2599 to be resumed is PTID; STEP and SIGGNAL indicate whether the
2600 resumed thread should be single-stepped and/or signalled. If PTID's
2601 PID is -1, then all threads are resumed; the thread to be stepped and/or
2602 signalled is given in the global INFERIOR_PTID. This function returns
2603 non-zero iff it resumes the inferior.
2604
2605 This function issues a strict subset of all possible vCont commands at the
2606 moment. */
2607
2608 static int
2609 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
2610 {
2611 struct remote_state *rs = get_remote_state ();
2612 int pid = PIDGET (ptid);
2613 char *buf = NULL, *outbuf;
2614 struct cleanup *old_cleanup;
2615
2616 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
2617 remote_vcont_probe (rs);
2618
2619 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
2620 return 0;
2621
2622 /* If we could generate a wider range of packets, we'd have to worry
2623 about overflowing BUF. Should there be a generic
2624 "multi-part-packet" packet? */
2625
2626 if (PIDGET (inferior_ptid) == MAGIC_NULL_PID)
2627 {
2628 /* MAGIC_NULL_PTID means that we don't have any active threads, so we
2629 don't have any PID numbers the inferior will understand. Make sure
2630 to only send forms that do not specify a PID. */
2631 if (step && siggnal != TARGET_SIGNAL_0)
2632 outbuf = xstrprintf ("vCont;S%02x", siggnal);
2633 else if (step)
2634 outbuf = xstrprintf ("vCont;s");
2635 else if (siggnal != TARGET_SIGNAL_0)
2636 outbuf = xstrprintf ("vCont;C%02x", siggnal);
2637 else
2638 outbuf = xstrprintf ("vCont;c");
2639 }
2640 else if (pid == -1)
2641 {
2642 /* Resume all threads, with preference for INFERIOR_PTID. */
2643 if (step && siggnal != TARGET_SIGNAL_0)
2644 outbuf = xstrprintf ("vCont;S%02x:%x;c", siggnal,
2645 PIDGET (inferior_ptid));
2646 else if (step)
2647 outbuf = xstrprintf ("vCont;s:%x;c", PIDGET (inferior_ptid));
2648 else if (siggnal != TARGET_SIGNAL_0)
2649 outbuf = xstrprintf ("vCont;C%02x:%x;c", siggnal,
2650 PIDGET (inferior_ptid));
2651 else
2652 outbuf = xstrprintf ("vCont;c");
2653 }
2654 else
2655 {
2656 /* Scheduler locking; resume only PTID. */
2657 if (step && siggnal != TARGET_SIGNAL_0)
2658 outbuf = xstrprintf ("vCont;S%02x:%x", siggnal, pid);
2659 else if (step)
2660 outbuf = xstrprintf ("vCont;s:%x", pid);
2661 else if (siggnal != TARGET_SIGNAL_0)
2662 outbuf = xstrprintf ("vCont;C%02x:%x", siggnal, pid);
2663 else
2664 outbuf = xstrprintf ("vCont;c:%x", pid);
2665 }
2666
2667 gdb_assert (outbuf && strlen (outbuf) < get_remote_packet_size ());
2668 old_cleanup = make_cleanup (xfree, outbuf);
2669
2670 putpkt (outbuf);
2671
2672 do_cleanups (old_cleanup);
2673
2674 return 1;
2675 }
2676
2677 /* Tell the remote machine to resume. */
2678
2679 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
2680
2681 static int last_sent_step;
2682
2683 static void
2684 remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
2685 {
2686 struct remote_state *rs = get_remote_state ();
2687 char *buf;
2688 int pid = PIDGET (ptid);
2689
2690 last_sent_signal = siggnal;
2691 last_sent_step = step;
2692
2693 /* A hook for when we need to do something at the last moment before
2694 resumption. */
2695 if (deprecated_target_resume_hook)
2696 (*deprecated_target_resume_hook) ();
2697
2698 /* The vCont packet doesn't need to specify threads via Hc. */
2699 if (remote_vcont_resume (ptid, step, siggnal))
2700 return;
2701
2702 /* All other supported resume packets do use Hc, so call set_thread. */
2703 if (pid == -1)
2704 set_thread (0, 0); /* Run any thread. */
2705 else
2706 set_thread (pid, 0); /* Run this thread. */
2707
2708 buf = rs->buf;
2709 if (siggnal != TARGET_SIGNAL_0)
2710 {
2711 buf[0] = step ? 'S' : 'C';
2712 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
2713 buf[2] = tohex (((int) siggnal) & 0xf);
2714 buf[3] = '\0';
2715 }
2716 else
2717 strcpy (buf, step ? "s" : "c");
2718
2719 putpkt (buf);
2720 }
2721
2722 /* Same as remote_resume, but with async support. */
2723 static void
2724 remote_async_resume (ptid_t ptid, int step, enum target_signal siggnal)
2725 {
2726 remote_resume (ptid, step, siggnal);
2727
2728 /* We are about to start executing the inferior, let's register it
2729 with the event loop. NOTE: this is the one place where all the
2730 execution commands end up. We could alternatively do this in each
2731 of the execution commands in infcmd.c. */
2732 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
2733 into infcmd.c in order to allow inferior function calls to work
2734 NOT asynchronously. */
2735 if (target_can_async_p ())
2736 target_async (inferior_event_handler, 0);
2737 /* Tell the world that the target is now executing. */
2738 /* FIXME: cagney/1999-09-23: Is it the targets responsibility to set
2739 this? Instead, should the client of target just assume (for
2740 async targets) that the target is going to start executing? Is
2741 this information already found in the continuation block? */
2742 if (target_is_async_p ())
2743 target_executing = 1;
2744 }
2745 \f
2746
2747 /* Set up the signal handler for SIGINT, while the target is
2748 executing, ovewriting the 'regular' SIGINT signal handler. */
2749 static void
2750 initialize_sigint_signal_handler (void)
2751 {
2752 sigint_remote_token =
2753 create_async_signal_handler (async_remote_interrupt, NULL);
2754 signal (SIGINT, handle_remote_sigint);
2755 }
2756
2757 /* Signal handler for SIGINT, while the target is executing. */
2758 static void
2759 handle_remote_sigint (int sig)
2760 {
2761 signal (sig, handle_remote_sigint_twice);
2762 sigint_remote_twice_token =
2763 create_async_signal_handler (async_remote_interrupt_twice, NULL);
2764 mark_async_signal_handler_wrapper (sigint_remote_token);
2765 }
2766
2767 /* Signal handler for SIGINT, installed after SIGINT has already been
2768 sent once. It will take effect the second time that the user sends
2769 a ^C. */
2770 static void
2771 handle_remote_sigint_twice (int sig)
2772 {
2773 signal (sig, handle_sigint);
2774 sigint_remote_twice_token =
2775 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
2776 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
2777 }
2778
2779 /* Perform the real interruption of the target execution, in response
2780 to a ^C. */
2781 static void
2782 async_remote_interrupt (gdb_client_data arg)
2783 {
2784 if (remote_debug)
2785 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
2786
2787 target_stop ();
2788 }
2789
2790 /* Perform interrupt, if the first attempt did not succeed. Just give
2791 up on the target alltogether. */
2792 void
2793 async_remote_interrupt_twice (gdb_client_data arg)
2794 {
2795 if (remote_debug)
2796 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
2797 /* Do something only if the target was not killed by the previous
2798 cntl-C. */
2799 if (target_executing)
2800 {
2801 interrupt_query ();
2802 signal (SIGINT, handle_remote_sigint);
2803 }
2804 }
2805
2806 /* Reinstall the usual SIGINT handlers, after the target has
2807 stopped. */
2808 static void
2809 cleanup_sigint_signal_handler (void *dummy)
2810 {
2811 signal (SIGINT, handle_sigint);
2812 if (sigint_remote_twice_token)
2813 delete_async_signal_handler ((struct async_signal_handler **)
2814 &sigint_remote_twice_token);
2815 if (sigint_remote_token)
2816 delete_async_signal_handler ((struct async_signal_handler **)
2817 &sigint_remote_token);
2818 }
2819
2820 /* Send ^C to target to halt it. Target will respond, and send us a
2821 packet. */
2822 static void (*ofunc) (int);
2823
2824 /* The command line interface's stop routine. This function is installed
2825 as a signal handler for SIGINT. The first time a user requests a
2826 stop, we call remote_stop to send a break or ^C. If there is no
2827 response from the target (it didn't stop when the user requested it),
2828 we ask the user if he'd like to detach from the target. */
2829 static void
2830 remote_interrupt (int signo)
2831 {
2832 /* If this doesn't work, try more severe steps. */
2833 signal (signo, remote_interrupt_twice);
2834
2835 if (remote_debug)
2836 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
2837
2838 target_stop ();
2839 }
2840
2841 /* The user typed ^C twice. */
2842
2843 static void
2844 remote_interrupt_twice (int signo)
2845 {
2846 signal (signo, ofunc);
2847 interrupt_query ();
2848 signal (signo, remote_interrupt);
2849 }
2850
2851 /* This is the generic stop called via the target vector. When a target
2852 interrupt is requested, either by the command line or the GUI, we
2853 will eventually end up here. */
2854 static void
2855 remote_stop (void)
2856 {
2857 /* Send a break or a ^C, depending on user preference. */
2858 if (remote_debug)
2859 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
2860
2861 if (remote_break)
2862 serial_send_break (remote_desc);
2863 else
2864 serial_write (remote_desc, "\003", 1);
2865 }
2866
2867 /* Ask the user what to do when an interrupt is received. */
2868
2869 static void
2870 interrupt_query (void)
2871 {
2872 target_terminal_ours ();
2873
2874 if (query ("Interrupted while waiting for the program.\n\
2875 Give up (and stop debugging it)? "))
2876 {
2877 target_mourn_inferior ();
2878 deprecated_throw_reason (RETURN_QUIT);
2879 }
2880
2881 target_terminal_inferior ();
2882 }
2883
2884 /* Enable/disable target terminal ownership. Most targets can use
2885 terminal groups to control terminal ownership. Remote targets are
2886 different in that explicit transfer of ownership to/from GDB/target
2887 is required. */
2888
2889 static void
2890 remote_async_terminal_inferior (void)
2891 {
2892 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
2893 sync_execution here. This function should only be called when
2894 GDB is resuming the inferior in the forground. A background
2895 resume (``run&'') should leave GDB in control of the terminal and
2896 consequently should not call this code. */
2897 if (!sync_execution)
2898 return;
2899 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
2900 calls target_terminal_*() idenpotent. The event-loop GDB talking
2901 to an asynchronous target with a synchronous command calls this
2902 function from both event-top.c and infrun.c/infcmd.c. Once GDB
2903 stops trying to transfer the terminal to the target when it
2904 shouldn't this guard can go away. */
2905 if (!remote_async_terminal_ours_p)
2906 return;
2907 delete_file_handler (input_fd);
2908 remote_async_terminal_ours_p = 0;
2909 initialize_sigint_signal_handler ();
2910 /* NOTE: At this point we could also register our selves as the
2911 recipient of all input. Any characters typed could then be
2912 passed on down to the target. */
2913 }
2914
2915 static void
2916 remote_async_terminal_ours (void)
2917 {
2918 /* See FIXME in remote_async_terminal_inferior. */
2919 if (!sync_execution)
2920 return;
2921 /* See FIXME in remote_async_terminal_inferior. */
2922 if (remote_async_terminal_ours_p)
2923 return;
2924 cleanup_sigint_signal_handler (NULL);
2925 add_file_handler (input_fd, stdin_event_handler, 0);
2926 remote_async_terminal_ours_p = 1;
2927 }
2928
2929 /* If nonzero, ignore the next kill. */
2930
2931 int kill_kludge;
2932
2933 void
2934 remote_console_output (char *msg)
2935 {
2936 char *p;
2937
2938 for (p = msg; p[0] && p[1]; p += 2)
2939 {
2940 char tb[2];
2941 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
2942 tb[0] = c;
2943 tb[1] = 0;
2944 fputs_unfiltered (tb, gdb_stdtarg);
2945 }
2946 gdb_flush (gdb_stdtarg);
2947 }
2948
2949 /* Wait until the remote machine stops, then return,
2950 storing status in STATUS just as `wait' would.
2951 Returns "pid", which in the case of a multi-threaded
2952 remote OS, is the thread-id. */
2953
2954 static ptid_t
2955 remote_wait (ptid_t ptid, struct target_waitstatus *status)
2956 {
2957 struct remote_state *rs = get_remote_state ();
2958 struct remote_arch_state *rsa = get_remote_arch_state ();
2959 ULONGEST thread_num = -1;
2960 ULONGEST addr;
2961
2962 status->kind = TARGET_WAITKIND_EXITED;
2963 status->value.integer = 0;
2964
2965 while (1)
2966 {
2967 char *buf, *p;
2968
2969 ofunc = signal (SIGINT, remote_interrupt);
2970 getpkt (&rs->buf, &rs->buf_size, 1);
2971 signal (SIGINT, ofunc);
2972
2973 buf = rs->buf;
2974
2975 /* This is a hook for when we need to do something (perhaps the
2976 collection of trace data) every time the target stops. */
2977 if (deprecated_target_wait_loop_hook)
2978 (*deprecated_target_wait_loop_hook) ();
2979
2980 remote_stopped_by_watchpoint_p = 0;
2981
2982 switch (buf[0])
2983 {
2984 case 'E': /* Error of some sort. */
2985 warning (_("Remote failure reply: %s"), buf);
2986 continue;
2987 case 'F': /* File-I/O request. */
2988 remote_fileio_request (buf);
2989 continue;
2990 case 'T': /* Status with PC, SP, FP, ... */
2991 {
2992 gdb_byte regs[MAX_REGISTER_SIZE];
2993
2994 /* Expedited reply, containing Signal, {regno, reg} repeat. */
2995 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
2996 ss = signal number
2997 n... = register number
2998 r... = register contents
2999 */
3000 p = &buf[3]; /* after Txx */
3001
3002 while (*p)
3003 {
3004 char *p1;
3005 char *p_temp;
3006 int fieldsize;
3007 LONGEST pnum = 0;
3008
3009 /* If the packet contains a register number save it in
3010 pnum and set p1 to point to the character following
3011 it. Otherwise p1 points to p. */
3012
3013 /* If this packet is an awatch packet, don't parse the
3014 'a' as a register number. */
3015
3016 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3017 {
3018 /* Read the ``P'' register number. */
3019 pnum = strtol (p, &p_temp, 16);
3020 p1 = p_temp;
3021 }
3022 else
3023 p1 = p;
3024
3025 if (p1 == p) /* No register number present here. */
3026 {
3027 p1 = strchr (p, ':');
3028 if (p1 == NULL)
3029 error (_("Malformed packet(a) (missing colon): %s\n\
3030 Packet: '%s'\n"),
3031 p, buf);
3032 if (strncmp (p, "thread", p1 - p) == 0)
3033 {
3034 p_temp = unpack_varlen_hex (++p1, &thread_num);
3035 record_currthread (thread_num);
3036 p = p_temp;
3037 }
3038 else if ((strncmp (p, "watch", p1 - p) == 0)
3039 || (strncmp (p, "rwatch", p1 - p) == 0)
3040 || (strncmp (p, "awatch", p1 - p) == 0))
3041 {
3042 remote_stopped_by_watchpoint_p = 1;
3043 p = unpack_varlen_hex (++p1, &addr);
3044 remote_watch_data_address = (CORE_ADDR)addr;
3045 }
3046 else
3047 {
3048 /* Silently skip unknown optional info. */
3049 p_temp = strchr (p1 + 1, ';');
3050 if (p_temp)
3051 p = p_temp;
3052 }
3053 }
3054 else
3055 {
3056 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3057 p = p1;
3058
3059 if (*p++ != ':')
3060 error (_("Malformed packet(b) (missing colon): %s\n\
3061 Packet: '%s'\n"),
3062 p, buf);
3063
3064 if (reg == NULL)
3065 error (_("Remote sent bad register number %s: %s\n\
3066 Packet: '%s'\n"),
3067 phex_nz (pnum, 0), p, buf);
3068
3069 fieldsize = hex2bin (p, regs,
3070 register_size (current_gdbarch,
3071 reg->regnum));
3072 p += 2 * fieldsize;
3073 if (fieldsize < register_size (current_gdbarch,
3074 reg->regnum))
3075 warning (_("Remote reply is too short: %s"), buf);
3076 regcache_raw_supply (current_regcache,
3077 reg->regnum, regs);
3078 }
3079
3080 if (*p++ != ';')
3081 error (_("Remote register badly formatted: %s\nhere: %s"),
3082 buf, p);
3083 }
3084 }
3085 /* fall through */
3086 case 'S': /* Old style status, just signal only. */
3087 status->kind = TARGET_WAITKIND_STOPPED;
3088 status->value.sig = (enum target_signal)
3089 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3090
3091 if (buf[3] == 'p')
3092 {
3093 thread_num = strtol ((const char *) &buf[4], NULL, 16);
3094 record_currthread (thread_num);
3095 }
3096 goto got_status;
3097 case 'W': /* Target exited. */
3098 {
3099 /* The remote process exited. */
3100 status->kind = TARGET_WAITKIND_EXITED;
3101 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3102 goto got_status;
3103 }
3104 case 'X':
3105 status->kind = TARGET_WAITKIND_SIGNALLED;
3106 status->value.sig = (enum target_signal)
3107 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3108 kill_kludge = 1;
3109
3110 goto got_status;
3111 case 'O': /* Console output. */
3112 remote_console_output (buf + 1);
3113 continue;
3114 case '\0':
3115 if (last_sent_signal != TARGET_SIGNAL_0)
3116 {
3117 /* Zero length reply means that we tried 'S' or 'C' and
3118 the remote system doesn't support it. */
3119 target_terminal_ours_for_output ();
3120 printf_filtered
3121 ("Can't send signals to this remote system. %s not sent.\n",
3122 target_signal_to_name (last_sent_signal));
3123 last_sent_signal = TARGET_SIGNAL_0;
3124 target_terminal_inferior ();
3125
3126 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3127 putpkt ((char *) buf);
3128 continue;
3129 }
3130 /* else fallthrough */
3131 default:
3132 warning (_("Invalid remote reply: %s"), buf);
3133 continue;
3134 }
3135 }
3136 got_status:
3137 if (thread_num != -1)
3138 {
3139 return pid_to_ptid (thread_num);
3140 }
3141 return inferior_ptid;
3142 }
3143
3144 /* Async version of remote_wait. */
3145 static ptid_t
3146 remote_async_wait (ptid_t ptid, struct target_waitstatus *status)
3147 {
3148 struct remote_state *rs = get_remote_state ();
3149 struct remote_arch_state *rsa = get_remote_arch_state ();
3150 ULONGEST thread_num = -1;
3151 ULONGEST addr;
3152
3153 status->kind = TARGET_WAITKIND_EXITED;
3154 status->value.integer = 0;
3155
3156 remote_stopped_by_watchpoint_p = 0;
3157
3158 while (1)
3159 {
3160 char *buf, *p;
3161
3162 if (!target_is_async_p ())
3163 ofunc = signal (SIGINT, remote_interrupt);
3164 /* FIXME: cagney/1999-09-27: If we're in async mode we should
3165 _never_ wait for ever -> test on target_is_async_p().
3166 However, before we do that we need to ensure that the caller
3167 knows how to take the target into/out of async mode. */
3168 getpkt (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
3169 if (!target_is_async_p ())
3170 signal (SIGINT, ofunc);
3171
3172 buf = rs->buf;
3173
3174 /* This is a hook for when we need to do something (perhaps the
3175 collection of trace data) every time the target stops. */
3176 if (deprecated_target_wait_loop_hook)
3177 (*deprecated_target_wait_loop_hook) ();
3178
3179 switch (buf[0])
3180 {
3181 case 'E': /* Error of some sort. */
3182 warning (_("Remote failure reply: %s"), buf);
3183 continue;
3184 case 'F': /* File-I/O request. */
3185 remote_fileio_request (buf);
3186 continue;
3187 case 'T': /* Status with PC, SP, FP, ... */
3188 {
3189 gdb_byte regs[MAX_REGISTER_SIZE];
3190
3191 /* Expedited reply, containing Signal, {regno, reg} repeat. */
3192 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
3193 ss = signal number
3194 n... = register number
3195 r... = register contents
3196 */
3197 p = &buf[3]; /* after Txx */
3198
3199 while (*p)
3200 {
3201 char *p1;
3202 char *p_temp;
3203 int fieldsize;
3204 long pnum = 0;
3205
3206 /* If the packet contains a register number, save it
3207 in pnum and set p1 to point to the character
3208 following it. Otherwise p1 points to p. */
3209
3210 /* If this packet is an awatch packet, don't parse the 'a'
3211 as a register number. */
3212
3213 if (!strncmp (p, "awatch", strlen ("awatch")) != 0)
3214 {
3215 /* Read the register number. */
3216 pnum = strtol (p, &p_temp, 16);
3217 p1 = p_temp;
3218 }
3219 else
3220 p1 = p;
3221
3222 if (p1 == p) /* No register number present here. */
3223 {
3224 p1 = strchr (p, ':');
3225 if (p1 == NULL)
3226 error (_("Malformed packet(a) (missing colon): %s\n\
3227 Packet: '%s'\n"),
3228 p, buf);
3229 if (strncmp (p, "thread", p1 - p) == 0)
3230 {
3231 p_temp = unpack_varlen_hex (++p1, &thread_num);
3232 record_currthread (thread_num);
3233 p = p_temp;
3234 }
3235 else if ((strncmp (p, "watch", p1 - p) == 0)
3236 || (strncmp (p, "rwatch", p1 - p) == 0)
3237 || (strncmp (p, "awatch", p1 - p) == 0))
3238 {
3239 remote_stopped_by_watchpoint_p = 1;
3240 p = unpack_varlen_hex (++p1, &addr);
3241 remote_watch_data_address = (CORE_ADDR)addr;
3242 }
3243 else
3244 {
3245 /* Silently skip unknown optional info. */
3246 p_temp = strchr (p1 + 1, ';');
3247 if (p_temp)
3248 p = p_temp;
3249 }
3250 }
3251
3252 else
3253 {
3254 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3255 p = p1;
3256 if (*p++ != ':')
3257 error (_("Malformed packet(b) (missing colon): %s\n\
3258 Packet: '%s'\n"),
3259 p, buf);
3260
3261 if (reg == NULL)
3262 error (_("Remote sent bad register number %ld: %s\n\
3263 Packet: '%s'\n"),
3264 pnum, p, buf);
3265
3266 fieldsize = hex2bin (p, regs,
3267 register_size (current_gdbarch,
3268 reg->regnum));
3269 p += 2 * fieldsize;
3270 if (fieldsize < register_size (current_gdbarch,
3271 reg->regnum))
3272 warning (_("Remote reply is too short: %s"), buf);
3273 regcache_raw_supply (current_regcache, reg->regnum, regs);
3274 }
3275
3276 if (*p++ != ';')
3277 error (_("Remote register badly formatted: %s\nhere: %s"),
3278 buf, p);
3279 }
3280 }
3281 /* fall through */
3282 case 'S': /* Old style status, just signal only. */
3283 status->kind = TARGET_WAITKIND_STOPPED;
3284 status->value.sig = (enum target_signal)
3285 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3286
3287 if (buf[3] == 'p')
3288 {
3289 thread_num = strtol ((const char *) &buf[4], NULL, 16);
3290 record_currthread (thread_num);
3291 }
3292 goto got_status;
3293 case 'W': /* Target exited. */
3294 {
3295 /* The remote process exited. */
3296 status->kind = TARGET_WAITKIND_EXITED;
3297 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3298 goto got_status;
3299 }
3300 case 'X':
3301 status->kind = TARGET_WAITKIND_SIGNALLED;
3302 status->value.sig = (enum target_signal)
3303 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3304 kill_kludge = 1;
3305
3306 goto got_status;
3307 case 'O': /* Console output. */
3308 remote_console_output (buf + 1);
3309 /* Return immediately to the event loop. The event loop will
3310 still be waiting on the inferior afterwards. */
3311 status->kind = TARGET_WAITKIND_IGNORE;
3312 goto got_status;
3313 case '\0':
3314 if (last_sent_signal != TARGET_SIGNAL_0)
3315 {
3316 /* Zero length reply means that we tried 'S' or 'C' and
3317 the remote system doesn't support it. */
3318 target_terminal_ours_for_output ();
3319 printf_filtered
3320 ("Can't send signals to this remote system. %s not sent.\n",
3321 target_signal_to_name (last_sent_signal));
3322 last_sent_signal = TARGET_SIGNAL_0;
3323 target_terminal_inferior ();
3324
3325 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3326 putpkt ((char *) buf);
3327 continue;
3328 }
3329 /* else fallthrough */
3330 default:
3331 warning (_("Invalid remote reply: %s"), buf);
3332 continue;
3333 }
3334 }
3335 got_status:
3336 if (thread_num != -1)
3337 {
3338 return pid_to_ptid (thread_num);
3339 }
3340 return inferior_ptid;
3341 }
3342
3343 /* Number of bytes of registers this stub implements. */
3344
3345 static int register_bytes_found;
3346
3347 /* Read the remote registers into the block REGS. */
3348 /* Currently we just read all the registers, so we don't use regnum. */
3349
3350 static int
3351 fetch_register_using_p (int regnum)
3352 {
3353 struct remote_state *rs = get_remote_state ();
3354 char *buf, *p;
3355 char regp[MAX_REGISTER_SIZE];
3356 int i;
3357
3358 p = rs->buf;
3359 *p++ = 'p';
3360 p += hexnumstr (p, regnum);
3361 *p++ = '\0';
3362 remote_send (&rs->buf, &rs->buf_size);
3363
3364 buf = rs->buf;
3365
3366 /* If the stub didn't recognize the packet, or if we got an error,
3367 tell our caller. */
3368 if (buf[0] == '\0' || buf[0] == 'E')
3369 return 0;
3370
3371 /* If this register is unfetchable, tell the regcache. */
3372 if (buf[0] == 'x')
3373 {
3374 regcache_raw_supply (current_regcache, regnum, NULL);
3375 set_register_cached (regnum, -1);
3376 return 1;
3377 }
3378
3379 /* Otherwise, parse and supply the value. */
3380 p = buf;
3381 i = 0;
3382 while (p[0] != 0)
3383 {
3384 if (p[1] == 0)
3385 {
3386 error (_("fetch_register_using_p: early buf termination"));
3387 return 0;
3388 }
3389
3390 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
3391 p += 2;
3392 }
3393 regcache_raw_supply (current_regcache, regnum, regp);
3394 return 1;
3395 }
3396
3397 static void
3398 remote_fetch_registers (int regnum)
3399 {
3400 struct remote_state *rs = get_remote_state ();
3401 struct remote_arch_state *rsa = get_remote_arch_state ();
3402 char *buf;
3403 int i;
3404 char *p;
3405 char *regs = alloca (rsa->sizeof_g_packet);
3406
3407 set_thread (PIDGET (inferior_ptid), 1);
3408
3409 if (regnum >= 0)
3410 {
3411 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
3412 gdb_assert (reg != NULL);
3413 if (!reg->in_g_packet)
3414 internal_error (__FILE__, __LINE__,
3415 _("Attempt to fetch a non G-packet register when this "
3416 "remote.c does not support the p-packet."));
3417 }
3418 switch (remote_protocol_packets[PACKET_p].support)
3419 {
3420 case PACKET_DISABLE:
3421 break;
3422 case PACKET_ENABLE:
3423 if (fetch_register_using_p (regnum))
3424 return;
3425 else
3426 error (_("Protocol error: p packet not recognized by stub"));
3427 case PACKET_SUPPORT_UNKNOWN:
3428 if (fetch_register_using_p (regnum))
3429 {
3430 /* The stub recognized the 'p' packet. Remember this. */
3431 remote_protocol_packets[PACKET_p].support = PACKET_ENABLE;
3432 return;
3433 }
3434 else
3435 {
3436 /* The stub does not support the 'P' packet. Use 'G'
3437 instead, and don't try using 'P' in the future (it
3438 will just waste our time). */
3439 remote_protocol_packets[PACKET_p].support = PACKET_DISABLE;
3440 break;
3441 }
3442 }
3443
3444 sprintf (rs->buf, "g");
3445 remote_send (&rs->buf, &rs->buf_size);
3446 buf = rs->buf;
3447
3448 /* Save the size of the packet sent to us by the target. Its used
3449 as a heuristic when determining the max size of packets that the
3450 target can safely receive. */
3451 if ((rsa->actual_register_packet_size) == 0)
3452 (rsa->actual_register_packet_size) = strlen (buf);
3453
3454 /* Unimplemented registers read as all bits zero. */
3455 memset (regs, 0, rsa->sizeof_g_packet);
3456
3457 /* We can get out of synch in various cases. If the first character
3458 in the buffer is not a hex character, assume that has happened
3459 and try to fetch another packet to read. */
3460 while ((buf[0] < '0' || buf[0] > '9')
3461 && (buf[0] < 'A' || buf[0] > 'F')
3462 && (buf[0] < 'a' || buf[0] > 'f')
3463 && buf[0] != 'x') /* New: unavailable register value. */
3464 {
3465 if (remote_debug)
3466 fprintf_unfiltered (gdb_stdlog,
3467 "Bad register packet; fetching a new packet\n");
3468 getpkt (&rs->buf, &rs->buf_size, 0);
3469 buf = rs->buf;
3470 }
3471
3472 /* Reply describes registers byte by byte, each byte encoded as two
3473 hex characters. Suck them all up, then supply them to the
3474 register cacheing/storage mechanism. */
3475
3476 p = buf;
3477 for (i = 0; i < rsa->sizeof_g_packet; i++)
3478 {
3479 if (p[0] == 0)
3480 break;
3481 if (p[1] == 0)
3482 {
3483 warning (_("Remote reply is of odd length: %s"), buf);
3484 /* Don't change register_bytes_found in this case, and don't
3485 print a second warning. */
3486 goto supply_them;
3487 }
3488 if (p[0] == 'x' && p[1] == 'x')
3489 regs[i] = 0; /* 'x' */
3490 else
3491 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3492 p += 2;
3493 }
3494
3495 if (i != register_bytes_found)
3496 {
3497 register_bytes_found = i;
3498 if (REGISTER_BYTES_OK_P ()
3499 && !REGISTER_BYTES_OK (i))
3500 warning (_("Remote reply is too short: %s"), buf);
3501 }
3502
3503 supply_them:
3504 {
3505 int i;
3506 for (i = 0; i < NUM_REGS + NUM_PSEUDO_REGS; i++)
3507 {
3508 struct packet_reg *r = &rsa->regs[i];
3509 if (r->in_g_packet)
3510 {
3511 if (r->offset * 2 >= strlen (buf))
3512 /* A short packet that didn't include the register's
3513 value, this implies that the register is zero (and
3514 not that the register is unavailable). Supply that
3515 zero value. */
3516 regcache_raw_supply (current_regcache, r->regnum, NULL);
3517 else if (buf[r->offset * 2] == 'x')
3518 {
3519 gdb_assert (r->offset * 2 < strlen (buf));
3520 /* The register isn't available, mark it as such (at
3521 the same time setting the value to zero). */
3522 regcache_raw_supply (current_regcache, r->regnum, NULL);
3523 set_register_cached (i, -1);
3524 }
3525 else
3526 regcache_raw_supply (current_regcache, r->regnum,
3527 regs + r->offset);
3528 }
3529 }
3530 }
3531 }
3532
3533 /* Prepare to store registers. Since we may send them all (using a
3534 'G' request), we have to read out the ones we don't want to change
3535 first. */
3536
3537 static void
3538 remote_prepare_to_store (void)
3539 {
3540 struct remote_arch_state *rsa = get_remote_arch_state ();
3541 int i;
3542 gdb_byte buf[MAX_REGISTER_SIZE];
3543
3544 /* Make sure the entire registers array is valid. */
3545 switch (remote_protocol_packets[PACKET_P].support)
3546 {
3547 case PACKET_DISABLE:
3548 case PACKET_SUPPORT_UNKNOWN:
3549 /* Make sure all the necessary registers are cached. */
3550 for (i = 0; i < NUM_REGS; i++)
3551 if (rsa->regs[i].in_g_packet)
3552 regcache_raw_read (current_regcache, rsa->regs[i].regnum, buf);
3553 break;
3554 case PACKET_ENABLE:
3555 break;
3556 }
3557 }
3558
3559 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
3560 packet was not recognized. */
3561
3562 static int
3563 store_register_using_P (int regnum)
3564 {
3565 struct remote_state *rs = get_remote_state ();
3566 struct remote_arch_state *rsa = get_remote_arch_state ();
3567 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
3568 /* Try storing a single register. */
3569 char *buf = rs->buf;
3570 gdb_byte regp[MAX_REGISTER_SIZE];
3571 char *p;
3572
3573 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
3574 p = buf + strlen (buf);
3575 regcache_raw_collect (current_regcache, reg->regnum, regp);
3576 bin2hex (regp, p, register_size (current_gdbarch, reg->regnum));
3577 remote_send (&rs->buf, &rs->buf_size);
3578
3579 return rs->buf[0] != '\0';
3580 }
3581
3582
3583 /* Store register REGNUM, or all registers if REGNUM == -1, from the
3584 contents of the register cache buffer. FIXME: ignores errors. */
3585
3586 static void
3587 remote_store_registers (int regnum)
3588 {
3589 struct remote_state *rs = get_remote_state ();
3590 struct remote_arch_state *rsa = get_remote_arch_state ();
3591 gdb_byte *regs;
3592 char *p;
3593
3594 set_thread (PIDGET (inferior_ptid), 1);
3595
3596 if (regnum >= 0)
3597 {
3598 switch (remote_protocol_packets[PACKET_P].support)
3599 {
3600 case PACKET_DISABLE:
3601 break;
3602 case PACKET_ENABLE:
3603 if (store_register_using_P (regnum))
3604 return;
3605 else
3606 error (_("Protocol error: P packet not recognized by stub"));
3607 case PACKET_SUPPORT_UNKNOWN:
3608 if (store_register_using_P (regnum))
3609 {
3610 /* The stub recognized the 'P' packet. Remember this. */
3611 remote_protocol_packets[PACKET_P].support = PACKET_ENABLE;
3612 return;
3613 }
3614 else
3615 {
3616 /* The stub does not support the 'P' packet. Use 'G'
3617 instead, and don't try using 'P' in the future (it
3618 will just waste our time). */
3619 remote_protocol_packets[PACKET_P].support = PACKET_DISABLE;
3620 break;
3621 }
3622 }
3623 }
3624
3625 /* Extract all the registers in the regcache copying them into a
3626 local buffer. */
3627 {
3628 int i;
3629 regs = alloca (rsa->sizeof_g_packet);
3630 memset (regs, 0, rsa->sizeof_g_packet);
3631 for (i = 0; i < NUM_REGS + NUM_PSEUDO_REGS; i++)
3632 {
3633 struct packet_reg *r = &rsa->regs[i];
3634 if (r->in_g_packet)
3635 regcache_raw_collect (current_regcache, r->regnum, regs + r->offset);
3636 }
3637 }
3638
3639 /* Command describes registers byte by byte,
3640 each byte encoded as two hex characters. */
3641 p = rs->buf;
3642 *p++ = 'G';
3643 /* remote_prepare_to_store insures that register_bytes_found gets set. */
3644 bin2hex (regs, p, register_bytes_found);
3645 remote_send (&rs->buf, &rs->buf_size);
3646 }
3647 \f
3648
3649 /* Return the number of hex digits in num. */
3650
3651 static int
3652 hexnumlen (ULONGEST num)
3653 {
3654 int i;
3655
3656 for (i = 0; num != 0; i++)
3657 num >>= 4;
3658
3659 return max (i, 1);
3660 }
3661
3662 /* Set BUF to the minimum number of hex digits representing NUM. */
3663
3664 static int
3665 hexnumstr (char *buf, ULONGEST num)
3666 {
3667 int len = hexnumlen (num);
3668 return hexnumnstr (buf, num, len);
3669 }
3670
3671
3672 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
3673
3674 static int
3675 hexnumnstr (char *buf, ULONGEST num, int width)
3676 {
3677 int i;
3678
3679 buf[width] = '\0';
3680
3681 for (i = width - 1; i >= 0; i--)
3682 {
3683 buf[i] = "0123456789abcdef"[(num & 0xf)];
3684 num >>= 4;
3685 }
3686
3687 return width;
3688 }
3689
3690 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
3691
3692 static CORE_ADDR
3693 remote_address_masked (CORE_ADDR addr)
3694 {
3695 if (remote_address_size > 0
3696 && remote_address_size < (sizeof (ULONGEST) * 8))
3697 {
3698 /* Only create a mask when that mask can safely be constructed
3699 in a ULONGEST variable. */
3700 ULONGEST mask = 1;
3701 mask = (mask << remote_address_size) - 1;
3702 addr &= mask;
3703 }
3704 return addr;
3705 }
3706
3707 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
3708 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
3709 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
3710 (which may be more than *OUT_LEN due to escape characters). The
3711 total number of bytes in the output buffer will be at most
3712 OUT_MAXLEN. */
3713
3714 static int
3715 remote_escape_output (const gdb_byte *buffer, int len,
3716 gdb_byte *out_buf, int *out_len,
3717 int out_maxlen)
3718 {
3719 int input_index, output_index;
3720
3721 output_index = 0;
3722 for (input_index = 0; input_index < len; input_index++)
3723 {
3724 gdb_byte b = buffer[input_index];
3725
3726 if (b == '$' || b == '#' || b == '}')
3727 {
3728 /* These must be escaped. */
3729 if (output_index + 2 > out_maxlen)
3730 break;
3731 out_buf[output_index++] = '}';
3732 out_buf[output_index++] = b ^ 0x20;
3733 }
3734 else
3735 {
3736 if (output_index + 1 > out_maxlen)
3737 break;
3738 out_buf[output_index++] = b;
3739 }
3740 }
3741
3742 *out_len = input_index;
3743 return output_index;
3744 }
3745
3746 /* Convert BUFFER, escaped data LEN bytes long, into binary data
3747 in OUT_BUF. Return the number of bytes written to OUT_BUF.
3748 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
3749
3750 This function reverses remote_escape_output. It allows more
3751 escaped characters than that function does, in particular because
3752 '*' must be escaped to avoid the run-length encoding processing
3753 in reading packets. */
3754
3755 static int
3756 remote_unescape_input (const gdb_byte *buffer, int len,
3757 gdb_byte *out_buf, int out_maxlen)
3758 {
3759 int input_index, output_index;
3760 int escaped;
3761
3762 output_index = 0;
3763 escaped = 0;
3764 for (input_index = 0; input_index < len; input_index++)
3765 {
3766 gdb_byte b = buffer[input_index];
3767
3768 if (output_index + 1 > out_maxlen)
3769 {
3770 warning (_("Received too much data from remote target;"
3771 " ignoring overflow."));
3772 return output_index;
3773 }
3774
3775 if (escaped)
3776 {
3777 out_buf[output_index++] = b ^ 0x20;
3778 escaped = 0;
3779 }
3780 else if (b == '}')
3781 escaped = 1;
3782 else
3783 out_buf[output_index++] = b;
3784 }
3785
3786 if (escaped)
3787 error (_("Unmatched escape character in target response."));
3788
3789 return output_index;
3790 }
3791
3792 /* Determine whether the remote target supports binary downloading.
3793 This is accomplished by sending a no-op memory write of zero length
3794 to the target at the specified address. It does not suffice to send
3795 the whole packet, since many stubs strip the eighth bit and
3796 subsequently compute a wrong checksum, which causes real havoc with
3797 remote_write_bytes.
3798
3799 NOTE: This can still lose if the serial line is not eight-bit
3800 clean. In cases like this, the user should clear "remote
3801 X-packet". */
3802
3803 static void
3804 check_binary_download (CORE_ADDR addr)
3805 {
3806 struct remote_state *rs = get_remote_state ();
3807
3808 switch (remote_protocol_packets[PACKET_X].support)
3809 {
3810 case PACKET_DISABLE:
3811 break;
3812 case PACKET_ENABLE:
3813 break;
3814 case PACKET_SUPPORT_UNKNOWN:
3815 {
3816 char *p;
3817
3818 p = rs->buf;
3819 *p++ = 'X';
3820 p += hexnumstr (p, (ULONGEST) addr);
3821 *p++ = ',';
3822 p += hexnumstr (p, (ULONGEST) 0);
3823 *p++ = ':';
3824 *p = '\0';
3825
3826 putpkt_binary (rs->buf, (int) (p - rs->buf));
3827 getpkt (&rs->buf, &rs->buf_size, 0);
3828
3829 if (rs->buf[0] == '\0')
3830 {
3831 if (remote_debug)
3832 fprintf_unfiltered (gdb_stdlog,
3833 "binary downloading NOT suppported by target\n");
3834 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
3835 }
3836 else
3837 {
3838 if (remote_debug)
3839 fprintf_unfiltered (gdb_stdlog,
3840 "binary downloading suppported by target\n");
3841 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
3842 }
3843 break;
3844 }
3845 }
3846 }
3847
3848 /* Write memory data directly to the remote machine.
3849 This does not inform the data cache; the data cache uses this.
3850 MEMADDR is the address in the remote memory space.
3851 MYADDR is the address of the buffer in our space.
3852 LEN is the number of bytes.
3853
3854 Returns number of bytes transferred, or 0 (setting errno) for
3855 error. Only transfer a single packet. */
3856
3857 int
3858 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
3859 {
3860 struct remote_state *rs = get_remote_state ();
3861 char *p;
3862 char *plen;
3863 int plenlen;
3864 int todo;
3865 int nr_bytes;
3866 int payload_size;
3867 int payload_length;
3868
3869 /* Should this be the selected frame? */
3870 gdbarch_remote_translate_xfer_address (current_gdbarch,
3871 current_regcache,
3872 memaddr, len,
3873 &memaddr, &len);
3874
3875 if (len <= 0)
3876 return 0;
3877
3878 /* Verify that the target can support a binary download. */
3879 check_binary_download (memaddr);
3880
3881 payload_size = get_memory_write_packet_size ();
3882
3883 /* The packet buffer will be large enough for the payload;
3884 get_memory_packet_size ensures this. */
3885
3886 /* Compute the size of the actual payload by subtracting out the
3887 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
3888 */
3889 payload_size -= strlen ("$M,:#NN");
3890 payload_size -= hexnumlen (memaddr);
3891
3892 /* Construct the packet header: "[MX]<memaddr>,<len>:". */
3893
3894 /* Append "[XM]". Compute a best guess of the number of bytes
3895 actually transfered. */
3896 p = rs->buf;
3897 switch (remote_protocol_packets[PACKET_X].support)
3898 {
3899 case PACKET_ENABLE:
3900 *p++ = 'X';
3901 /* Best guess at number of bytes that will fit. */
3902 todo = min (len, payload_size);
3903 payload_size -= hexnumlen (todo);
3904 todo = min (todo, payload_size);
3905 break;
3906 case PACKET_DISABLE:
3907 *p++ = 'M';
3908 /* Num bytes that will fit. */
3909 todo = min (len, payload_size / 2);
3910 payload_size -= hexnumlen (todo);
3911 todo = min (todo, payload_size / 2);
3912 break;
3913 case PACKET_SUPPORT_UNKNOWN:
3914 internal_error (__FILE__, __LINE__,
3915 _("remote_write_bytes: bad internal state"));
3916 default:
3917 internal_error (__FILE__, __LINE__, _("bad switch"));
3918 }
3919 if (todo <= 0)
3920 internal_error (__FILE__, __LINE__,
3921 _("minumum packet size too small to write data"));
3922
3923 /* If we already need another packet, then try to align the end
3924 of this packet to a useful boundary. */
3925 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
3926 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
3927
3928 /* Append "<memaddr>". */
3929 memaddr = remote_address_masked (memaddr);
3930 p += hexnumstr (p, (ULONGEST) memaddr);
3931
3932 /* Append ",". */
3933 *p++ = ',';
3934
3935 /* Append <len>. Retain the location/size of <len>. It may need to
3936 be adjusted once the packet body has been created. */
3937 plen = p;
3938 plenlen = hexnumstr (p, (ULONGEST) todo);
3939 p += plenlen;
3940
3941 /* Append ":". */
3942 *p++ = ':';
3943 *p = '\0';
3944
3945 /* Append the packet body. */
3946 switch (remote_protocol_packets[PACKET_X].support)
3947 {
3948 case PACKET_ENABLE:
3949 /* Binary mode. Send target system values byte by byte, in
3950 increasing byte addresses. Only escape certain critical
3951 characters. */
3952 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
3953 payload_size);
3954
3955 /* If not all TODO bytes fit, then we'll need another packet. Make
3956 a second try to keep the end of the packet aligned. */
3957 if (nr_bytes < todo)
3958 {
3959 int new_nr_bytes;
3960
3961 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
3962 - memaddr);
3963 if (new_nr_bytes != nr_bytes)
3964 payload_length = remote_escape_output (myaddr, new_nr_bytes,
3965 p, &nr_bytes,
3966 payload_size);
3967 }
3968
3969 p += payload_length;
3970 if (nr_bytes < todo)
3971 {
3972 /* Escape chars have filled up the buffer prematurely,
3973 and we have actually sent fewer bytes than planned.
3974 Fix-up the length field of the packet. Use the same
3975 number of characters as before. */
3976 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
3977 *plen = ':'; /* overwrite \0 from hexnumnstr() */
3978 }
3979 break;
3980 case PACKET_DISABLE:
3981 /* Normal mode: Send target system values byte by byte, in
3982 increasing byte addresses. Each byte is encoded as a two hex
3983 value. */
3984 nr_bytes = bin2hex (myaddr, p, todo);
3985 p += 2 * nr_bytes;
3986 break;
3987 case PACKET_SUPPORT_UNKNOWN:
3988 internal_error (__FILE__, __LINE__,
3989 _("remote_write_bytes: bad internal state"));
3990 default:
3991 internal_error (__FILE__, __LINE__, _("bad switch"));
3992 }
3993
3994 putpkt_binary (rs->buf, (int) (p - rs->buf));
3995 getpkt (&rs->buf, &rs->buf_size, 0);
3996
3997 if (rs->buf[0] == 'E')
3998 {
3999 /* There is no correspondance between what the remote protocol
4000 uses for errors and errno codes. We would like a cleaner way
4001 of representing errors (big enough to include errno codes,
4002 bfd_error codes, and others). But for now just return EIO. */
4003 errno = EIO;
4004 return 0;
4005 }
4006
4007 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
4008 fewer bytes than we'd planned. */
4009 return nr_bytes;
4010 }
4011
4012 /* Read memory data directly from the remote machine.
4013 This does not use the data cache; the data cache uses this.
4014 MEMADDR is the address in the remote memory space.
4015 MYADDR is the address of the buffer in our space.
4016 LEN is the number of bytes.
4017
4018 Returns number of bytes transferred, or 0 for error. */
4019
4020 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
4021 remote targets) shouldn't attempt to read the entire buffer.
4022 Instead it should read a single packet worth of data and then
4023 return the byte size of that packet to the caller. The caller (its
4024 caller and its callers caller ;-) already contains code for
4025 handling partial reads. */
4026
4027 int
4028 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
4029 {
4030 struct remote_state *rs = get_remote_state ();
4031 int max_buf_size; /* Max size of packet output buffer. */
4032 int origlen;
4033
4034 /* Should this be the selected frame? */
4035 gdbarch_remote_translate_xfer_address (current_gdbarch,
4036 current_regcache,
4037 memaddr, len,
4038 &memaddr, &len);
4039
4040 if (len <= 0)
4041 return 0;
4042
4043 max_buf_size = get_memory_read_packet_size ();
4044 /* The packet buffer will be large enough for the payload;
4045 get_memory_packet_size ensures this. */
4046
4047 origlen = len;
4048 while (len > 0)
4049 {
4050 char *p;
4051 int todo;
4052 int i;
4053
4054 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
4055
4056 /* construct "m"<memaddr>","<len>" */
4057 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
4058 memaddr = remote_address_masked (memaddr);
4059 p = rs->buf;
4060 *p++ = 'm';
4061 p += hexnumstr (p, (ULONGEST) memaddr);
4062 *p++ = ',';
4063 p += hexnumstr (p, (ULONGEST) todo);
4064 *p = '\0';
4065
4066 putpkt (rs->buf);
4067 getpkt (&rs->buf, &rs->buf_size, 0);
4068
4069 if (rs->buf[0] == 'E'
4070 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
4071 && rs->buf[3] == '\0')
4072 {
4073 /* There is no correspondance between what the remote
4074 protocol uses for errors and errno codes. We would like
4075 a cleaner way of representing errors (big enough to
4076 include errno codes, bfd_error codes, and others). But
4077 for now just return EIO. */
4078 errno = EIO;
4079 return 0;
4080 }
4081
4082 /* Reply describes memory byte by byte,
4083 each byte encoded as two hex characters. */
4084
4085 p = rs->buf;
4086 if ((i = hex2bin (p, myaddr, todo)) < todo)
4087 {
4088 /* Reply is short. This means that we were able to read
4089 only part of what we wanted to. */
4090 return i + (origlen - len);
4091 }
4092 myaddr += todo;
4093 memaddr += todo;
4094 len -= todo;
4095 }
4096 return origlen;
4097 }
4098 \f
4099 /* Read or write LEN bytes from inferior memory at MEMADDR,
4100 transferring to or from debugger address BUFFER. Write to inferior
4101 if SHOULD_WRITE is nonzero. Returns length of data written or
4102 read; 0 for error. TARGET is unused. */
4103
4104 static int
4105 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
4106 int should_write, struct mem_attrib *attrib,
4107 struct target_ops *target)
4108 {
4109 int res;
4110
4111 if (should_write)
4112 res = remote_write_bytes (mem_addr, buffer, mem_len);
4113 else
4114 res = remote_read_bytes (mem_addr, buffer, mem_len);
4115
4116 return res;
4117 }
4118
4119 static void
4120 remote_files_info (struct target_ops *ignore)
4121 {
4122 puts_filtered ("Debugging a target over a serial line.\n");
4123 }
4124 \f
4125 /* Stuff for dealing with the packets which are part of this protocol.
4126 See comment at top of file for details. */
4127
4128 /* Read a single character from the remote end. */
4129
4130 static int
4131 readchar (int timeout)
4132 {
4133 int ch;
4134
4135 ch = serial_readchar (remote_desc, timeout);
4136
4137 if (ch >= 0)
4138 return ch;
4139
4140 switch ((enum serial_rc) ch)
4141 {
4142 case SERIAL_EOF:
4143 target_mourn_inferior ();
4144 error (_("Remote connection closed"));
4145 /* no return */
4146 case SERIAL_ERROR:
4147 perror_with_name (_("Remote communication error"));
4148 /* no return */
4149 case SERIAL_TIMEOUT:
4150 break;
4151 }
4152 return ch;
4153 }
4154
4155 /* Send the command in *BUF to the remote machine, and read the reply
4156 into *BUF. Report an error if we get an error reply. Resize
4157 *BUF using xrealloc if necessary to hold the result, and update
4158 *SIZEOF_BUF. */
4159
4160 static void
4161 remote_send (char **buf,
4162 long *sizeof_buf)
4163 {
4164 putpkt (*buf);
4165 getpkt (buf, sizeof_buf, 0);
4166
4167 if ((*buf)[0] == 'E')
4168 error (_("Remote failure reply: %s"), *buf);
4169 }
4170
4171 /* Display a null-terminated packet on stdout, for debugging, using C
4172 string notation. */
4173
4174 static void
4175 print_packet (char *buf)
4176 {
4177 puts_filtered ("\"");
4178 fputstr_filtered (buf, '"', gdb_stdout);
4179 puts_filtered ("\"");
4180 }
4181
4182 int
4183 putpkt (char *buf)
4184 {
4185 return putpkt_binary (buf, strlen (buf));
4186 }
4187
4188 /* Send a packet to the remote machine, with error checking. The data
4189 of the packet is in BUF. The string in BUF can be at most
4190 get_remote_packet_size () - 5 to account for the $, # and checksum,
4191 and for a possible /0 if we are debugging (remote_debug) and want
4192 to print the sent packet as a string. */
4193
4194 static int
4195 putpkt_binary (char *buf, int cnt)
4196 {
4197 int i;
4198 unsigned char csum = 0;
4199 char *buf2 = alloca (cnt + 6);
4200
4201 int ch;
4202 int tcount = 0;
4203 char *p;
4204
4205 /* Copy the packet into buffer BUF2, encapsulating it
4206 and giving it a checksum. */
4207
4208 p = buf2;
4209 *p++ = '$';
4210
4211 for (i = 0; i < cnt; i++)
4212 {
4213 csum += buf[i];
4214 *p++ = buf[i];
4215 }
4216 *p++ = '#';
4217 *p++ = tohex ((csum >> 4) & 0xf);
4218 *p++ = tohex (csum & 0xf);
4219
4220 /* Send it over and over until we get a positive ack. */
4221
4222 while (1)
4223 {
4224 int started_error_output = 0;
4225
4226 if (remote_debug)
4227 {
4228 *p = '\0';
4229 fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
4230 fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
4231 fprintf_unfiltered (gdb_stdlog, "...");
4232 gdb_flush (gdb_stdlog);
4233 }
4234 if (serial_write (remote_desc, buf2, p - buf2))
4235 perror_with_name (_("putpkt: write failed"));
4236
4237 /* Read until either a timeout occurs (-2) or '+' is read. */
4238 while (1)
4239 {
4240 ch = readchar (remote_timeout);
4241
4242 if (remote_debug)
4243 {
4244 switch (ch)
4245 {
4246 case '+':
4247 case '-':
4248 case SERIAL_TIMEOUT:
4249 case '$':
4250 if (started_error_output)
4251 {
4252 putchar_unfiltered ('\n');
4253 started_error_output = 0;
4254 }
4255 }
4256 }
4257
4258 switch (ch)
4259 {
4260 case '+':
4261 if (remote_debug)
4262 fprintf_unfiltered (gdb_stdlog, "Ack\n");
4263 return 1;
4264 case '-':
4265 if (remote_debug)
4266 fprintf_unfiltered (gdb_stdlog, "Nak\n");
4267 case SERIAL_TIMEOUT:
4268 tcount++;
4269 if (tcount > 3)
4270 return 0;
4271 break; /* Retransmit buffer. */
4272 case '$':
4273 {
4274 if (remote_debug)
4275 fprintf_unfiltered (gdb_stdlog,
4276 "Packet instead of Ack, ignoring it\n");
4277 /* It's probably an old response sent because an ACK
4278 was lost. Gobble up the packet and ack it so it
4279 doesn't get retransmitted when we resend this
4280 packet. */
4281 skip_frame ();
4282 serial_write (remote_desc, "+", 1);
4283 continue; /* Now, go look for +. */
4284 }
4285 default:
4286 if (remote_debug)
4287 {
4288 if (!started_error_output)
4289 {
4290 started_error_output = 1;
4291 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
4292 }
4293 fputc_unfiltered (ch & 0177, gdb_stdlog);
4294 }
4295 continue;
4296 }
4297 break; /* Here to retransmit. */
4298 }
4299
4300 #if 0
4301 /* This is wrong. If doing a long backtrace, the user should be
4302 able to get out next time we call QUIT, without anything as
4303 violent as interrupt_query. If we want to provide a way out of
4304 here without getting to the next QUIT, it should be based on
4305 hitting ^C twice as in remote_wait. */
4306 if (quit_flag)
4307 {
4308 quit_flag = 0;
4309 interrupt_query ();
4310 }
4311 #endif
4312 }
4313 }
4314
4315 /* Come here after finding the start of a frame when we expected an
4316 ack. Do our best to discard the rest of this packet. */
4317
4318 static void
4319 skip_frame (void)
4320 {
4321 int c;
4322
4323 while (1)
4324 {
4325 c = readchar (remote_timeout);
4326 switch (c)
4327 {
4328 case SERIAL_TIMEOUT:
4329 /* Nothing we can do. */
4330 return;
4331 case '#':
4332 /* Discard the two bytes of checksum and stop. */
4333 c = readchar (remote_timeout);
4334 if (c >= 0)
4335 c = readchar (remote_timeout);
4336
4337 return;
4338 case '*': /* Run length encoding. */
4339 /* Discard the repeat count. */
4340 c = readchar (remote_timeout);
4341 if (c < 0)
4342 return;
4343 break;
4344 default:
4345 /* A regular character. */
4346 break;
4347 }
4348 }
4349 }
4350
4351 /* Come here after finding the start of the frame. Collect the rest
4352 into *BUF, verifying the checksum, length, and handling run-length
4353 compression. NUL terminate the buffer. If there is not enough room,
4354 expand *BUF using xrealloc.
4355
4356 Returns -1 on error, number of characters in buffer (ignoring the
4357 trailing NULL) on success. (could be extended to return one of the
4358 SERIAL status indications). */
4359
4360 static long
4361 read_frame (char **buf_p,
4362 long *sizeof_buf)
4363 {
4364 unsigned char csum;
4365 long bc;
4366 int c;
4367 char *buf = *buf_p;
4368
4369 csum = 0;
4370 bc = 0;
4371
4372 while (1)
4373 {
4374 c = readchar (remote_timeout);
4375 switch (c)
4376 {
4377 case SERIAL_TIMEOUT:
4378 if (remote_debug)
4379 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
4380 return -1;
4381 case '$':
4382 if (remote_debug)
4383 fputs_filtered ("Saw new packet start in middle of old one\n",
4384 gdb_stdlog);
4385 return -1; /* Start a new packet, count retries. */
4386 case '#':
4387 {
4388 unsigned char pktcsum;
4389 int check_0 = 0;
4390 int check_1 = 0;
4391
4392 buf[bc] = '\0';
4393
4394 check_0 = readchar (remote_timeout);
4395 if (check_0 >= 0)
4396 check_1 = readchar (remote_timeout);
4397
4398 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
4399 {
4400 if (remote_debug)
4401 fputs_filtered ("Timeout in checksum, retrying\n",
4402 gdb_stdlog);
4403 return -1;
4404 }
4405 else if (check_0 < 0 || check_1 < 0)
4406 {
4407 if (remote_debug)
4408 fputs_filtered ("Communication error in checksum\n",
4409 gdb_stdlog);
4410 return -1;
4411 }
4412
4413 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
4414 if (csum == pktcsum)
4415 return bc;
4416
4417 if (remote_debug)
4418 {
4419 fprintf_filtered (gdb_stdlog,
4420 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
4421 pktcsum, csum);
4422 fputstrn_filtered (buf, bc, 0, gdb_stdlog);
4423 fputs_filtered ("\n", gdb_stdlog);
4424 }
4425 /* Number of characters in buffer ignoring trailing
4426 NULL. */
4427 return -1;
4428 }
4429 case '*': /* Run length encoding. */
4430 {
4431 int repeat;
4432 csum += c;
4433
4434 c = readchar (remote_timeout);
4435 csum += c;
4436 repeat = c - ' ' + 3; /* Compute repeat count. */
4437
4438 /* The character before ``*'' is repeated. */
4439
4440 if (repeat > 0 && repeat <= 255 && bc > 0)
4441 {
4442 if (bc + repeat - 1 >= *sizeof_buf - 1)
4443 {
4444 /* Make some more room in the buffer. */
4445 *sizeof_buf += repeat;
4446 *buf_p = xrealloc (*buf_p, *sizeof_buf);
4447 buf = *buf_p;
4448 }
4449
4450 memset (&buf[bc], buf[bc - 1], repeat);
4451 bc += repeat;
4452 continue;
4453 }
4454
4455 buf[bc] = '\0';
4456 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
4457 return -1;
4458 }
4459 default:
4460 if (bc >= *sizeof_buf - 1)
4461 {
4462 /* Make some more room in the buffer. */
4463 *sizeof_buf *= 2;
4464 *buf_p = xrealloc (*buf_p, *sizeof_buf);
4465 buf = *buf_p;
4466 }
4467
4468 buf[bc++] = c;
4469 csum += c;
4470 continue;
4471 }
4472 }
4473 }
4474
4475 /* Read a packet from the remote machine, with error checking, and
4476 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
4477 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
4478 rather than timing out; this is used (in synchronous mode) to wait
4479 for a target that is is executing user code to stop. */
4480 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
4481 don't have to change all the calls to getpkt to deal with the
4482 return value, because at the moment I don't know what the right
4483 thing to do it for those. */
4484 void
4485 getpkt (char **buf,
4486 long *sizeof_buf,
4487 int forever)
4488 {
4489 int timed_out;
4490
4491 timed_out = getpkt_sane (buf, sizeof_buf, forever);
4492 }
4493
4494
4495 /* Read a packet from the remote machine, with error checking, and
4496 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
4497 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
4498 rather than timing out; this is used (in synchronous mode) to wait
4499 for a target that is is executing user code to stop. If FOREVER ==
4500 0, this function is allowed to time out gracefully and return an
4501 indication of this to the caller. Otherwise return the number
4502 of bytes read. */
4503 static int
4504 getpkt_sane (char **buf, long *sizeof_buf, int forever)
4505 {
4506 int c;
4507 int tries;
4508 int timeout;
4509 int val;
4510
4511 strcpy (*buf, "timeout");
4512
4513 if (forever)
4514 {
4515 timeout = watchdog > 0 ? watchdog : -1;
4516 }
4517
4518 else
4519 timeout = remote_timeout;
4520
4521 #define MAX_TRIES 3
4522
4523 for (tries = 1; tries <= MAX_TRIES; tries++)
4524 {
4525 /* This can loop forever if the remote side sends us characters
4526 continuously, but if it pauses, we'll get a zero from
4527 readchar because of timeout. Then we'll count that as a
4528 retry. */
4529
4530 /* Note that we will only wait forever prior to the start of a
4531 packet. After that, we expect characters to arrive at a
4532 brisk pace. They should show up within remote_timeout
4533 intervals. */
4534
4535 do
4536 {
4537 c = readchar (timeout);
4538
4539 if (c == SERIAL_TIMEOUT)
4540 {
4541 if (forever) /* Watchdog went off? Kill the target. */
4542 {
4543 QUIT;
4544 target_mourn_inferior ();
4545 error (_("Watchdog has expired. Target detached."));
4546 }
4547 if (remote_debug)
4548 fputs_filtered ("Timed out.\n", gdb_stdlog);
4549 goto retry;
4550 }
4551 }
4552 while (c != '$');
4553
4554 /* We've found the start of a packet, now collect the data. */
4555
4556 val = read_frame (buf, sizeof_buf);
4557
4558 if (val >= 0)
4559 {
4560 if (remote_debug)
4561 {
4562 fprintf_unfiltered (gdb_stdlog, "Packet received: ");
4563 fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
4564 fprintf_unfiltered (gdb_stdlog, "\n");
4565 }
4566 serial_write (remote_desc, "+", 1);
4567 return val;
4568 }
4569
4570 /* Try the whole thing again. */
4571 retry:
4572 serial_write (remote_desc, "-", 1);
4573 }
4574
4575 /* We have tried hard enough, and just can't receive the packet.
4576 Give up. */
4577
4578 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
4579 serial_write (remote_desc, "+", 1);
4580 return -1;
4581 }
4582 \f
4583 static void
4584 remote_kill (void)
4585 {
4586 /* For some mysterious reason, wait_for_inferior calls kill instead of
4587 mourn after it gets TARGET_WAITKIND_SIGNALLED. Work around it. */
4588 if (kill_kludge)
4589 {
4590 kill_kludge = 0;
4591 target_mourn_inferior ();
4592 return;
4593 }
4594
4595 /* Use catch_errors so the user can quit from gdb even when we aren't on
4596 speaking terms with the remote system. */
4597 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
4598
4599 /* Don't wait for it to die. I'm not really sure it matters whether
4600 we do or not. For the existing stubs, kill is a noop. */
4601 target_mourn_inferior ();
4602 }
4603
4604 /* Async version of remote_kill. */
4605 static void
4606 remote_async_kill (void)
4607 {
4608 /* Unregister the file descriptor from the event loop. */
4609 if (target_is_async_p ())
4610 serial_async (remote_desc, NULL, 0);
4611
4612 /* For some mysterious reason, wait_for_inferior calls kill instead of
4613 mourn after it gets TARGET_WAITKIND_SIGNALLED. Work around it. */
4614 if (kill_kludge)
4615 {
4616 kill_kludge = 0;
4617 target_mourn_inferior ();
4618 return;
4619 }
4620
4621 /* Use catch_errors so the user can quit from gdb even when we
4622 aren't on speaking terms with the remote system. */
4623 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
4624
4625 /* Don't wait for it to die. I'm not really sure it matters whether
4626 we do or not. For the existing stubs, kill is a noop. */
4627 target_mourn_inferior ();
4628 }
4629
4630 static void
4631 remote_mourn (void)
4632 {
4633 remote_mourn_1 (&remote_ops);
4634 }
4635
4636 static void
4637 remote_async_mourn (void)
4638 {
4639 remote_mourn_1 (&remote_async_ops);
4640 }
4641
4642 static void
4643 extended_remote_mourn (void)
4644 {
4645 /* We do _not_ want to mourn the target like this; this will
4646 remove the extended remote target from the target stack,
4647 and the next time the user says "run" it'll fail.
4648
4649 FIXME: What is the right thing to do here? */
4650 #if 0
4651 remote_mourn_1 (&extended_remote_ops);
4652 #endif
4653 }
4654
4655 /* Worker function for remote_mourn. */
4656 static void
4657 remote_mourn_1 (struct target_ops *target)
4658 {
4659 unpush_target (target);
4660 generic_mourn_inferior ();
4661 }
4662
4663 /* In the extended protocol we want to be able to do things like
4664 "run" and have them basically work as expected. So we need
4665 a special create_inferior function.
4666
4667 FIXME: One day add support for changing the exec file
4668 we're debugging, arguments and an environment. */
4669
4670 static void
4671 extended_remote_create_inferior (char *exec_file, char *args,
4672 char **env, int from_tty)
4673 {
4674 /* Rip out the breakpoints; we'll reinsert them after restarting
4675 the remote server. */
4676 remove_breakpoints ();
4677
4678 /* Now restart the remote server. */
4679 extended_remote_restart ();
4680
4681 /* Now put the breakpoints back in. This way we're safe if the
4682 restart function works via a unix fork on the remote side. */
4683 insert_breakpoints ();
4684
4685 /* Clean up from the last time we were running. */
4686 clear_proceed_status ();
4687 }
4688
4689 /* Async version of extended_remote_create_inferior. */
4690 static void
4691 extended_remote_async_create_inferior (char *exec_file, char *args,
4692 char **env, int from_tty)
4693 {
4694 /* Rip out the breakpoints; we'll reinsert them after restarting
4695 the remote server. */
4696 remove_breakpoints ();
4697
4698 /* If running asynchronously, register the target file descriptor
4699 with the event loop. */
4700 if (target_can_async_p ())
4701 target_async (inferior_event_handler, 0);
4702
4703 /* Now restart the remote server. */
4704 extended_remote_restart ();
4705
4706 /* Now put the breakpoints back in. This way we're safe if the
4707 restart function works via a unix fork on the remote side. */
4708 insert_breakpoints ();
4709
4710 /* Clean up from the last time we were running. */
4711 clear_proceed_status ();
4712 }
4713 \f
4714
4715 /* On some machines, e.g. 68k, we may use a different breakpoint
4716 instruction than other targets; in those use
4717 DEPRECATED_REMOTE_BREAKPOINT instead of just BREAKPOINT_FROM_PC.
4718 Also, bi-endian targets may define
4719 DEPRECATED_LITTLE_REMOTE_BREAKPOINT and
4720 DEPRECATED_BIG_REMOTE_BREAKPOINT. If none of these are defined, we
4721 just call the standard routines that are in mem-break.c. */
4722
4723 /* NOTE: cagney/2003-06-08: This is silly. A remote and simulator
4724 target should use an identical BREAKPOINT_FROM_PC. As for native,
4725 the ARCH-OS-tdep.c code can override the default. */
4726
4727 #if defined (DEPRECATED_LITTLE_REMOTE_BREAKPOINT) && defined (DEPRECATED_BIG_REMOTE_BREAKPOINT) && !defined(DEPRECATED_REMOTE_BREAKPOINT)
4728 #define DEPRECATED_REMOTE_BREAKPOINT
4729 #endif
4730
4731 #ifdef DEPRECATED_REMOTE_BREAKPOINT
4732
4733 /* If the target isn't bi-endian, just pretend it is. */
4734 #if !defined (DEPRECATED_LITTLE_REMOTE_BREAKPOINT) && !defined (DEPRECATED_BIG_REMOTE_BREAKPOINT)
4735 #define DEPRECATED_LITTLE_REMOTE_BREAKPOINT DEPRECATED_REMOTE_BREAKPOINT
4736 #define DEPRECATED_BIG_REMOTE_BREAKPOINT DEPRECATED_REMOTE_BREAKPOINT
4737 #endif
4738
4739 static unsigned char big_break_insn[] = DEPRECATED_BIG_REMOTE_BREAKPOINT;
4740 static unsigned char little_break_insn[] = DEPRECATED_LITTLE_REMOTE_BREAKPOINT;
4741
4742 #endif /* DEPRECATED_REMOTE_BREAKPOINT */
4743
4744 /* Insert a breakpoint. On targets that have software breakpoint
4745 support, we ask the remote target to do the work; on targets
4746 which don't, we insert a traditional memory breakpoint. */
4747
4748 static int
4749 remote_insert_breakpoint (struct bp_target_info *bp_tgt)
4750 {
4751 CORE_ADDR addr = bp_tgt->placed_address;
4752 struct remote_state *rs = get_remote_state ();
4753 #ifdef DEPRECATED_REMOTE_BREAKPOINT
4754 int val;
4755 #endif
4756
4757 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
4758 If it succeeds, then set the support to PACKET_ENABLE. If it
4759 fails, and the user has explicitly requested the Z support then
4760 report an error, otherwise, mark it disabled and go on. */
4761
4762 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
4763 {
4764 char *p = rs->buf;
4765
4766 *(p++) = 'Z';
4767 *(p++) = '0';
4768 *(p++) = ',';
4769 BREAKPOINT_FROM_PC (&bp_tgt->placed_address, &bp_tgt->placed_size);
4770 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
4771 p += hexnumstr (p, addr);
4772 sprintf (p, ",%d", bp_tgt->placed_size);
4773
4774 putpkt (rs->buf);
4775 getpkt (&rs->buf, &rs->buf_size, 0);
4776
4777 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
4778 {
4779 case PACKET_ERROR:
4780 return -1;
4781 case PACKET_OK:
4782 return 0;
4783 case PACKET_UNKNOWN:
4784 break;
4785 }
4786 }
4787
4788 #ifdef DEPRECATED_REMOTE_BREAKPOINT
4789 bp_tgt->placed_size = bp_tgt->shadow_len = sizeof big_break_insn;
4790 val = target_read_memory (addr, bp_tgt->shadow_contents, bp_tgt->shadow_len);
4791
4792 if (val == 0)
4793 {
4794 if (TARGET_BYTE_ORDER == BFD_ENDIAN_BIG)
4795 val = target_write_memory (addr, (char *) big_break_insn,
4796 sizeof big_break_insn);
4797 else
4798 val = target_write_memory (addr, (char *) little_break_insn,
4799 sizeof little_break_insn);
4800 }
4801
4802 return val;
4803 #else
4804 return memory_insert_breakpoint (bp_tgt);
4805 #endif /* DEPRECATED_REMOTE_BREAKPOINT */
4806 }
4807
4808 static int
4809 remote_remove_breakpoint (struct bp_target_info *bp_tgt)
4810 {
4811 CORE_ADDR addr = bp_tgt->placed_address;
4812 struct remote_state *rs = get_remote_state ();
4813 int bp_size;
4814
4815 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
4816 {
4817 char *p = rs->buf;
4818
4819 *(p++) = 'z';
4820 *(p++) = '0';
4821 *(p++) = ',';
4822
4823 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
4824 p += hexnumstr (p, addr);
4825 sprintf (p, ",%d", bp_tgt->placed_size);
4826
4827 putpkt (rs->buf);
4828 getpkt (&rs->buf, &rs->buf_size, 0);
4829
4830 return (rs->buf[0] == 'E');
4831 }
4832
4833 #ifdef DEPRECATED_REMOTE_BREAKPOINT
4834 return target_write_memory (bp_tgt->placed_address, bp_tgt->shadow_contents,
4835 bp_tgt->shadow_len);
4836 #else
4837 return memory_remove_breakpoint (bp_tgt);
4838 #endif /* DEPRECATED_REMOTE_BREAKPOINT */
4839 }
4840
4841 static int
4842 watchpoint_to_Z_packet (int type)
4843 {
4844 switch (type)
4845 {
4846 case hw_write:
4847 return Z_PACKET_WRITE_WP;
4848 break;
4849 case hw_read:
4850 return Z_PACKET_READ_WP;
4851 break;
4852 case hw_access:
4853 return Z_PACKET_ACCESS_WP;
4854 break;
4855 default:
4856 internal_error (__FILE__, __LINE__,
4857 _("hw_bp_to_z: bad watchpoint type %d"), type);
4858 }
4859 }
4860
4861 static int
4862 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
4863 {
4864 struct remote_state *rs = get_remote_state ();
4865 char *p;
4866 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
4867
4868 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
4869 return -1;
4870
4871 sprintf (rs->buf, "Z%x,", packet);
4872 p = strchr (rs->buf, '\0');
4873 addr = remote_address_masked (addr);
4874 p += hexnumstr (p, (ULONGEST) addr);
4875 sprintf (p, ",%x", len);
4876
4877 putpkt (rs->buf);
4878 getpkt (&rs->buf, &rs->buf_size, 0);
4879
4880 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
4881 {
4882 case PACKET_ERROR:
4883 case PACKET_UNKNOWN:
4884 return -1;
4885 case PACKET_OK:
4886 return 0;
4887 }
4888 internal_error (__FILE__, __LINE__,
4889 _("remote_insert_watchpoint: reached end of function"));
4890 }
4891
4892
4893 static int
4894 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
4895 {
4896 struct remote_state *rs = get_remote_state ();
4897 char *p;
4898 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
4899
4900 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
4901 return -1;
4902
4903 sprintf (rs->buf, "z%x,", packet);
4904 p = strchr (rs->buf, '\0');
4905 addr = remote_address_masked (addr);
4906 p += hexnumstr (p, (ULONGEST) addr);
4907 sprintf (p, ",%x", len);
4908 putpkt (rs->buf);
4909 getpkt (&rs->buf, &rs->buf_size, 0);
4910
4911 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
4912 {
4913 case PACKET_ERROR:
4914 case PACKET_UNKNOWN:
4915 return -1;
4916 case PACKET_OK:
4917 return 0;
4918 }
4919 internal_error (__FILE__, __LINE__,
4920 _("remote_remove_watchpoint: reached end of function"));
4921 }
4922
4923
4924 int remote_hw_watchpoint_limit = -1;
4925 int remote_hw_breakpoint_limit = -1;
4926
4927 static int
4928 remote_check_watch_resources (int type, int cnt, int ot)
4929 {
4930 if (type == bp_hardware_breakpoint)
4931 {
4932 if (remote_hw_breakpoint_limit == 0)
4933 return 0;
4934 else if (remote_hw_breakpoint_limit < 0)
4935 return 1;
4936 else if (cnt <= remote_hw_breakpoint_limit)
4937 return 1;
4938 }
4939 else
4940 {
4941 if (remote_hw_watchpoint_limit == 0)
4942 return 0;
4943 else if (remote_hw_watchpoint_limit < 0)
4944 return 1;
4945 else if (ot)
4946 return -1;
4947 else if (cnt <= remote_hw_watchpoint_limit)
4948 return 1;
4949 }
4950 return -1;
4951 }
4952
4953 static int
4954 remote_stopped_by_watchpoint (void)
4955 {
4956 return remote_stopped_by_watchpoint_p;
4957 }
4958
4959 extern int stepped_after_stopped_by_watchpoint;
4960
4961 static int
4962 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
4963 {
4964 int rc = 0;
4965 if (remote_stopped_by_watchpoint ()
4966 || stepped_after_stopped_by_watchpoint)
4967 {
4968 *addr_p = remote_watch_data_address;
4969 rc = 1;
4970 }
4971
4972 return rc;
4973 }
4974
4975
4976 static int
4977 remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
4978 {
4979 CORE_ADDR addr;
4980 struct remote_state *rs = get_remote_state ();
4981 char *p = rs->buf;
4982
4983 /* The length field should be set to the size of a breakpoint
4984 instruction, even though we aren't inserting one ourselves. */
4985
4986 BREAKPOINT_FROM_PC (&bp_tgt->placed_address, &bp_tgt->placed_size);
4987
4988 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
4989 return -1;
4990
4991 *(p++) = 'Z';
4992 *(p++) = '1';
4993 *(p++) = ',';
4994
4995 addr = remote_address_masked (bp_tgt->placed_address);
4996 p += hexnumstr (p, (ULONGEST) addr);
4997 sprintf (p, ",%x", bp_tgt->placed_size);
4998
4999 putpkt (rs->buf);
5000 getpkt (&rs->buf, &rs->buf_size, 0);
5001
5002 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5003 {
5004 case PACKET_ERROR:
5005 case PACKET_UNKNOWN:
5006 return -1;
5007 case PACKET_OK:
5008 return 0;
5009 }
5010 internal_error (__FILE__, __LINE__,
5011 _("remote_insert_hw_breakpoint: reached end of function"));
5012 }
5013
5014
5015 static int
5016 remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
5017 {
5018 CORE_ADDR addr;
5019 struct remote_state *rs = get_remote_state ();
5020 char *p = rs->buf;
5021
5022 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5023 return -1;
5024
5025 *(p++) = 'z';
5026 *(p++) = '1';
5027 *(p++) = ',';
5028
5029 addr = remote_address_masked (bp_tgt->placed_address);
5030 p += hexnumstr (p, (ULONGEST) addr);
5031 sprintf (p, ",%x", bp_tgt->placed_size);
5032
5033 putpkt (rs->buf);
5034 getpkt (&rs->buf, &rs->buf_size, 0);
5035
5036 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5037 {
5038 case PACKET_ERROR:
5039 case PACKET_UNKNOWN:
5040 return -1;
5041 case PACKET_OK:
5042 return 0;
5043 }
5044 internal_error (__FILE__, __LINE__,
5045 _("remote_remove_hw_breakpoint: reached end of function"));
5046 }
5047
5048 /* Some targets are only capable of doing downloads, and afterwards
5049 they switch to the remote serial protocol. This function provides
5050 a clean way to get from the download target to the remote target.
5051 It's basically just a wrapper so that we don't have to expose any
5052 of the internal workings of remote.c.
5053
5054 Prior to calling this routine, you should shutdown the current
5055 target code, else you will get the "A program is being debugged
5056 already..." message. Usually a call to pop_target() suffices. */
5057
5058 void
5059 push_remote_target (char *name, int from_tty)
5060 {
5061 printf_filtered (_("Switching to remote protocol\n"));
5062 remote_open (name, from_tty);
5063 }
5064
5065 /* Table used by the crc32 function to calcuate the checksum. */
5066
5067 static unsigned long crc32_table[256] =
5068 {0, 0};
5069
5070 static unsigned long
5071 crc32 (unsigned char *buf, int len, unsigned int crc)
5072 {
5073 if (!crc32_table[1])
5074 {
5075 /* Initialize the CRC table and the decoding table. */
5076 int i, j;
5077 unsigned int c;
5078
5079 for (i = 0; i < 256; i++)
5080 {
5081 for (c = i << 24, j = 8; j > 0; --j)
5082 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
5083 crc32_table[i] = c;
5084 }
5085 }
5086
5087 while (len--)
5088 {
5089 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
5090 buf++;
5091 }
5092 return crc;
5093 }
5094
5095 /* compare-sections command
5096
5097 With no arguments, compares each loadable section in the exec bfd
5098 with the same memory range on the target, and reports mismatches.
5099 Useful for verifying the image on the target against the exec file.
5100 Depends on the target understanding the new "qCRC:" request. */
5101
5102 /* FIXME: cagney/1999-10-26: This command should be broken down into a
5103 target method (target verify memory) and generic version of the
5104 actual command. This will allow other high-level code (especially
5105 generic_load()) to make use of this target functionality. */
5106
5107 static void
5108 compare_sections_command (char *args, int from_tty)
5109 {
5110 struct remote_state *rs = get_remote_state ();
5111 asection *s;
5112 unsigned long host_crc, target_crc;
5113 extern bfd *exec_bfd;
5114 struct cleanup *old_chain;
5115 char *tmp;
5116 char *sectdata;
5117 const char *sectname;
5118 bfd_size_type size;
5119 bfd_vma lma;
5120 int matched = 0;
5121 int mismatched = 0;
5122
5123 if (!exec_bfd)
5124 error (_("command cannot be used without an exec file"));
5125 if (!current_target.to_shortname ||
5126 strcmp (current_target.to_shortname, "remote") != 0)
5127 error (_("command can only be used with remote target"));
5128
5129 for (s = exec_bfd->sections; s; s = s->next)
5130 {
5131 if (!(s->flags & SEC_LOAD))
5132 continue; /* skip non-loadable section */
5133
5134 size = bfd_get_section_size (s);
5135 if (size == 0)
5136 continue; /* skip zero-length section */
5137
5138 sectname = bfd_get_section_name (exec_bfd, s);
5139 if (args && strcmp (args, sectname) != 0)
5140 continue; /* not the section selected by user */
5141
5142 matched = 1; /* do this section */
5143 lma = s->lma;
5144 /* FIXME: assumes lma can fit into long. */
5145 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
5146 (long) lma, (long) size);
5147 putpkt (rs->buf);
5148
5149 /* Be clever; compute the host_crc before waiting for target
5150 reply. */
5151 sectdata = xmalloc (size);
5152 old_chain = make_cleanup (xfree, sectdata);
5153 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5154 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
5155
5156 getpkt (&rs->buf, &rs->buf_size, 0);
5157 if (rs->buf[0] == 'E')
5158 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
5159 sectname, paddr (lma), paddr (lma + size));
5160 if (rs->buf[0] != 'C')
5161 error (_("remote target does not support this operation"));
5162
5163 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
5164 target_crc = target_crc * 16 + fromhex (*tmp);
5165
5166 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
5167 sectname, paddr (lma), paddr (lma + size));
5168 if (host_crc == target_crc)
5169 printf_filtered ("matched.\n");
5170 else
5171 {
5172 printf_filtered ("MIS-MATCHED!\n");
5173 mismatched++;
5174 }
5175
5176 do_cleanups (old_chain);
5177 }
5178 if (mismatched > 0)
5179 warning (_("One or more sections of the remote executable does not match\n\
5180 the loaded file\n"));
5181 if (args && !matched)
5182 printf_filtered (_("No loaded section named '%s'.\n"), args);
5183 }
5184
5185 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
5186 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
5187 number of bytes read is returned, or 0 for EOF, or -1 for error.
5188 The number of bytes read may be less than LEN without indicating an
5189 EOF. PACKET is checked and updated to indicate whether the remote
5190 target supports this object. */
5191
5192 static LONGEST
5193 remote_read_qxfer (struct target_ops *ops, const char *object_name,
5194 const char *annex,
5195 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
5196 struct packet_config *packet)
5197 {
5198 static char *finished_object;
5199 static char *finished_annex;
5200 static ULONGEST finished_offset;
5201
5202 struct remote_state *rs = get_remote_state ();
5203 unsigned int total = 0;
5204 LONGEST i, n, packet_len;
5205
5206 if (packet->support == PACKET_DISABLE)
5207 return -1;
5208
5209 /* Check whether we've cached an end-of-object packet that matches
5210 this request. */
5211 if (finished_object)
5212 {
5213 if (strcmp (object_name, finished_object) == 0
5214 && strcmp (annex ? annex : "", finished_annex) == 0
5215 && offset == finished_offset)
5216 return 0;
5217
5218 /* Otherwise, we're now reading something different. Discard
5219 the cache. */
5220 xfree (finished_object);
5221 xfree (finished_annex);
5222 finished_object = NULL;
5223 finished_annex = NULL;
5224 }
5225
5226 /* Request only enough to fit in a single packet. The actual data
5227 may not, since we don't know how much of it will need to be escaped;
5228 the target is free to respond with slightly less data. We subtract
5229 five to account for the response type and the protocol frame. */
5230 n = min (get_remote_packet_size () - 5, len);
5231 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
5232 object_name, annex ? annex : "",
5233 phex_nz (offset, sizeof offset),
5234 phex_nz (n, sizeof n));
5235 i = putpkt (rs->buf);
5236 if (i < 0)
5237 return -1;
5238
5239 rs->buf[0] = '\0';
5240 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
5241 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
5242 return -1;
5243
5244 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
5245 error (_("Unknown remote qXfer reply: %s"), rs->buf);
5246
5247 /* 'm' means there is (or at least might be) more data after this
5248 batch. That does not make sense unless there's at least one byte
5249 of data in this reply. */
5250 if (rs->buf[0] == 'm' && packet_len == 1)
5251 error (_("Remote qXfer reply contained no data."));
5252
5253 /* Got some data. */
5254 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
5255
5256 /* 'l' is an EOF marker, possibly including a final block of data,
5257 or possibly empty. Record it to bypass the next read, if one is
5258 issued. */
5259 if (rs->buf[0] == 'l')
5260 {
5261 finished_object = xstrdup (object_name);
5262 finished_annex = xstrdup (annex ? annex : "");
5263 finished_offset = offset + i;
5264 }
5265
5266 return i;
5267 }
5268
5269 static LONGEST
5270 remote_xfer_partial (struct target_ops *ops, enum target_object object,
5271 const char *annex, gdb_byte *readbuf,
5272 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
5273 {
5274 struct remote_state *rs = get_remote_state ();
5275 int i;
5276 char *p2;
5277 char query_type;
5278
5279 /* Handle memory using the standard memory routines. */
5280 if (object == TARGET_OBJECT_MEMORY)
5281 {
5282 int xfered;
5283 errno = 0;
5284
5285 if (writebuf != NULL)
5286 xfered = remote_write_bytes (offset, writebuf, len);
5287 else
5288 xfered = remote_read_bytes (offset, readbuf, len);
5289
5290 if (xfered > 0)
5291 return xfered;
5292 else if (xfered == 0 && errno == 0)
5293 return 0;
5294 else
5295 return -1;
5296 }
5297
5298 /* Only handle reads. */
5299 if (writebuf != NULL || readbuf == NULL)
5300 return -1;
5301
5302 /* Map pre-existing objects onto letters. DO NOT do this for new
5303 objects!!! Instead specify new query packets. */
5304 switch (object)
5305 {
5306 case TARGET_OBJECT_AVR:
5307 query_type = 'R';
5308 break;
5309
5310 case TARGET_OBJECT_AUXV:
5311 gdb_assert (annex == NULL);
5312 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
5313 &remote_protocol_packets[PACKET_qXfer_auxv]);
5314
5315 default:
5316 return -1;
5317 }
5318
5319 /* Note: a zero OFFSET and LEN can be used to query the minimum
5320 buffer size. */
5321 if (offset == 0 && len == 0)
5322 return (get_remote_packet_size ());
5323 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
5324 large enough let the caller deal with it. */
5325 if (len < get_remote_packet_size ())
5326 return -1;
5327 len = get_remote_packet_size ();
5328
5329 /* Except for querying the minimum buffer size, target must be open. */
5330 if (!remote_desc)
5331 error (_("remote query is only available after target open"));
5332
5333 gdb_assert (annex != NULL);
5334 gdb_assert (readbuf != NULL);
5335
5336 p2 = rs->buf;
5337 *p2++ = 'q';
5338 *p2++ = query_type;
5339
5340 /* We used one buffer char for the remote protocol q command and
5341 another for the query type. As the remote protocol encapsulation
5342 uses 4 chars plus one extra in case we are debugging
5343 (remote_debug), we have PBUFZIZ - 7 left to pack the query
5344 string. */
5345 i = 0;
5346 while (annex[i] && (i < (get_remote_packet_size () - 8)))
5347 {
5348 /* Bad caller may have sent forbidden characters. */
5349 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
5350 *p2++ = annex[i];
5351 i++;
5352 }
5353 *p2 = '\0';
5354 gdb_assert (annex[i] == '\0');
5355
5356 i = putpkt (rs->buf);
5357 if (i < 0)
5358 return i;
5359
5360 getpkt (&rs->buf, &rs->buf_size, 0);
5361 strcpy ((char *) readbuf, rs->buf);
5362
5363 return strlen ((char *) readbuf);
5364 }
5365
5366 static void
5367 remote_rcmd (char *command,
5368 struct ui_file *outbuf)
5369 {
5370 struct remote_state *rs = get_remote_state ();
5371 char *p = rs->buf;
5372
5373 if (!remote_desc)
5374 error (_("remote rcmd is only available after target open"));
5375
5376 /* Send a NULL command across as an empty command. */
5377 if (command == NULL)
5378 command = "";
5379
5380 /* The query prefix. */
5381 strcpy (rs->buf, "qRcmd,");
5382 p = strchr (rs->buf, '\0');
5383
5384 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
5385 error (_("\"monitor\" command ``%s'' is too long."), command);
5386
5387 /* Encode the actual command. */
5388 bin2hex ((gdb_byte *) command, p, 0);
5389
5390 if (putpkt (rs->buf) < 0)
5391 error (_("Communication problem with target."));
5392
5393 /* get/display the response */
5394 while (1)
5395 {
5396 char *buf;
5397
5398 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
5399 rs->buf[0] = '\0';
5400 getpkt (&rs->buf, &rs->buf_size, 0);
5401 buf = rs->buf;
5402 if (buf[0] == '\0')
5403 error (_("Target does not support this command."));
5404 if (buf[0] == 'O' && buf[1] != 'K')
5405 {
5406 remote_console_output (buf + 1); /* 'O' message from stub. */
5407 continue;
5408 }
5409 if (strcmp (buf, "OK") == 0)
5410 break;
5411 if (strlen (buf) == 3 && buf[0] == 'E'
5412 && isdigit (buf[1]) && isdigit (buf[2]))
5413 {
5414 error (_("Protocol error with Rcmd"));
5415 }
5416 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
5417 {
5418 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
5419 fputc_unfiltered (c, outbuf);
5420 }
5421 break;
5422 }
5423 }
5424
5425 static void
5426 packet_command (char *args, int from_tty)
5427 {
5428 struct remote_state *rs = get_remote_state ();
5429
5430 if (!remote_desc)
5431 error (_("command can only be used with remote target"));
5432
5433 if (!args)
5434 error (_("remote-packet command requires packet text as argument"));
5435
5436 puts_filtered ("sending: ");
5437 print_packet (args);
5438 puts_filtered ("\n");
5439 putpkt (args);
5440
5441 getpkt (&rs->buf, &rs->buf_size, 0);
5442 puts_filtered ("received: ");
5443 print_packet (rs->buf);
5444 puts_filtered ("\n");
5445 }
5446
5447 #if 0
5448 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
5449
5450 static void display_thread_info (struct gdb_ext_thread_info *info);
5451
5452 static void threadset_test_cmd (char *cmd, int tty);
5453
5454 static void threadalive_test (char *cmd, int tty);
5455
5456 static void threadlist_test_cmd (char *cmd, int tty);
5457
5458 int get_and_display_threadinfo (threadref *ref);
5459
5460 static void threadinfo_test_cmd (char *cmd, int tty);
5461
5462 static int thread_display_step (threadref *ref, void *context);
5463
5464 static void threadlist_update_test_cmd (char *cmd, int tty);
5465
5466 static void init_remote_threadtests (void);
5467
5468 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
5469
5470 static void
5471 threadset_test_cmd (char *cmd, int tty)
5472 {
5473 int sample_thread = SAMPLE_THREAD;
5474
5475 printf_filtered (_("Remote threadset test\n"));
5476 set_thread (sample_thread, 1);
5477 }
5478
5479
5480 static void
5481 threadalive_test (char *cmd, int tty)
5482 {
5483 int sample_thread = SAMPLE_THREAD;
5484
5485 if (remote_thread_alive (pid_to_ptid (sample_thread)))
5486 printf_filtered ("PASS: Thread alive test\n");
5487 else
5488 printf_filtered ("FAIL: Thread alive test\n");
5489 }
5490
5491 void output_threadid (char *title, threadref *ref);
5492
5493 void
5494 output_threadid (char *title, threadref *ref)
5495 {
5496 char hexid[20];
5497
5498 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
5499 hexid[16] = 0;
5500 printf_filtered ("%s %s\n", title, (&hexid[0]));
5501 }
5502
5503 static void
5504 threadlist_test_cmd (char *cmd, int tty)
5505 {
5506 int startflag = 1;
5507 threadref nextthread;
5508 int done, result_count;
5509 threadref threadlist[3];
5510
5511 printf_filtered ("Remote Threadlist test\n");
5512 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
5513 &result_count, &threadlist[0]))
5514 printf_filtered ("FAIL: threadlist test\n");
5515 else
5516 {
5517 threadref *scan = threadlist;
5518 threadref *limit = scan + result_count;
5519
5520 while (scan < limit)
5521 output_threadid (" thread ", scan++);
5522 }
5523 }
5524
5525 void
5526 display_thread_info (struct gdb_ext_thread_info *info)
5527 {
5528 output_threadid ("Threadid: ", &info->threadid);
5529 printf_filtered ("Name: %s\n ", info->shortname);
5530 printf_filtered ("State: %s\n", info->display);
5531 printf_filtered ("other: %s\n\n", info->more_display);
5532 }
5533
5534 int
5535 get_and_display_threadinfo (threadref *ref)
5536 {
5537 int result;
5538 int set;
5539 struct gdb_ext_thread_info threadinfo;
5540
5541 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
5542 | TAG_MOREDISPLAY | TAG_DISPLAY;
5543 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
5544 display_thread_info (&threadinfo);
5545 return result;
5546 }
5547
5548 static void
5549 threadinfo_test_cmd (char *cmd, int tty)
5550 {
5551 int athread = SAMPLE_THREAD;
5552 threadref thread;
5553 int set;
5554
5555 int_to_threadref (&thread, athread);
5556 printf_filtered ("Remote Threadinfo test\n");
5557 if (!get_and_display_threadinfo (&thread))
5558 printf_filtered ("FAIL cannot get thread info\n");
5559 }
5560
5561 static int
5562 thread_display_step (threadref *ref, void *context)
5563 {
5564 /* output_threadid(" threadstep ",ref); *//* simple test */
5565 return get_and_display_threadinfo (ref);
5566 }
5567
5568 static void
5569 threadlist_update_test_cmd (char *cmd, int tty)
5570 {
5571 printf_filtered ("Remote Threadlist update test\n");
5572 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
5573 }
5574
5575 static void
5576 init_remote_threadtests (void)
5577 {
5578 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
5579 Fetch and print the remote list of thread identifiers, one pkt only"));
5580 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
5581 _("Fetch and display info about one thread"));
5582 add_com ("tset", class_obscure, threadset_test_cmd,
5583 _("Test setting to a different thread"));
5584 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
5585 _("Iterate through updating all remote thread info"));
5586 add_com ("talive", class_obscure, threadalive_test,
5587 _(" Remote thread alive test "));
5588 }
5589
5590 #endif /* 0 */
5591
5592 /* Convert a thread ID to a string. Returns the string in a static
5593 buffer. */
5594
5595 static char *
5596 remote_pid_to_str (ptid_t ptid)
5597 {
5598 static char buf[32];
5599
5600 xsnprintf (buf, sizeof buf, "thread %d", ptid_get_pid (ptid));
5601 return buf;
5602 }
5603
5604 /* Get the address of the thread local variable in OBJFILE which is
5605 stored at OFFSET within the thread local storage for thread PTID. */
5606
5607 static CORE_ADDR
5608 remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
5609 {
5610 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
5611 {
5612 struct remote_state *rs = get_remote_state ();
5613 char *p = rs->buf;
5614 enum packet_result result;
5615
5616 strcpy (p, "qGetTLSAddr:");
5617 p += strlen (p);
5618 p += hexnumstr (p, PIDGET (ptid));
5619 *p++ = ',';
5620 p += hexnumstr (p, offset);
5621 *p++ = ',';
5622 p += hexnumstr (p, lm);
5623 *p++ = '\0';
5624
5625 putpkt (rs->buf);
5626 getpkt (&rs->buf, &rs->buf_size, 0);
5627 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
5628 if (result == PACKET_OK)
5629 {
5630 ULONGEST result;
5631
5632 unpack_varlen_hex (rs->buf, &result);
5633 return result;
5634 }
5635 else if (result == PACKET_UNKNOWN)
5636 throw_error (TLS_GENERIC_ERROR,
5637 _("Remote target doesn't support qGetTLSAddr packet"));
5638 else
5639 throw_error (TLS_GENERIC_ERROR,
5640 _("Remote target failed to process qGetTLSAddr request"));
5641 }
5642 else
5643 throw_error (TLS_GENERIC_ERROR,
5644 _("TLS not supported or disabled on this target"));
5645 /* Not reached. */
5646 return 0;
5647 }
5648
5649 static void
5650 init_remote_ops (void)
5651 {
5652 remote_ops.to_shortname = "remote";
5653 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
5654 remote_ops.to_doc =
5655 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
5656 Specify the serial device it is connected to\n\
5657 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
5658 remote_ops.to_open = remote_open;
5659 remote_ops.to_close = remote_close;
5660 remote_ops.to_detach = remote_detach;
5661 remote_ops.to_disconnect = remote_disconnect;
5662 remote_ops.to_resume = remote_resume;
5663 remote_ops.to_wait = remote_wait;
5664 remote_ops.to_fetch_registers = remote_fetch_registers;
5665 remote_ops.to_store_registers = remote_store_registers;
5666 remote_ops.to_prepare_to_store = remote_prepare_to_store;
5667 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
5668 remote_ops.to_files_info = remote_files_info;
5669 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
5670 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
5671 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
5672 remote_ops.to_stopped_data_address = remote_stopped_data_address;
5673 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
5674 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
5675 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
5676 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
5677 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
5678 remote_ops.to_kill = remote_kill;
5679 remote_ops.to_load = generic_load;
5680 remote_ops.to_mourn_inferior = remote_mourn;
5681 remote_ops.to_thread_alive = remote_thread_alive;
5682 remote_ops.to_find_new_threads = remote_threads_info;
5683 remote_ops.to_pid_to_str = remote_pid_to_str;
5684 remote_ops.to_extra_thread_info = remote_threads_extra_info;
5685 remote_ops.to_stop = remote_stop;
5686 remote_ops.to_xfer_partial = remote_xfer_partial;
5687 remote_ops.to_rcmd = remote_rcmd;
5688 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
5689 remote_ops.to_stratum = process_stratum;
5690 remote_ops.to_has_all_memory = 1;
5691 remote_ops.to_has_memory = 1;
5692 remote_ops.to_has_stack = 1;
5693 remote_ops.to_has_registers = 1;
5694 remote_ops.to_has_execution = 1;
5695 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
5696 remote_ops.to_magic = OPS_MAGIC;
5697 }
5698
5699 /* Set up the extended remote vector by making a copy of the standard
5700 remote vector and adding to it. */
5701
5702 static void
5703 init_extended_remote_ops (void)
5704 {
5705 extended_remote_ops = remote_ops;
5706
5707 extended_remote_ops.to_shortname = "extended-remote";
5708 extended_remote_ops.to_longname =
5709 "Extended remote serial target in gdb-specific protocol";
5710 extended_remote_ops.to_doc =
5711 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
5712 Specify the serial device it is connected to (e.g. /dev/ttya).",
5713 extended_remote_ops.to_open = extended_remote_open;
5714 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
5715 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
5716 }
5717
5718 static int
5719 remote_can_async_p (void)
5720 {
5721 /* We're async whenever the serial device is. */
5722 return (current_target.to_async_mask_value) && serial_can_async_p (remote_desc);
5723 }
5724
5725 static int
5726 remote_is_async_p (void)
5727 {
5728 /* We're async whenever the serial device is. */
5729 return (current_target.to_async_mask_value) && serial_is_async_p (remote_desc);
5730 }
5731
5732 /* Pass the SERIAL event on and up to the client. One day this code
5733 will be able to delay notifying the client of an event until the
5734 point where an entire packet has been received. */
5735
5736 static void (*async_client_callback) (enum inferior_event_type event_type,
5737 void *context);
5738 static void *async_client_context;
5739 static serial_event_ftype remote_async_serial_handler;
5740
5741 static void
5742 remote_async_serial_handler (struct serial *scb, void *context)
5743 {
5744 /* Don't propogate error information up to the client. Instead let
5745 the client find out about the error by querying the target. */
5746 async_client_callback (INF_REG_EVENT, async_client_context);
5747 }
5748
5749 static void
5750 remote_async (void (*callback) (enum inferior_event_type event_type,
5751 void *context), void *context)
5752 {
5753 if (current_target.to_async_mask_value == 0)
5754 internal_error (__FILE__, __LINE__,
5755 _("Calling remote_async when async is masked"));
5756
5757 if (callback != NULL)
5758 {
5759 serial_async (remote_desc, remote_async_serial_handler, NULL);
5760 async_client_callback = callback;
5761 async_client_context = context;
5762 }
5763 else
5764 serial_async (remote_desc, NULL, NULL);
5765 }
5766
5767 /* Target async and target extended-async.
5768
5769 This are temporary targets, until it is all tested. Eventually
5770 async support will be incorporated int the usual 'remote'
5771 target. */
5772
5773 static void
5774 init_remote_async_ops (void)
5775 {
5776 remote_async_ops.to_shortname = "async";
5777 remote_async_ops.to_longname =
5778 "Remote serial target in async version of the gdb-specific protocol";
5779 remote_async_ops.to_doc =
5780 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
5781 Specify the serial device it is connected to (e.g. /dev/ttya).";
5782 remote_async_ops.to_open = remote_async_open;
5783 remote_async_ops.to_close = remote_close;
5784 remote_async_ops.to_detach = remote_detach;
5785 remote_async_ops.to_disconnect = remote_disconnect;
5786 remote_async_ops.to_resume = remote_async_resume;
5787 remote_async_ops.to_wait = remote_async_wait;
5788 remote_async_ops.to_fetch_registers = remote_fetch_registers;
5789 remote_async_ops.to_store_registers = remote_store_registers;
5790 remote_async_ops.to_prepare_to_store = remote_prepare_to_store;
5791 remote_async_ops.deprecated_xfer_memory = remote_xfer_memory;
5792 remote_async_ops.to_files_info = remote_files_info;
5793 remote_async_ops.to_insert_breakpoint = remote_insert_breakpoint;
5794 remote_async_ops.to_remove_breakpoint = remote_remove_breakpoint;
5795 remote_async_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
5796 remote_async_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
5797 remote_async_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
5798 remote_async_ops.to_insert_watchpoint = remote_insert_watchpoint;
5799 remote_async_ops.to_remove_watchpoint = remote_remove_watchpoint;
5800 remote_async_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
5801 remote_async_ops.to_stopped_data_address = remote_stopped_data_address;
5802 remote_async_ops.to_terminal_inferior = remote_async_terminal_inferior;
5803 remote_async_ops.to_terminal_ours = remote_async_terminal_ours;
5804 remote_async_ops.to_kill = remote_async_kill;
5805 remote_async_ops.to_load = generic_load;
5806 remote_async_ops.to_mourn_inferior = remote_async_mourn;
5807 remote_async_ops.to_thread_alive = remote_thread_alive;
5808 remote_async_ops.to_find_new_threads = remote_threads_info;
5809 remote_async_ops.to_pid_to_str = remote_pid_to_str;
5810 remote_async_ops.to_extra_thread_info = remote_threads_extra_info;
5811 remote_async_ops.to_stop = remote_stop;
5812 remote_async_ops.to_xfer_partial = remote_xfer_partial;
5813 remote_async_ops.to_rcmd = remote_rcmd;
5814 remote_async_ops.to_stratum = process_stratum;
5815 remote_async_ops.to_has_all_memory = 1;
5816 remote_async_ops.to_has_memory = 1;
5817 remote_async_ops.to_has_stack = 1;
5818 remote_async_ops.to_has_registers = 1;
5819 remote_async_ops.to_has_execution = 1;
5820 remote_async_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
5821 remote_async_ops.to_can_async_p = remote_can_async_p;
5822 remote_async_ops.to_is_async_p = remote_is_async_p;
5823 remote_async_ops.to_async = remote_async;
5824 remote_async_ops.to_async_mask_value = 1;
5825 remote_async_ops.to_magic = OPS_MAGIC;
5826 }
5827
5828 /* Set up the async extended remote vector by making a copy of the standard
5829 remote vector and adding to it. */
5830
5831 static void
5832 init_extended_async_remote_ops (void)
5833 {
5834 extended_async_remote_ops = remote_async_ops;
5835
5836 extended_async_remote_ops.to_shortname = "extended-async";
5837 extended_async_remote_ops.to_longname =
5838 "Extended remote serial target in async gdb-specific protocol";
5839 extended_async_remote_ops.to_doc =
5840 "Use a remote computer via a serial line, using an async gdb-specific protocol.\n\
5841 Specify the serial device it is connected to (e.g. /dev/ttya).",
5842 extended_async_remote_ops.to_open = extended_remote_async_open;
5843 extended_async_remote_ops.to_create_inferior = extended_remote_async_create_inferior;
5844 extended_async_remote_ops.to_mourn_inferior = extended_remote_mourn;
5845 }
5846
5847 static void
5848 set_remote_cmd (char *args, int from_tty)
5849 {
5850 }
5851
5852 static void
5853 show_remote_cmd (char *args, int from_tty)
5854 {
5855 /* We can't just use cmd_show_list here, because we want to skip
5856 the redundant "show remote Z-packet". */
5857 struct cleanup *showlist_chain;
5858 struct cmd_list_element *list = remote_show_cmdlist;
5859
5860 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
5861 for (; list != NULL; list = list->next)
5862 if (strcmp (list->name, "Z-packet") == 0)
5863 continue;
5864 else if (list->type == show_cmd)
5865 {
5866 struct cleanup *option_chain
5867 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
5868 ui_out_field_string (uiout, "name", list->name);
5869 ui_out_text (uiout, ": ");
5870 do_setshow_command ((char *) NULL, from_tty, list);
5871 /* Close the tuple. */
5872 do_cleanups (option_chain);
5873 }
5874 }
5875
5876 static void
5877 build_remote_gdbarch_data (void)
5878 {
5879 remote_address_size = TARGET_ADDR_BIT;
5880 }
5881
5882 /* Saved pointer to previous owner of the new_objfile event. */
5883 static void (*remote_new_objfile_chain) (struct objfile *);
5884
5885 /* Function to be called whenever a new objfile (shlib) is detected. */
5886 static void
5887 remote_new_objfile (struct objfile *objfile)
5888 {
5889 if (remote_desc != 0) /* Have a remote connection. */
5890 {
5891 remote_check_symbols (objfile);
5892 }
5893 /* Call predecessor on chain, if any. */
5894 if (remote_new_objfile_chain != 0 &&
5895 remote_desc == 0)
5896 remote_new_objfile_chain (objfile);
5897 }
5898
5899 void
5900 _initialize_remote (void)
5901 {
5902 struct remote_state *rs;
5903
5904 /* architecture specific data */
5905 remote_gdbarch_data_handle =
5906 gdbarch_data_register_post_init (init_remote_state);
5907
5908 /* Old tacky stuff. NOTE: This comes after the remote protocol so
5909 that the remote protocol has been initialized. */
5910 DEPRECATED_REGISTER_GDBARCH_SWAP (remote_address_size);
5911 deprecated_register_gdbarch_swap (NULL, 0, build_remote_gdbarch_data);
5912
5913 /* Initialize the per-target state. At the moment there is only one
5914 of these, not one per target. Only one target is active at a
5915 time. The default buffer size is unimportant; it will be expanded
5916 whenever a larger buffer is needed. */
5917 rs = get_remote_state ();
5918 rs->buf_size = 400;
5919 rs->buf = xmalloc (rs->buf_size);
5920
5921 init_remote_ops ();
5922 add_target (&remote_ops);
5923
5924 init_extended_remote_ops ();
5925 add_target (&extended_remote_ops);
5926
5927 init_remote_async_ops ();
5928 add_target (&remote_async_ops);
5929
5930 init_extended_async_remote_ops ();
5931 add_target (&extended_async_remote_ops);
5932
5933 /* Hook into new objfile notification. */
5934 remote_new_objfile_chain = deprecated_target_new_objfile_hook;
5935 deprecated_target_new_objfile_hook = remote_new_objfile;
5936
5937 #if 0
5938 init_remote_threadtests ();
5939 #endif
5940
5941 /* set/show remote ... */
5942
5943 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5944 Remote protocol specific variables\n\
5945 Configure various remote-protocol specific variables such as\n\
5946 the packets being used"),
5947 &remote_set_cmdlist, "set remote ",
5948 0 /* allow-unknown */, &setlist);
5949 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5950 Remote protocol specific variables\n\
5951 Configure various remote-protocol specific variables such as\n\
5952 the packets being used"),
5953 &remote_show_cmdlist, "show remote ",
5954 0 /* allow-unknown */, &showlist);
5955
5956 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
5957 Compare section data on target to the exec file.\n\
5958 Argument is a single section name (default: all loaded sections)."),
5959 &cmdlist);
5960
5961 add_cmd ("packet", class_maintenance, packet_command, _("\
5962 Send an arbitrary packet to a remote target.\n\
5963 maintenance packet TEXT\n\
5964 If GDB is talking to an inferior via the GDB serial protocol, then\n\
5965 this command sends the string TEXT to the inferior, and displays the\n\
5966 response packet. GDB supplies the initial `$' character, and the\n\
5967 terminating `#' character and checksum."),
5968 &maintenancelist);
5969
5970 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
5971 Set whether to send break if interrupted."), _("\
5972 Show whether to send break if interrupted."), _("\
5973 If set, a break, instead of a cntrl-c, is sent to the remote target."),
5974 NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s. */
5975 &setlist, &showlist);
5976
5977 /* Install commands for configuring memory read/write packets. */
5978
5979 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
5980 Set the maximum number of bytes per memory write packet (deprecated)."),
5981 &setlist);
5982 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
5983 Show the maximum number of bytes per memory write packet (deprecated)."),
5984 &showlist);
5985 add_cmd ("memory-write-packet-size", no_class,
5986 set_memory_write_packet_size, _("\
5987 Set the maximum number of bytes per memory-write packet.\n\
5988 Specify the number of bytes in a packet or 0 (zero) for the\n\
5989 default packet size. The actual limit is further reduced\n\
5990 dependent on the target. Specify ``fixed'' to disable the\n\
5991 further restriction and ``limit'' to enable that restriction."),
5992 &remote_set_cmdlist);
5993 add_cmd ("memory-read-packet-size", no_class,
5994 set_memory_read_packet_size, _("\
5995 Set the maximum number of bytes per memory-read packet.\n\
5996 Specify the number of bytes in a packet or 0 (zero) for the\n\
5997 default packet size. The actual limit is further reduced\n\
5998 dependent on the target. Specify ``fixed'' to disable the\n\
5999 further restriction and ``limit'' to enable that restriction."),
6000 &remote_set_cmdlist);
6001 add_cmd ("memory-write-packet-size", no_class,
6002 show_memory_write_packet_size,
6003 _("Show the maximum number of bytes per memory-write packet."),
6004 &remote_show_cmdlist);
6005 add_cmd ("memory-read-packet-size", no_class,
6006 show_memory_read_packet_size,
6007 _("Show the maximum number of bytes per memory-read packet."),
6008 &remote_show_cmdlist);
6009
6010 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
6011 &remote_hw_watchpoint_limit, _("\
6012 Set the maximum number of target hardware watchpoints."), _("\
6013 Show the maximum number of target hardware watchpoints."), _("\
6014 Specify a negative limit for unlimited."),
6015 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
6016 &remote_set_cmdlist, &remote_show_cmdlist);
6017 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
6018 &remote_hw_breakpoint_limit, _("\
6019 Set the maximum number of target hardware breakpoints."), _("\
6020 Show the maximum number of target hardware breakpoints."), _("\
6021 Specify a negative limit for unlimited."),
6022 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
6023 &remote_set_cmdlist, &remote_show_cmdlist);
6024
6025 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
6026 &remote_address_size, _("\
6027 Set the maximum size of the address (in bits) in a memory packet."), _("\
6028 Show the maximum size of the address (in bits) in a memory packet."), NULL,
6029 NULL,
6030 NULL, /* FIXME: i18n: */
6031 &setlist, &showlist);
6032
6033 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
6034 "X", "binary-download", 1);
6035
6036 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
6037 "vCont", "verbose-resume", 0);
6038
6039 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
6040 "qSymbol", "symbol-lookup", 0);
6041
6042 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
6043 "P", "set-register", 1);
6044
6045 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
6046 "p", "fetch-register", 1);
6047
6048 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
6049 "Z0", "software-breakpoint", 0);
6050
6051 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
6052 "Z1", "hardware-breakpoint", 0);
6053
6054 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
6055 "Z2", "write-watchpoint", 0);
6056
6057 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
6058 "Z3", "read-watchpoint", 0);
6059
6060 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
6061 "Z4", "access-watchpoint", 0);
6062
6063 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
6064 "qXfer:auxv:read", "read-aux-vector", 0);
6065
6066 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
6067 "qGetTLSAddr", "get-thread-local-storage-address",
6068 0);
6069
6070 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
6071 "qSupported", "supported-packets", 0);
6072
6073 /* Keep the old ``set remote Z-packet ...'' working. Each individual
6074 Z sub-packet has its own set and show commands, but users may
6075 have sets to this variable in their .gdbinit files (or in their
6076 documentation). */
6077 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
6078 &remote_Z_packet_detect, _("\
6079 Set use of remote protocol `Z' packets"), _("\
6080 Show use of remote protocol `Z' packets "), _("\
6081 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
6082 packets."),
6083 set_remote_protocol_Z_packet_cmd,
6084 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
6085 &remote_set_cmdlist, &remote_show_cmdlist);
6086
6087 /* Eventually initialize fileio. See fileio.c */
6088 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
6089 }
This page took 0.214108 seconds and 4 git commands to generate.