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