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