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