]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/remote.c
import gdb-1999-06-14 snapshot
[thirdparty/binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2 Copyright 1988, 91, 92, 93, 94, 95, 96, 97, 1998
3 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
20
21 /* Remote communication protocol.
22
23 A debug packet whose contents are <data>
24 is encapsulated for transmission in the form:
25
26 $ <data> # CSUM1 CSUM2
27
28 <data> must be ASCII alphanumeric and cannot include characters
29 '$' or '#'. If <data> starts with two characters followed by
30 ':', then the existing stubs interpret this as a sequence number.
31
32 CSUM1 and CSUM2 are ascii hex representation of an 8-bit
33 checksum of <data>, the most significant nibble is sent first.
34 the hex digits 0-9,a-f are used.
35
36 Receiver responds with:
37
38 + - if CSUM is correct and ready for next packet
39 - - if CSUM is incorrect
40
41 <data> is as follows:
42 Most values are encoded in ascii hex digits. Signal numbers are according
43 to the numbering in target.h.
44
45 Request Packet
46
47 set thread Hct... Set thread for subsequent operations.
48 c = 'c' for thread used in step and
49 continue; t... can be -1 for all
50 threads.
51 c = 'g' for thread used in other
52 operations. If zero, pick a thread,
53 any thread.
54 reply OK for success
55 ENN for an error.
56
57 read registers g
58 reply XX....X Each byte of register data
59 is described by two hex digits.
60 Registers are in the internal order
61 for GDB, and the bytes in a register
62 are in the same order the machine uses.
63 or ENN for an error.
64
65 write regs GXX..XX Each byte of register data
66 is described by two hex digits.
67 reply OK for success
68 ENN for an error
69
70 write reg Pn...=r... Write register n... with value r...,
71 which contains two hex digits for each
72 byte in the register (target byte
73 order).
74 reply OK for success
75 ENN for an error
76 (not supported by all stubs).
77
78 read mem mAA..AA,LLLL AA..AA is address, LLLL is length.
79 reply XX..XX XX..XX is mem contents
80 Can be fewer bytes than requested
81 if able to read only part of the data.
82 or ENN NN is errno
83
84 write mem MAA..AA,LLLL:XX..XX
85 AA..AA is address,
86 LLLL is number of bytes,
87 XX..XX is data
88 reply OK for success
89 ENN for an error (this includes the case
90 where only part of the data was
91 written).
92
93 write mem XAA..AA,LLLL:XX..XX
94 (binary) AA..AA is address,
95 LLLL is number of bytes,
96 XX..XX is binary data
97 reply OK for success
98 ENN for an error
99
100 continue cAA..AA AA..AA is address to resume
101 If AA..AA is omitted,
102 resume at same address.
103
104 step sAA..AA AA..AA is address to resume
105 If AA..AA is omitted,
106 resume at same address.
107
108 continue with Csig;AA..AA Continue with signal sig (hex signal
109 signal number). If ;AA..AA is omitted,
110 resume at same address.
111
112 step with Ssig;AA..AA Like 'C' but step not continue.
113 signal
114
115 last signal ? Reply the current reason for stopping.
116 This is the same reply as is generated
117 for step or cont : SAA where AA is the
118 signal number.
119
120 detach D Reply OK.
121
122 There is no immediate reply to step or cont.
123 The reply comes when the machine stops.
124 It is SAA AA is the signal number.
125
126 or... TAAn...:r...;n...:r...;n...:r...;
127 AA = signal number
128 n... = register number (hex)
129 r... = register contents
130 n... = `thread'
131 r... = thread process ID. This is
132 a hex integer.
133 n... = other string not starting
134 with valid hex digit.
135 gdb should ignore this n,r pair
136 and go on to the next. This way
137 we can extend the protocol.
138 or... WAA The process exited, and AA is
139 the exit status. This is only
140 applicable for certains sorts of
141 targets.
142 or... XAA The process terminated with signal
143 AA.
144 or (obsolete) NAA;tttttttt;dddddddd;bbbbbbbb
145 AA = signal number
146 tttttttt = address of symbol "_start"
147 dddddddd = base of data section
148 bbbbbbbb = base of bss section.
149 Note: only used by Cisco Systems
150 targets. The difference between this
151 reply and the "qOffsets" query is that
152 the 'N' packet may arrive spontaneously
153 whereas the 'qOffsets' is a query
154 initiated by the host debugger.
155 or... OXX..XX XX..XX is hex encoding of ASCII data. This
156 can happen at any time while the
157 program is running and the debugger
158 should continue to wait for
159 'W', 'T', etc.
160
161 thread alive TXX Find out if the thread XX is alive.
162 reply OK thread is still alive
163 ENN thread is dead
164
165 remote restart RXX Restart the remote server
166
167 extended ops ! Use the extended remote protocol.
168 Sticky -- only needs to be set once.
169
170 kill request k
171
172 toggle debug d toggle debug flag (see 386 & 68k stubs)
173 reset r reset -- see sparc stub.
174 reserved <other> On other requests, the stub should
175 ignore the request and send an empty
176 response ($#<checksum>). This way
177 we can extend the protocol and GDB
178 can tell whether the stub it is
179 talking to uses the old or the new.
180 search tAA:PP,MM Search backwards starting at address
181 AA for a match with pattern PP and
182 mask MM. PP and MM are 4 bytes.
183 Not supported by all stubs.
184
185 general query qXXXX Request info about XXXX.
186 general set QXXXX=yyyy Set value of XXXX to yyyy.
187 query sect offs qOffsets Get section offsets. Reply is
188 Text=xxx;Data=yyy;Bss=zzz
189
190 Responses can be run-length encoded to save space. A '*' means that
191 the next character is an ASCII encoding giving a repeat count which
192 stands for that many repititions of the character preceding the '*'.
193 The encoding is n+29, yielding a printable character where n >=3
194 (which is where rle starts to win). Don't use an n > 126.
195
196 So
197 "0* " means the same as "0000". */
198
199 #include "defs.h"
200 #include "gdb_string.h"
201 #include <ctype.h>
202 #include <fcntl.h>
203 #include "frame.h"
204 #include "inferior.h"
205 #include "bfd.h"
206 #include "symfile.h"
207 #include "target.h"
208 #include "wait.h"
209 /*#include "terminal.h"*/
210 #include "gdbcmd.h"
211 #include "objfiles.h"
212 #include "gdb-stabs.h"
213 #include "gdbthread.h"
214
215 #include "dcache.h"
216
217 #include <ctype.h>
218 #ifdef USG
219 #include <sys/types.h>
220 #endif
221
222 #include <signal.h>
223 #include "serial.h"
224
225 /* Prototypes for local functions */
226
227 static void build_remote_gdbarch_data PARAMS ((void));
228
229 static int remote_write_bytes PARAMS ((CORE_ADDR memaddr,
230 char *myaddr, int len));
231
232 static int remote_read_bytes PARAMS ((CORE_ADDR memaddr,
233 char *myaddr, int len));
234
235 static void remote_files_info PARAMS ((struct target_ops *ignore));
236
237 static int remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char * myaddr,
238 int len, int should_write,
239 struct target_ops * target));
240
241 static void remote_prepare_to_store PARAMS ((void));
242
243 static void remote_fetch_registers PARAMS ((int regno));
244
245 static void remote_resume PARAMS ((int pid, int step,
246 enum target_signal siggnal));
247
248 static int remote_start_remote PARAMS ((PTR));
249
250 static void remote_open PARAMS ((char *name, int from_tty));
251
252 static void extended_remote_open PARAMS ((char *name, int from_tty));
253
254 static void remote_open_1 PARAMS ((char *, int, struct target_ops *,
255 int extended_p));
256
257 static void remote_close PARAMS ((int quitting));
258
259 static void remote_store_registers PARAMS ((int regno));
260
261 static void remote_mourn PARAMS ((void));
262
263 static void extended_remote_restart PARAMS ((void));
264
265 static void extended_remote_mourn PARAMS ((void));
266
267 static void extended_remote_create_inferior PARAMS ((char *, char *, char **));
268
269 static void remote_mourn_1 PARAMS ((struct target_ops *));
270
271 static void remote_send PARAMS ((char *buf));
272
273 static int readchar PARAMS ((int timeout));
274
275 static int remote_wait PARAMS ((int pid, struct target_waitstatus * status));
276
277 static void remote_kill PARAMS ((void));
278
279 static int tohex PARAMS ((int nib));
280
281 static void remote_detach PARAMS ((char *args, int from_tty));
282
283 static void remote_interrupt PARAMS ((int signo));
284
285 static void remote_interrupt_twice PARAMS ((int signo));
286
287 static void interrupt_query PARAMS ((void));
288
289 static void set_thread PARAMS ((int, int));
290
291 static int remote_thread_alive PARAMS ((int));
292
293 static void get_offsets PARAMS ((void));
294
295 static int read_frame PARAMS ((char *));
296
297 static int remote_insert_breakpoint PARAMS ((CORE_ADDR, char *));
298
299 static int remote_remove_breakpoint PARAMS ((CORE_ADDR, char *));
300
301 static int hexnumlen PARAMS ((ULONGEST num));
302
303 static void init_remote_ops PARAMS ((void));
304
305 static void init_extended_remote_ops PARAMS ((void));
306
307 static void init_remote_cisco_ops PARAMS ((void));
308
309 static struct target_ops remote_cisco_ops;
310
311 static void remote_stop PARAMS ((void));
312
313 static int ishex PARAMS ((int ch, int *val));
314
315 static int stubhex PARAMS ((int ch));
316
317 static int remote_query PARAMS ((int/*char*/, char *, char *, int *));
318
319 static int hexnumstr PARAMS ((char *, ULONGEST));
320
321 static CORE_ADDR remote_address_masked PARAMS ((CORE_ADDR));
322
323 static void print_packet PARAMS ((char *));
324
325 static unsigned long crc32 PARAMS ((unsigned char *, int, unsigned int));
326
327 static void compare_sections_command PARAMS ((char *, int));
328
329 static void packet_command PARAMS ((char *, int));
330
331 static int stub_unpack_int PARAMS ((char *buff, int fieldlength));
332
333 static int remote_current_thread PARAMS ((int oldpid));
334
335 static void remote_find_new_threads PARAMS ((void));
336
337 static void record_currthread PARAMS ((int currthread));
338
339 /* exported functions */
340
341 extern int fromhex PARAMS ((int a));
342
343 extern void getpkt PARAMS ((char *buf, int forever));
344
345 extern int putpkt PARAMS ((char *buf));
346
347 static int putpkt_binary PARAMS ((char *buf, int cnt));
348
349 void remote_console_output PARAMS ((char *));
350
351 static void check_binary_download PARAMS ((CORE_ADDR addr));
352
353 /* Define the target subroutine names */
354
355 void open_remote_target PARAMS ((char *, int, struct target_ops *, int));
356
357 void _initialize_remote PARAMS ((void));
358
359 /* */
360
361 static struct target_ops remote_ops;
362
363 static struct target_ops extended_remote_ops;
364
365 /* This was 5 seconds, which is a long time to sit and wait.
366 Unless this is going though some terminal server or multiplexer or
367 other form of hairy serial connection, I would think 2 seconds would
368 be plenty. */
369
370 /* Changed to allow option to set timeout value.
371 was static int remote_timeout = 2; */
372 extern int remote_timeout;
373
374 /* This variable chooses whether to send a ^C or a break when the user
375 requests program interruption. Although ^C is usually what remote
376 systems expect, and that is the default here, sometimes a break is
377 preferable instead. */
378
379 static int remote_break;
380
381 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
382 remote_open knows that we don't have a file open when the program
383 starts. */
384 static serial_t remote_desc = NULL;
385
386 /* This is set by the target (thru the 'S' message)
387 to denote that the target is in kernel mode. */
388 static int cisco_kernel_mode = 0;
389
390 /* This variable (available to the user via "set remotebinarydownload")
391 dictates whether downloads are sent in binary (via the 'X' packet).
392 We assume that the stub can, and attempt to do it. This will be cleared if
393 the stub does not understand it. This switch is still needed, though
394 in cases when the packet is supported in the stub, but the connection
395 does not allow it (i.e., 7-bit serial connection only). */
396 static int remote_binary_download = 1;
397
398 /* Have we already checked whether binary downloads work? */
399 static int remote_binary_checked;
400
401 /* Maximum number of bytes to read/write at once. The value here
402 is chosen to fill up a packet (the headers account for the 32). */
403 #define MAXBUFBYTES(N) (((N)-32)/2)
404
405 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
406 and i386-stub.c. Normally, no one would notice because it only matters
407 for writing large chunks of memory (e.g. in downloads). Also, this needs
408 to be more than 400 if required to hold the registers (see below, where
409 we round it up based on REGISTER_BYTES). */
410 /* Round up PBUFSIZ to hold all the registers, at least. */
411 #define PBUFSIZ ((REGISTER_BYTES > MAXBUFBYTES (400)) \
412 ? (REGISTER_BYTES * 2 + 32) \
413 : 400)
414
415
416 /* This variable sets the number of bytes to be written to the target
417 in a single packet. Normally PBUFSIZ is satisfactory, but some
418 targets need smaller values (perhaps because the receiving end
419 is slow). */
420
421 static int remote_write_size;
422
423 /* This variable sets the number of bits in an address that are to be
424 sent in a memory ("M" or "m") packet. Normally, after stripping
425 leading zeros, the entire address would be sent. This variable
426 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
427 initial implementation of remote.c restricted the address sent in
428 memory packets to ``host::sizeof long'' bytes - (typically 32
429 bits). Consequently, for 64 bit targets, the upper 32 bits of an
430 address was never sent. Since fixing this bug may cause a break in
431 some remote targets this variable is principly provided to
432 facilitate backward compatibility. */
433
434 static int remote_address_size;
435
436 /* This is the size (in chars) of the first response to the `g' command. This
437 is used to limit the size of the memory read and write commands to prevent
438 stub buffers from overflowing. The size does not include headers and
439 trailers, it is only the payload size. */
440
441 static int remote_register_buf_size = 0;
442
443 /* Should we try the 'P' request? If this is set to one when the stub
444 doesn't support 'P', the only consequence is some unnecessary traffic. */
445 static int stub_supports_P = 1;
446
447 /* These are pointers to hook functions that may be set in order to
448 modify resume/wait behavior for a particular architecture. */
449
450 void (*target_resume_hook) PARAMS ((void));
451 void (*target_wait_loop_hook) PARAMS ((void));
452
453 \f
454
455 /* These are the threads which we last sent to the remote system.
456 -1 for all or -2 for not sent yet. */
457 static int general_thread;
458 static int continue_thread;
459
460 /* Call this function as a result of
461 1) A halt indication (T packet) containing a thread id
462 2) A direct query of currthread
463 3) Successful execution of set thread
464 */
465
466 static void
467 record_currthread (currthread)
468 int currthread;
469 {
470 general_thread = currthread;
471
472 /* If this is a new thread, add it to GDB's thread list.
473 If we leave it up to WFI to do this, bad things will happen. */
474 if (!in_thread_list (currthread))
475 {
476 add_thread (currthread);
477 printf_filtered ("[New %s]\n", target_pid_to_str (currthread));
478 }
479 }
480
481 #define MAGIC_NULL_PID 42000
482
483 static void
484 set_thread (th, gen)
485 int th;
486 int gen;
487 {
488 char buf[PBUFSIZ];
489 int state = gen ? general_thread : continue_thread;
490
491 if (state == th)
492 return;
493
494 buf[0] = 'H';
495 buf[1] = gen ? 'g' : 'c';
496 if (th == MAGIC_NULL_PID)
497 {
498 buf[2] = '0';
499 buf[3] = '\0';
500 }
501 else if (th < 0)
502 sprintf (&buf[2], "-%x", -th);
503 else
504 sprintf (&buf[2], "%x", th);
505 putpkt (buf);
506 getpkt (buf, 0);
507 if (gen)
508 general_thread = th;
509 else
510 continue_thread = th;
511 }
512 \f
513 /* Return nonzero if the thread TH is still alive on the remote system. */
514
515 static int
516 remote_thread_alive (tid)
517 int tid;
518 {
519 char buf[16];
520
521 if (tid < 0)
522 sprintf (buf, "T-%08x", -tid);
523 else
524 sprintf (buf, "T%08x", tid);
525 putpkt (buf);
526 getpkt (buf, 0);
527 return (buf[0] == 'O' && buf[1] == 'K');
528 }
529
530 /* About these extended threadlist and threadinfo packets. They are
531 variable length packets but, the fields within them are often fixed
532 length. They are redundent enough to send over UDP as is the
533 remote protocol in general. There is a matching unit test module
534 in libstub. */
535
536 #define OPAQUETHREADBYTES 8
537
538 /* a 64 bit opaque identifier */
539 typedef unsigned char threadref[OPAQUETHREADBYTES];
540
541 /* WARNING: This threadref data structure comes from the remote O.S., libstub
542 protocol encoding, and remote.c. it is not particularly changable */
543
544 /* Right now, the internal structure is int. We want it to be bigger.
545 Plan to fix this.
546 */
547
548 typedef int gdb_threadref; /* internal GDB thread reference */
549
550 /* gdb_ext_thread_info is an internal GDB data structure which is
551 equivalint to the reply of the remote threadinfo packet */
552
553 struct gdb_ext_thread_info
554 {
555 threadref threadid; /* External form of thread reference */
556 int active; /* Has state interesting to GDB? , regs, stack */
557 char display[256]; /* Brief state display, name, blocked/syspended */
558 char shortname[32]; /* To be used to name threads */
559 char more_display[256]; /* Long info, statistics, queue depth, whatever */
560 };
561
562 /* The volume of remote transfers can be limited by submitting
563 a mask containing bits specifying the desired information.
564 Use a union of these values as the 'selection' parameter to
565 get_thread_info. FIXME: Make these TAG names more thread specific.
566 */
567
568 #define TAG_THREADID 1
569 #define TAG_EXISTS 2
570 #define TAG_DISPLAY 4
571 #define TAG_THREADNAME 8
572 #define TAG_MOREDISPLAY 16
573
574 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES*2)
575
576 char *unpack_varlen_hex PARAMS ((char *buff, int *result));
577
578 static char *unpack_nibble PARAMS ((char *buf, int *val));
579
580 static char *pack_nibble PARAMS ((char *buf, int nibble));
581
582 static char *pack_hex_byte PARAMS ((char *pkt, int/*unsigned char*/ byte));
583
584 static char *unpack_byte PARAMS ((char *buf, int *value));
585
586 static char *pack_int PARAMS ((char *buf, int value));
587
588 static char *unpack_int PARAMS ((char *buf, int *value));
589
590 static char *unpack_string PARAMS ((char *src, char *dest, int length));
591
592 static char *pack_threadid PARAMS ((char *pkt, threadref *id));
593
594 static char *unpack_threadid PARAMS ((char *inbuf, threadref *id));
595
596 void int_to_threadref PARAMS ((threadref *id, int value));
597
598 static int threadref_to_int PARAMS ((threadref *ref));
599
600 static void copy_threadref PARAMS ((threadref *dest, threadref *src));
601
602 static int threadmatch PARAMS ((threadref *dest, threadref *src));
603
604 static char *pack_threadinfo_request PARAMS ((char *pkt, int mode,
605 threadref *id));
606
607 static int remote_unpack_thread_info_response PARAMS ((char *pkt,
608 threadref *expectedref,
609 struct gdb_ext_thread_info *info));
610
611
612 static int remote_get_threadinfo PARAMS ((threadref *threadid,
613 int fieldset, /*TAG mask */
614 struct gdb_ext_thread_info *info));
615
616 static int adapt_remote_get_threadinfo PARAMS ((gdb_threadref *ref,
617 int selection,
618 struct gdb_ext_thread_info *info));
619
620 static char *pack_threadlist_request PARAMS ((char *pkt, int startflag,
621 int threadcount,
622 threadref *nextthread));
623
624 static int parse_threadlist_response PARAMS ((char *pkt,
625 int result_limit,
626 threadref *original_echo,
627 threadref *resultlist,
628 int *doneflag));
629
630 static int remote_get_threadlist PARAMS ((int startflag,
631 threadref *nextthread,
632 int result_limit,
633 int *done,
634 int *result_count,
635 threadref *threadlist));
636
637 typedef int (*rmt_thread_action) (threadref *ref, void *context);
638
639 static int remote_threadlist_iterator PARAMS ((rmt_thread_action stepfunction,
640 void *context, int looplimit));
641
642 static int remote_newthread_step PARAMS ((threadref *ref, void *context));
643
644 /* encode 64 bits in 16 chars of hex */
645
646 static const char hexchars[] = "0123456789abcdef";
647
648 static int
649 ishex (ch, val)
650 int ch;
651 int *val;
652 {
653 if ((ch >= 'a') && (ch <= 'f'))
654 {
655 *val = ch - 'a' + 10;
656 return 1;
657 }
658 if ((ch >= 'A') && (ch <= 'F'))
659 {
660 *val = ch - 'A' + 10;
661 return 1;
662 }
663 if ((ch >= '0') && (ch <= '9'))
664 {
665 *val = ch - '0';
666 return 1;
667 }
668 return 0;
669 }
670
671 static int
672 stubhex (ch)
673 int ch;
674 {
675 if (ch >= 'a' && ch <= 'f')
676 return ch - 'a' + 10;
677 if (ch >= '0' && ch <= '9')
678 return ch - '0';
679 if (ch >= 'A' && ch <= 'F')
680 return ch - 'A' + 10;
681 return -1;
682 }
683
684 static int
685 stub_unpack_int (buff, fieldlength)
686 char *buff;
687 int fieldlength;
688 {
689 int nibble;
690 int retval = 0;
691
692 while (fieldlength)
693 {
694 nibble = stubhex (*buff++);
695 retval |= nibble;
696 fieldlength--;
697 if (fieldlength)
698 retval = retval << 4;
699 }
700 return retval;
701 }
702
703 char *
704 unpack_varlen_hex (buff, result)
705 char *buff; /* packet to parse */
706 int *result;
707 {
708 int nibble;
709 int retval = 0;
710
711 while (ishex (*buff, &nibble))
712 {
713 buff++;
714 retval = retval << 4;
715 retval |= nibble & 0x0f;
716 }
717 *result = retval;
718 return buff;
719 }
720
721 static char *
722 unpack_nibble (buf, val)
723 char *buf;
724 int *val;
725 {
726 ishex (*buf++, val);
727 return buf;
728 }
729
730 static char *
731 pack_nibble (buf, nibble)
732 char *buf;
733 int nibble;
734 {
735 *buf++ = hexchars[(nibble & 0x0f)];
736 return buf;
737 }
738
739 static char *
740 pack_hex_byte (pkt, byte)
741 char *pkt;
742 int byte;
743 {
744 *pkt++ = hexchars[(byte >> 4) & 0xf];
745 *pkt++ = hexchars[(byte & 0xf)];
746 return pkt;
747 }
748
749 static char *
750 unpack_byte (buf, value)
751 char *buf;
752 int *value;
753 {
754 *value = stub_unpack_int (buf, 2);
755 return buf + 2;
756 }
757
758 static char *
759 pack_int (buf, value)
760 char *buf;
761 int value;
762 {
763 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
764 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
765 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
766 buf = pack_hex_byte (buf, (value & 0xff));
767 return buf;
768 }
769
770 static char *
771 unpack_int (buf, value)
772 char *buf;
773 int *value;
774 {
775 *value = stub_unpack_int (buf, 8);
776 return buf + 8;
777 }
778
779 #if 0 /* currently unused, uncomment when needed */
780 static char *pack_string PARAMS ((char *pkt, char *string));
781
782 static char *
783 pack_string (pkt, string)
784 char *pkt;
785 char *string;
786 {
787 char ch;
788 int len;
789
790 len = strlen (string);
791 if (len > 200)
792 len = 200; /* Bigger than most GDB packets, junk??? */
793 pkt = pack_hex_byte (pkt, len);
794 while (len-- > 0)
795 {
796 ch = *string++;
797 if ((ch == '\0') || (ch == '#'))
798 ch = '*'; /* Protect encapsulation */
799 *pkt++ = ch;
800 }
801 return pkt;
802 }
803 #endif /* 0 (unused) */
804
805 static char *
806 unpack_string (src, dest, length)
807 char *src;
808 char *dest;
809 int length;
810 {
811 while (length--)
812 *dest++ = *src++;
813 *dest = '\0';
814 return src;
815 }
816
817 static char *
818 pack_threadid (pkt, id)
819 char *pkt;
820 threadref *id;
821 {
822 char *limit;
823 unsigned char *altid;
824
825 altid = (unsigned char *) id;
826 limit = pkt + BUF_THREAD_ID_SIZE;
827 while (pkt < limit)
828 pkt = pack_hex_byte (pkt, *altid++);
829 return pkt;
830 }
831
832
833 static char *
834 unpack_threadid (inbuf, id)
835 char *inbuf;
836 threadref *id;
837 {
838 char *altref;
839 char *limit = inbuf + BUF_THREAD_ID_SIZE;
840 int x, y;
841
842 altref = (char *) id;
843
844 while (inbuf < limit)
845 {
846 x = stubhex (*inbuf++);
847 y = stubhex (*inbuf++);
848 *altref++ = (x << 4) | y;
849 }
850 return inbuf;
851 }
852
853 /* Externally, threadrefs are 64 bits but internally, they are still
854 ints. This is due to a mismatch of specifications. We would like
855 to use 64bit thread references internally. This is an adapter
856 function. */
857
858 void
859 int_to_threadref (id, value)
860 threadref *id;
861 int value;
862 {
863 unsigned char *scan;
864
865 scan = (unsigned char *) id;
866 {
867 int i = 4;
868 while (i--)
869 *scan++ = 0;
870 }
871 *scan++ = (value >> 24) & 0xff;
872 *scan++ = (value >> 16) & 0xff;
873 *scan++ = (value >> 8) & 0xff;
874 *scan++ = (value & 0xff);
875 }
876
877 static int
878 threadref_to_int (ref)
879 threadref *ref;
880 {
881 int i, value = 0;
882 unsigned char *scan;
883
884 scan = (char *) ref;
885 scan += 4;
886 i = 4;
887 while (i-- > 0)
888 value = (value << 8) | ((*scan++) & 0xff);
889 return value;
890 }
891
892 static void
893 copy_threadref (dest, src)
894 threadref *dest;
895 threadref *src;
896 {
897 int i;
898 unsigned char *csrc, *cdest;
899
900 csrc = (unsigned char *) src;
901 cdest = (unsigned char *) dest;
902 i = 8;
903 while (i--)
904 *cdest++ = *csrc++;
905 }
906
907 static int
908 threadmatch (dest, src)
909 threadref *dest;
910 threadref *src;
911 {
912 /* things are broken right now, so just assume we got a match */
913 #if 0
914 unsigned char *srcp, *destp;
915 int i, result;
916 srcp = (char *) src;
917 destp = (char *) dest;
918
919 result = 1;
920 while (i-- > 0)
921 result &= (*srcp++ == *destp++) ? 1 : 0;
922 return result;
923 #endif
924 return 1;
925 }
926
927 /*
928 threadid:1, # always request threadid
929 context_exists:2,
930 display:4,
931 unique_name:8,
932 more_display:16
933 */
934
935 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
936
937 static char *
938 pack_threadinfo_request (pkt, mode, id)
939 char *pkt;
940 int mode;
941 threadref *id;
942 {
943 *pkt++ = 'q'; /* Info Query */
944 *pkt++ = 'P'; /* process or thread info */
945 pkt = pack_int (pkt, mode); /* mode */
946 pkt = pack_threadid (pkt, id); /* threadid */
947 *pkt = '\0'; /* terminate */
948 return pkt;
949 }
950
951 /* These values tag the fields in a thread info response packet */
952 /* Tagging the fields allows us to request specific fields and to
953 add more fields as time goes by */
954
955 #define TAG_THREADID 1 /* Echo the thread identifier */
956 #define TAG_EXISTS 2 /* Is this process defined enough to
957 fetch registers and its stack */
958 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
959 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is */
960 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
961 the process*/
962
963 static int
964 remote_unpack_thread_info_response (pkt, expectedref, info)
965 char *pkt;
966 threadref *expectedref;
967 struct gdb_ext_thread_info *info;
968 {
969 int mask, length;
970 unsigned int tag;
971 threadref ref;
972 char *limit = pkt + PBUFSIZ; /* plausable parsing limit */
973 int retval = 1;
974
975 /* info->threadid = 0; FIXME: implement zero_threadref */
976 info->active = 0;
977 info->display[0] = '\0';
978 info->shortname[0] = '\0';
979 info->more_display[0] = '\0';
980
981 /* Assume the characters indicating the packet type have been stripped */
982 pkt = unpack_int (pkt, &mask); /* arg mask */
983 pkt = unpack_threadid (pkt, &ref);
984
985 if (mask == 0)
986 warning ("Incomplete response to threadinfo request\n");
987 if (!threadmatch (&ref, expectedref))
988 { /* This is an answer to a different request */
989 warning ("ERROR RMT Thread info mismatch\n");
990 return 0;
991 }
992 copy_threadref (&info->threadid, &ref);
993
994 /* Loop on tagged fields , try to bail if somthing goes wrong */
995
996 while ((pkt < limit) && mask && *pkt) /* packets are terminated with nulls */
997 {
998 pkt = unpack_int (pkt, &tag); /* tag */
999 pkt = unpack_byte (pkt, &length); /* length */
1000 if (!(tag & mask)) /* tags out of synch with mask */
1001 {
1002 warning ("ERROR RMT: threadinfo tag mismatch\n");
1003 retval = 0;
1004 break;
1005 }
1006 if (tag == TAG_THREADID)
1007 {
1008 if (length != 16)
1009 {
1010 warning ("ERROR RMT: length of threadid is not 16\n");
1011 retval = 0;
1012 break;
1013 }
1014 pkt = unpack_threadid (pkt, &ref);
1015 mask = mask & ~TAG_THREADID;
1016 continue;
1017 }
1018 if (tag == TAG_EXISTS)
1019 {
1020 info->active = stub_unpack_int (pkt, length);
1021 pkt += length;
1022 mask = mask & ~(TAG_EXISTS);
1023 if (length > 8)
1024 {
1025 warning ("ERROR RMT: 'exists' length too long\n");
1026 retval = 0;
1027 break;
1028 }
1029 continue;
1030 }
1031 if (tag == TAG_THREADNAME)
1032 {
1033 pkt = unpack_string (pkt, &info->shortname[0], length);
1034 mask = mask & ~TAG_THREADNAME;
1035 continue;
1036 }
1037 if (tag == TAG_DISPLAY)
1038 {
1039 pkt = unpack_string (pkt, &info->display[0], length);
1040 mask = mask & ~TAG_DISPLAY;
1041 continue;
1042 }
1043 if (tag == TAG_MOREDISPLAY)
1044 {
1045 pkt = unpack_string (pkt, &info->more_display[0], length);
1046 mask = mask & ~TAG_MOREDISPLAY;
1047 continue;
1048 }
1049 warning ("ERROR RMT: unknown thread info tag\n");
1050 break; /* Not a tag we know about */
1051 }
1052 return retval;
1053 }
1054
1055 static int
1056 remote_get_threadinfo (threadid, fieldset, info)
1057 threadref *threadid;
1058 int fieldset; /* TAG mask */
1059 struct gdb_ext_thread_info *info;
1060 {
1061 int result;
1062 char threadinfo_pkt[PBUFSIZ];
1063
1064 pack_threadinfo_request (threadinfo_pkt, fieldset, threadid);
1065 putpkt (threadinfo_pkt);
1066 getpkt (threadinfo_pkt, 0);
1067 result = remote_unpack_thread_info_response (threadinfo_pkt + 2, threadid,
1068 info);
1069 return result;
1070 }
1071
1072 /* Unfortunately, 61 bit thread-ids are bigger than the internal
1073 representation of a threadid. */
1074
1075 static int
1076 adapt_remote_get_threadinfo (ref, selection, info)
1077 gdb_threadref *ref;
1078 int selection;
1079 struct gdb_ext_thread_info *info;
1080 {
1081 threadref lclref;
1082
1083 int_to_threadref (&lclref, *ref);
1084 return remote_get_threadinfo (&lclref, selection, info);
1085 }
1086
1087 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1088
1089 static char *
1090 pack_threadlist_request (pkt, startflag, threadcount, nextthread)
1091 char *pkt;
1092 int startflag;
1093 int threadcount;
1094 threadref *nextthread;
1095 {
1096 *pkt++ = 'q'; /* info query packet */
1097 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1098 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1099 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1100 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1101 *pkt = '\0';
1102 return pkt;
1103 }
1104
1105 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1106
1107 static int
1108 parse_threadlist_response (pkt, result_limit, original_echo, resultlist,
1109 doneflag)
1110 char *pkt;
1111 int result_limit;
1112 threadref *original_echo;
1113 threadref *resultlist;
1114 int *doneflag;
1115 {
1116 char *limit;
1117 int count, resultcount, done;
1118
1119 resultcount = 0;
1120 /* Assume the 'q' and 'M chars have been stripped. */
1121 limit = pkt + (PBUFSIZ - BUF_THREAD_ID_SIZE); /* done parse past here */
1122 pkt = unpack_byte (pkt, &count); /* count field */
1123 pkt = unpack_nibble (pkt, &done);
1124 /* The first threadid is the argument threadid. */
1125 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1126 while ((count-- > 0) && (pkt < limit))
1127 {
1128 pkt = unpack_threadid (pkt, resultlist++);
1129 if (resultcount++ >= result_limit)
1130 break;
1131 }
1132 if (doneflag)
1133 *doneflag = done;
1134 return resultcount;
1135 }
1136
1137 static int
1138 remote_get_threadlist (startflag, nextthread, result_limit,
1139 done, result_count, threadlist)
1140 int startflag;
1141 threadref *nextthread;
1142 int result_limit;
1143 int *done;
1144 int *result_count;
1145 threadref *threadlist;
1146
1147 {
1148 static threadref echo_nextthread;
1149 char threadlist_packet[PBUFSIZ];
1150 char t_response[PBUFSIZ];
1151 int result = 1;
1152
1153 /* Trancate result limit to be smaller than the packet size */
1154 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= PBUFSIZ)
1155 result_limit = (PBUFSIZ / BUF_THREAD_ID_SIZE) - 2;
1156
1157 pack_threadlist_request (threadlist_packet,
1158 startflag, result_limit, nextthread);
1159 putpkt (threadlist_packet);
1160 getpkt (t_response, 0);
1161
1162 *result_count =
1163 parse_threadlist_response (t_response + 2, result_limit, &echo_nextthread,
1164 threadlist, done);
1165
1166 if (!threadmatch (&echo_nextthread, nextthread))
1167 {
1168 /* FIXME: This is a good reason to drop the packet */
1169 /* Possably, there is a duplicate response */
1170 /* Possabilities :
1171 retransmit immediatly - race conditions
1172 retransmit after timeout - yes
1173 exit
1174 wait for packet, then exit
1175 */
1176 warning ("HMM: threadlist did not echo arg thread, dropping it\n");
1177 return 0; /* I choose simply exiting */
1178 }
1179 if (*result_count <= 0)
1180 {
1181 if (*done != 1)
1182 {
1183 warning ("RMT ERROR : failed to get remote thread list\n");
1184 result = 0;
1185 }
1186 return result; /* break; */
1187 }
1188 if (*result_count > result_limit)
1189 {
1190 *result_count = 0;
1191 warning ("RMT ERROR: threadlist response longer than requested\n");
1192 return 0;
1193 }
1194 return result;
1195 }
1196
1197 /* This is the interface between remote and threads, remotes upper interface */
1198
1199 /* remote_find_new_threads retrieves the thread list and for each
1200 thread in the list, looks up the thread in GDB's internal list,
1201 ading the thread if it does not already exist. This involves
1202 getting partial thread lists from the remote target so, polling the
1203 quit_flag is required. */
1204
1205
1206 /* About this many threadisds fit in a packet. */
1207
1208 #define MAXTHREADLISTRESULTS 32
1209
1210 static int
1211 remote_threadlist_iterator (stepfunction, context, looplimit)
1212 rmt_thread_action stepfunction;
1213 void *context;
1214 int looplimit;
1215 {
1216 int done, i, result_count;
1217 int startflag = 1;
1218 int result = 1;
1219 int loopcount = 0;
1220 static threadref nextthread;
1221 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1222
1223 done = 0;
1224 while (!done)
1225 {
1226 if (loopcount++ > looplimit)
1227 {
1228 result = 0;
1229 warning ("Remote fetch threadlist -infinite loop-\n");
1230 break;
1231 }
1232 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1233 &done, &result_count, resultthreadlist))
1234 {
1235 result = 0;
1236 break;
1237 }
1238 /* clear for later iterations */
1239 startflag = 0;
1240 /* Setup to resume next batch of thread references, set nextthread. */
1241 if (result_count >= 1)
1242 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1243 i = 0;
1244 while (result_count--)
1245 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1246 break;
1247 }
1248 return result;
1249 }
1250
1251 static int
1252 remote_newthread_step (ref, context)
1253 threadref *ref;
1254 void *context;
1255 {
1256 int pid;
1257
1258 pid = threadref_to_int (ref);
1259 if (!in_thread_list (pid))
1260 add_thread (pid);
1261 return 1; /* continue iterator */
1262 }
1263
1264 #define CRAZY_MAX_THREADS 1000
1265
1266 static int
1267 remote_current_thread (oldpid)
1268 int oldpid;
1269 {
1270 char buf[PBUFSIZ];
1271
1272 putpkt ("qC");
1273 getpkt (buf, 0);
1274 if (buf[0] == 'Q' && buf[1] == 'C')
1275 return strtol (&buf[2], NULL, 16);
1276 else
1277 return oldpid;
1278 }
1279
1280 /* Find new threads for info threads command. */
1281
1282 static void
1283 remote_find_new_threads ()
1284 {
1285 remote_threadlist_iterator (remote_newthread_step, 0,
1286 CRAZY_MAX_THREADS);
1287 if (inferior_pid == MAGIC_NULL_PID) /* ack ack ack */
1288 inferior_pid = remote_current_thread (inferior_pid);
1289 }
1290
1291 static void
1292 remote_threads_info (void)
1293 {
1294 char buf[PBUFSIZ], *bufp;
1295 int tid;
1296
1297 if (remote_desc == 0) /* paranoia */
1298 error ("Command can only be used when connected to the remote target.");
1299
1300 putpkt ("qfThreadInfo");
1301 getpkt (bufp = buf, 0);
1302 if (bufp[0] == '\0') /* q packet not recognized! */
1303 { /* try old jmetzler method */
1304 remote_find_new_threads ();
1305 return;
1306 }
1307 else /* try new 'q' method */
1308 while (*bufp++ == 'm') /* reply contains one or more TID */
1309 {
1310 do {
1311 tid = strtol(bufp, &bufp, 16);
1312 if (tid != 0 && !in_thread_list (tid))
1313 add_thread (tid);
1314 } while (*bufp++ == ','); /* comma-separated list */
1315 putpkt ("qsThreadInfo");
1316 getpkt (bufp = buf, 0);
1317 }
1318 }
1319
1320 \f
1321 /* Restart the remote side; this is an extended protocol operation. */
1322
1323 static void
1324 extended_remote_restart ()
1325 {
1326 char buf[PBUFSIZ];
1327
1328 /* Send the restart command; for reasons I don't understand the
1329 remote side really expects a number after the "R". */
1330 buf[0] = 'R';
1331 sprintf (&buf[1], "%x", 0);
1332 putpkt (buf);
1333
1334 /* Now query for status so this looks just like we restarted
1335 gdbserver from scratch. */
1336 putpkt ("?");
1337 getpkt (buf, 0);
1338 }
1339 \f
1340 /* Clean up connection to a remote debugger. */
1341
1342 /* ARGSUSED */
1343 static void
1344 remote_close (quitting)
1345 int quitting;
1346 {
1347 if (remote_desc)
1348 SERIAL_CLOSE (remote_desc);
1349 remote_desc = NULL;
1350 }
1351
1352 /* Query the remote side for the text, data and bss offsets. */
1353
1354 static void
1355 get_offsets ()
1356 {
1357 char buf[PBUFSIZ], *ptr;
1358 int lose;
1359 CORE_ADDR text_addr, data_addr, bss_addr;
1360 struct section_offsets *offs;
1361
1362 putpkt ("qOffsets");
1363
1364 getpkt (buf, 0);
1365
1366 if (buf[0] == '\000')
1367 return; /* Return silently. Stub doesn't support
1368 this command. */
1369 if (buf[0] == 'E')
1370 {
1371 warning ("Remote failure reply: %s", buf);
1372 return;
1373 }
1374
1375 /* Pick up each field in turn. This used to be done with scanf, but
1376 scanf will make trouble if CORE_ADDR size doesn't match
1377 conversion directives correctly. The following code will work
1378 with any size of CORE_ADDR. */
1379 text_addr = data_addr = bss_addr = 0;
1380 ptr = buf;
1381 lose = 0;
1382
1383 if (strncmp (ptr, "Text=", 5) == 0)
1384 {
1385 ptr += 5;
1386 /* Don't use strtol, could lose on big values. */
1387 while (*ptr && *ptr != ';')
1388 text_addr = (text_addr << 4) + fromhex (*ptr++);
1389 }
1390 else
1391 lose = 1;
1392
1393 if (!lose && strncmp (ptr, ";Data=", 6) == 0)
1394 {
1395 ptr += 6;
1396 while (*ptr && *ptr != ';')
1397 data_addr = (data_addr << 4) + fromhex (*ptr++);
1398 }
1399 else
1400 lose = 1;
1401
1402 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
1403 {
1404 ptr += 5;
1405 while (*ptr && *ptr != ';')
1406 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
1407 }
1408 else
1409 lose = 1;
1410
1411 if (lose)
1412 error ("Malformed response to offset query, %s", buf);
1413
1414 if (symfile_objfile == NULL)
1415 return;
1416
1417 offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
1418 + symfile_objfile->num_sections
1419 * sizeof (offs->offsets));
1420 memcpy (offs, symfile_objfile->section_offsets,
1421 sizeof (struct section_offsets)
1422 + symfile_objfile->num_sections
1423 * sizeof (offs->offsets));
1424
1425 ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
1426
1427 /* This is a temporary kludge to force data and bss to use the same offsets
1428 because that's what nlmconv does now. The real solution requires changes
1429 to the stub and remote.c that I don't have time to do right now. */
1430
1431 ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
1432 ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
1433
1434 objfile_relocate (symfile_objfile, offs);
1435 }
1436
1437 /*
1438 * Cisco version of section offsets:
1439 *
1440 * Instead of having GDB query the target for the section offsets,
1441 * Cisco lets the target volunteer the information! It's also in
1442 * a different format, so here are the functions that will decode
1443 * a section offset packet from a Cisco target.
1444 */
1445
1446 /*
1447 * Function: remote_cisco_section_offsets
1448 *
1449 * Returns: zero for success, non-zero for failure
1450 */
1451
1452 static int
1453 remote_cisco_section_offsets (text_addr, data_addr, bss_addr,
1454 text_offs, data_offs, bss_offs)
1455 bfd_vma text_addr;
1456 bfd_vma data_addr;
1457 bfd_vma bss_addr;
1458 bfd_signed_vma * text_offs;
1459 bfd_signed_vma * data_offs;
1460 bfd_signed_vma * bss_offs;
1461 {
1462 bfd_vma text_base, data_base, bss_base;
1463 struct minimal_symbol *start;
1464 asection *sect;
1465 bfd * abfd;
1466 int len;
1467 char *p;
1468
1469 if (symfile_objfile == NULL)
1470 return -1; /* no can do nothin' */
1471
1472 start = lookup_minimal_symbol ("_start", NULL, NULL);
1473 if (start == NULL)
1474 return -1; /* Can't find "_start" symbol */
1475
1476 data_base = bss_base = 0;
1477 text_base = SYMBOL_VALUE_ADDRESS (start);
1478
1479 abfd = symfile_objfile->obfd;
1480 for (sect = abfd->sections;
1481 sect != 0;
1482 sect = sect->next)
1483 {
1484 p = (unsigned char *) bfd_get_section_name (abfd, sect);
1485 len = strlen (p);
1486 if (strcmp (p + len - 4, "data") == 0) /* ends in "data" */
1487 if (data_base == 0 ||
1488 data_base > bfd_get_section_vma (abfd, sect))
1489 data_base = bfd_get_section_vma (abfd, sect);
1490 if (strcmp (p + len - 3, "bss") == 0) /* ends in "bss" */
1491 if (bss_base == 0 ||
1492 bss_base > bfd_get_section_vma (abfd, sect))
1493 bss_base = bfd_get_section_vma (abfd, sect);
1494 }
1495 *text_offs = text_addr - text_base;
1496 *data_offs = data_addr - data_base;
1497 *bss_offs = bss_addr - bss_base;
1498 if (remote_debug)
1499 {
1500 char tmp[128];
1501
1502 sprintf (tmp, "VMA: text = 0x");
1503 sprintf_vma (tmp + strlen (tmp), text_addr);
1504 sprintf (tmp + strlen (tmp), " data = 0x");
1505 sprintf_vma (tmp + strlen (tmp), data_addr);
1506 sprintf (tmp + strlen (tmp), " bss = 0x");
1507 sprintf_vma (tmp + strlen (tmp), bss_addr);
1508 fprintf_filtered (gdb_stdlog, tmp);
1509 fprintf_filtered (gdb_stdlog,
1510 "Reloc offset: text = 0x%x data = 0x%x bss = 0x%x\n",
1511 (long) *text_offs, (long) *data_offs, (long) *bss_offs);
1512 }
1513
1514 return 0;
1515 }
1516
1517 /*
1518 * Function: remote_cisco_objfile_relocate
1519 *
1520 * Relocate the symbol file for a remote target.
1521 */
1522
1523 static void
1524 remote_cisco_objfile_relocate (text_off, data_off, bss_off)
1525 bfd_signed_vma text_off;
1526 bfd_signed_vma data_off;
1527 bfd_signed_vma bss_off;
1528 {
1529 struct section_offsets *offs;
1530
1531 if (text_off != 0 || data_off != 0 || bss_off != 0)
1532 {
1533 /* FIXME: This code assumes gdb-stabs.h is being used; it's
1534 broken for xcoff, dwarf, sdb-coff, etc. But there is no
1535 simple canonical representation for this stuff. */
1536
1537 offs = ((struct section_offsets *)
1538 alloca (sizeof (struct section_offsets)
1539 + (symfile_objfile->num_sections
1540 * sizeof (offs->offsets))));
1541
1542 memcpy (offs, symfile_objfile->section_offsets,
1543 (sizeof (struct section_offsets)
1544 + (symfile_objfile->num_sections
1545 * sizeof (offs->offsets))));
1546
1547 ANOFFSET (offs, SECT_OFF_TEXT) = text_off;
1548 ANOFFSET (offs, SECT_OFF_DATA) = data_off;
1549 ANOFFSET (offs, SECT_OFF_BSS) = bss_off;
1550
1551 /* First call the standard objfile_relocate. */
1552 objfile_relocate (symfile_objfile, offs);
1553
1554 /* Now we need to fix up the section entries already attached to
1555 the exec target. These entries will control memory transfers
1556 from the exec file. */
1557
1558 exec_set_section_offsets (text_off, data_off, bss_off);
1559 }
1560 }
1561
1562 /* Stub for catch_errors. */
1563
1564 static int
1565 remote_start_remote_dummy (dummy)
1566 char *dummy;
1567 {
1568 start_remote (); /* Initialize gdb process mechanisms */
1569 return 1;
1570 }
1571
1572 static int
1573 remote_start_remote (dummy)
1574 PTR dummy;
1575 {
1576 immediate_quit = 1; /* Allow user to interrupt it */
1577
1578 /* Ack any packet which the remote side has already sent. */
1579 SERIAL_WRITE (remote_desc, "+", 1);
1580
1581 /* Let the stub know that we want it to return the thread. */
1582 set_thread (-1, 0);
1583
1584 inferior_pid = remote_current_thread (inferior_pid);
1585
1586 get_offsets (); /* Get text, data & bss offsets */
1587
1588 putpkt ("?"); /* initiate a query from remote machine */
1589 immediate_quit = 0;
1590
1591 return remote_start_remote_dummy (dummy);
1592 }
1593
1594 /* Open a connection to a remote debugger.
1595 NAME is the filename used for communication. */
1596
1597 static void
1598 remote_open (name, from_tty)
1599 char *name;
1600 int from_tty;
1601 {
1602 remote_open_1 (name, from_tty, &remote_ops, 0);
1603 }
1604
1605 /* Open a connection to a remote debugger using the extended
1606 remote gdb protocol. NAME is the filename used for communication. */
1607
1608 static void
1609 extended_remote_open (name, from_tty)
1610 char *name;
1611 int from_tty;
1612 {
1613 remote_open_1 (name, from_tty, &extended_remote_ops, 1/*extended_p*/);
1614 }
1615
1616 /* Generic code for opening a connection to a remote target. */
1617
1618 static DCACHE *remote_dcache;
1619
1620 static void
1621 remote_open_1 (name, from_tty, target, extended_p)
1622 char *name;
1623 int from_tty;
1624 struct target_ops *target;
1625 int extended_p;
1626 {
1627 if (name == 0)
1628 error ("To open a remote debug connection, you need to specify what\n\
1629 serial device is attached to the remote system (e.g. /dev/ttya).");
1630
1631 target_preopen (from_tty);
1632
1633 unpush_target (target);
1634
1635 remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
1636
1637 remote_desc = SERIAL_OPEN (name);
1638 if (!remote_desc)
1639 perror_with_name (name);
1640
1641 if (baud_rate != -1)
1642 {
1643 if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
1644 {
1645 SERIAL_CLOSE (remote_desc);
1646 perror_with_name (name);
1647 }
1648 }
1649
1650
1651 SERIAL_RAW (remote_desc);
1652
1653 /* If there is something sitting in the buffer we might take it as a
1654 response to a command, which would be bad. */
1655 SERIAL_FLUSH_INPUT (remote_desc);
1656
1657 if (from_tty)
1658 {
1659 puts_filtered ("Remote debugging using ");
1660 puts_filtered (name);
1661 puts_filtered ("\n");
1662 }
1663 push_target (target); /* Switch to using remote target now */
1664
1665 /* Start out by trying the 'P' request to set registers. We set
1666 this each time that we open a new target so that if the user
1667 switches from one stub to another, we can (if the target is
1668 closed and reopened) cope. */
1669 stub_supports_P = 1;
1670
1671 general_thread = -2;
1672 continue_thread = -2;
1673
1674 /* Force remote_write_bytes to check whether target supports
1675 binary downloading. */
1676 remote_binary_checked = 0;
1677
1678 /* Without this, some commands which require an active target (such
1679 as kill) won't work. This variable serves (at least) double duty
1680 as both the pid of the target process (if it has such), and as a
1681 flag indicating that a target is active. These functions should
1682 be split out into seperate variables, especially since GDB will
1683 someday have a notion of debugging several processes. */
1684
1685 inferior_pid = MAGIC_NULL_PID;
1686 /* Start the remote connection; if error (0), discard this target.
1687 In particular, if the user quits, be sure to discard it
1688 (we'd be in an inconsistent state otherwise). */
1689 if (!catch_errors (remote_start_remote, NULL,
1690 "Couldn't establish connection to remote target\n",
1691 RETURN_MASK_ALL))
1692 {
1693 pop_target ();
1694 return;
1695 }
1696
1697 if (extended_p)
1698 {
1699 /* tell the remote that we're using the extended protocol. */
1700 char buf[PBUFSIZ];
1701 putpkt ("!");
1702 getpkt (buf, 0);
1703 }
1704 }
1705
1706 /* This takes a program previously attached to and detaches it. After
1707 this is done, GDB can be used to debug some other program. We
1708 better not have left any breakpoints in the target program or it'll
1709 die when it hits one. */
1710
1711 static void
1712 remote_detach (args, from_tty)
1713 char *args;
1714 int from_tty;
1715 {
1716 char buf[PBUFSIZ];
1717
1718 if (args)
1719 error ("Argument given to \"detach\" when remotely debugging.");
1720
1721 /* Tell the remote target to detach. */
1722 strcpy (buf, "D");
1723 remote_send (buf);
1724
1725 pop_target ();
1726 if (from_tty)
1727 puts_filtered ("Ending remote debugging.\n");
1728 }
1729
1730 /* Convert hex digit A to a number. */
1731
1732 int
1733 fromhex (a)
1734 int a;
1735 {
1736 if (a >= '0' && a <= '9')
1737 return a - '0';
1738 else if (a >= 'a' && a <= 'f')
1739 return a - 'a' + 10;
1740 else if (a >= 'A' && a <= 'F')
1741 return a - 'A' + 10;
1742 else
1743 error ("Reply contains invalid hex digit %d", a);
1744 }
1745
1746 /* Convert number NIB to a hex digit. */
1747
1748 static int
1749 tohex (nib)
1750 int nib;
1751 {
1752 if (nib < 10)
1753 return '0'+nib;
1754 else
1755 return 'a'+nib-10;
1756 }
1757 \f
1758 /* Tell the remote machine to resume. */
1759
1760 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
1761
1762 static int last_sent_step;
1763
1764 static void
1765 remote_resume (pid, step, siggnal)
1766 int pid, step;
1767 enum target_signal siggnal;
1768 {
1769 char buf[PBUFSIZ];
1770
1771 if (pid == -1)
1772 set_thread (0, 0); /* run any thread */
1773 else
1774 set_thread (pid, 0); /* run this thread */
1775
1776 dcache_flush (remote_dcache);
1777
1778 last_sent_signal = siggnal;
1779 last_sent_step = step;
1780
1781 /* A hook for when we need to do something at the last moment before
1782 resumption. */
1783 if (target_resume_hook)
1784 (*target_resume_hook) ();
1785
1786 if (siggnal != TARGET_SIGNAL_0)
1787 {
1788 buf[0] = step ? 'S' : 'C';
1789 buf[1] = tohex (((int)siggnal >> 4) & 0xf);
1790 buf[2] = tohex ((int)siggnal & 0xf);
1791 buf[3] = '\0';
1792 }
1793 else
1794 strcpy (buf, step ? "s": "c");
1795
1796 putpkt (buf);
1797 }
1798 \f
1799 /* Send ^C to target to halt it. Target will respond, and send us a
1800 packet. */
1801
1802 static void (*ofunc) PARAMS ((int));
1803
1804 /* The command line interface's stop routine. This function is installed
1805 as a signal handler for SIGINT. The first time a user requests a
1806 stop, we call remote_stop to send a break or ^C. If there is no
1807 response from the target (it didn't stop when the user requested it),
1808 we ask the user if he'd like to detach from the target. */
1809 static void
1810 remote_interrupt (signo)
1811 int signo;
1812 {
1813 /* If this doesn't work, try more severe steps. */
1814 signal (signo, remote_interrupt_twice);
1815
1816 if (remote_debug)
1817 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
1818
1819 target_stop ();
1820 }
1821
1822 /* The user typed ^C twice. */
1823
1824 static void
1825 remote_interrupt_twice (signo)
1826 int signo;
1827 {
1828 signal (signo, ofunc);
1829 interrupt_query ();
1830 signal (signo, remote_interrupt);
1831 }
1832
1833 /* This is the generic stop called via the target vector. When a target
1834 interrupt is requested, either by the command line or the GUI, we
1835 will eventually end up here. */
1836 static void
1837 remote_stop ()
1838 {
1839 /* Send a break or a ^C, depending on user preference. */
1840 if (remote_debug)
1841 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
1842
1843 if (remote_break)
1844 SERIAL_SEND_BREAK (remote_desc);
1845 else
1846 SERIAL_WRITE (remote_desc, "\003", 1);
1847 }
1848
1849 /* Ask the user what to do when an interrupt is received. */
1850
1851 static void
1852 interrupt_query ()
1853 {
1854 target_terminal_ours ();
1855
1856 if (query ("Interrupted while waiting for the program.\n\
1857 Give up (and stop debugging it)? "))
1858 {
1859 target_mourn_inferior ();
1860 return_to_top_level (RETURN_QUIT);
1861 }
1862
1863 target_terminal_inferior ();
1864 }
1865
1866 /* If nonzero, ignore the next kill. */
1867
1868 int kill_kludge;
1869
1870 void
1871 remote_console_output (msg)
1872 char *msg;
1873 {
1874 char *p;
1875
1876 for (p = msg; *p; p +=2)
1877 {
1878 char tb[2];
1879 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
1880 tb[0] = c;
1881 tb[1] = 0;
1882 if (target_output_hook)
1883 target_output_hook (tb);
1884 else
1885 fputs_filtered (tb, gdb_stdout);
1886 }
1887 }
1888
1889 /* Wait until the remote machine stops, then return,
1890 storing status in STATUS just as `wait' would.
1891 Returns "pid", which in the case of a multi-threaded
1892 remote OS, is the thread-id. */
1893
1894 static int
1895 remote_wait (pid, status)
1896 int pid;
1897 struct target_waitstatus *status;
1898 {
1899 unsigned char buf[PBUFSIZ];
1900 int thread_num = -1;
1901
1902 status->kind = TARGET_WAITKIND_EXITED;
1903 status->value.integer = 0;
1904
1905 while (1)
1906 {
1907 unsigned char *p;
1908
1909 ofunc = signal (SIGINT, remote_interrupt);
1910 getpkt ((char *) buf, 1);
1911 signal (SIGINT, ofunc);
1912
1913 /* This is a hook for when we need to do something (perhaps the
1914 collection of trace data) every time the target stops. */
1915 if (target_wait_loop_hook)
1916 (*target_wait_loop_hook) ();
1917
1918 switch (buf[0])
1919 {
1920 case 'E': /* Error of some sort */
1921 warning ("Remote failure reply: %s", buf);
1922 continue;
1923 case 'T': /* Status with PC, SP, FP, ... */
1924 {
1925 int i;
1926 long regno;
1927 char regs[MAX_REGISTER_RAW_SIZE];
1928
1929 /* Expedited reply, containing Signal, {regno, reg} repeat */
1930 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
1931 ss = signal number
1932 n... = register number
1933 r... = register contents
1934 */
1935 p = &buf[3]; /* after Txx */
1936
1937 while (*p)
1938 {
1939 unsigned char *p1;
1940 char *p_temp;
1941
1942 /* Read the register number */
1943 regno = strtol ((const char *) p, &p_temp, 16);
1944 p1 = (unsigned char *)p_temp;
1945
1946 if (p1 == p) /* No register number present here */
1947 {
1948 p1 = (unsigned char *) strchr ((const char *) p, ':');
1949 if (p1 == NULL)
1950 warning ("Malformed packet(a) (missing colon): %s\n\
1951 Packet: '%s'\n",
1952 p, buf);
1953 if (strncmp ((const char *) p, "thread", p1 - p) == 0)
1954 {
1955 p_temp = unpack_varlen_hex (++p1, &thread_num);
1956 record_currthread (thread_num);
1957 p = (unsigned char *) p_temp;
1958 }
1959 }
1960 else
1961 {
1962 p = p1;
1963
1964 if (*p++ != ':')
1965 warning ("Malformed packet(b) (missing colon): %s\n\
1966 Packet: '%s'\n",
1967 p, buf);
1968
1969 if (regno >= NUM_REGS)
1970 warning ("Remote sent bad register number %ld: %s\n\
1971 Packet: '%s'\n",
1972 regno, p, buf);
1973
1974 for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
1975 {
1976 if (p[0] == 0 || p[1] == 0)
1977 warning ("Remote reply is too short: %s", buf);
1978 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
1979 p += 2;
1980 }
1981 supply_register (regno, regs);
1982 }
1983
1984 if (*p++ != ';')
1985 {
1986 warning ("Remote register badly formatted: %s", buf);
1987 warning (" here: %s",p);
1988 }
1989 }
1990 }
1991 /* fall through */
1992 case 'S': /* Old style status, just signal only */
1993 status->kind = TARGET_WAITKIND_STOPPED;
1994 status->value.sig = (enum target_signal)
1995 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
1996
1997 if (buf[3] == 'p')
1998 {
1999 /* Export Cisco kernel mode as a convenience variable
2000 (so that it can be used in the GDB prompt if desired). */
2001
2002 if (cisco_kernel_mode == 1)
2003 set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
2004 value_from_string ("PDEBUG-"));
2005 cisco_kernel_mode = 0;
2006 thread_num = strtol ((const char *) &buf[4], NULL, 16);
2007 record_currthread (thread_num);
2008 }
2009 else if (buf[3] == 'k')
2010 {
2011 /* Export Cisco kernel mode as a convenience variable
2012 (so that it can be used in the GDB prompt if desired). */
2013
2014 if (cisco_kernel_mode == 1)
2015 set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
2016 value_from_string ("KDEBUG-"));
2017 cisco_kernel_mode = 1;
2018 }
2019 goto got_status;
2020 case 'N': /* Cisco special: status and offsets */
2021 {
2022 bfd_vma text_addr, data_addr, bss_addr;
2023 bfd_signed_vma text_off, data_off, bss_off;
2024 unsigned char *p1;
2025
2026 status->kind = TARGET_WAITKIND_STOPPED;
2027 status->value.sig = (enum target_signal)
2028 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
2029
2030 if (symfile_objfile == NULL)
2031 {
2032 warning ("Relocation packet recieved with no symbol file. \
2033 Packet Dropped");
2034 goto got_status;
2035 }
2036
2037 /* Relocate object file. Buffer format is NAATT;DD;BB
2038 * where AA is the signal number, TT is the new text
2039 * address, DD * is the new data address, and BB is the
2040 * new bss address. */
2041
2042 p = &buf[3];
2043 text_addr = strtoul (p, (char **) &p1, 16);
2044 if (p1 == p || *p1 != ';')
2045 warning ("Malformed relocation packet: Packet '%s'", buf);
2046 p = p1 + 1;
2047 data_addr = strtoul (p, (char **) &p1, 16);
2048 if (p1 == p || *p1 != ';')
2049 warning ("Malformed relocation packet: Packet '%s'", buf);
2050 p = p1 + 1;
2051 bss_addr = strtoul (p, (char **) &p1, 16);
2052 if (p1 == p)
2053 warning ("Malformed relocation packet: Packet '%s'", buf);
2054
2055 if (remote_cisco_section_offsets (text_addr, data_addr, bss_addr,
2056 &text_off, &data_off, &bss_off)
2057 == 0)
2058 if (text_off != 0 || data_off != 0 || bss_off != 0)
2059 remote_cisco_objfile_relocate (text_off, data_off, bss_off);
2060
2061 goto got_status;
2062 }
2063 case 'W': /* Target exited */
2064 {
2065 /* The remote process exited. */
2066 status->kind = TARGET_WAITKIND_EXITED;
2067 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
2068 goto got_status;
2069 }
2070 case 'X':
2071 status->kind = TARGET_WAITKIND_SIGNALLED;
2072 status->value.sig = (enum target_signal)
2073 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
2074 kill_kludge = 1;
2075
2076 goto got_status;
2077 case 'O': /* Console output */
2078 remote_console_output (buf + 1);
2079 continue;
2080 case '\0':
2081 if (last_sent_signal != TARGET_SIGNAL_0)
2082 {
2083 /* Zero length reply means that we tried 'S' or 'C' and
2084 the remote system doesn't support it. */
2085 target_terminal_ours_for_output ();
2086 printf_filtered
2087 ("Can't send signals to this remote system. %s not sent.\n",
2088 target_signal_to_name (last_sent_signal));
2089 last_sent_signal = TARGET_SIGNAL_0;
2090 target_terminal_inferior ();
2091
2092 strcpy ((char *) buf, last_sent_step ? "s" : "c");
2093 putpkt ((char *) buf);
2094 continue;
2095 }
2096 /* else fallthrough */
2097 default:
2098 warning ("Invalid remote reply: %s", buf);
2099 continue;
2100 }
2101 }
2102 got_status:
2103 if (thread_num != -1)
2104 {
2105 return thread_num;
2106 }
2107 return inferior_pid;
2108 }
2109
2110 /* Number of bytes of registers this stub implements. */
2111
2112 static int register_bytes_found;
2113
2114 /* Read the remote registers into the block REGS. */
2115 /* Currently we just read all the registers, so we don't use regno. */
2116
2117 /* ARGSUSED */
2118 static void
2119 remote_fetch_registers (regno)
2120 int regno;
2121 {
2122 char buf[PBUFSIZ];
2123 int i;
2124 char *p;
2125 char regs[REGISTER_BYTES];
2126
2127 set_thread (inferior_pid, 1);
2128
2129 sprintf (buf, "g");
2130 remote_send (buf);
2131
2132 if (remote_register_buf_size == 0)
2133 remote_register_buf_size = strlen (buf);
2134
2135 /* Unimplemented registers read as all bits zero. */
2136 memset (regs, 0, REGISTER_BYTES);
2137
2138 /* We can get out of synch in various cases. If the first character
2139 in the buffer is not a hex character, assume that has happened
2140 and try to fetch another packet to read. */
2141 while ((buf[0] < '0' || buf[0] > '9')
2142 && (buf[0] < 'a' || buf[0] > 'f')
2143 && buf[0] != 'x') /* New: unavailable register value */
2144 {
2145 if (remote_debug)
2146 fprintf_unfiltered (gdb_stdlog,
2147 "Bad register packet; fetching a new packet\n");
2148 getpkt (buf, 0);
2149 }
2150
2151 /* Reply describes registers byte by byte, each byte encoded as two
2152 hex characters. Suck them all up, then supply them to the
2153 register cacheing/storage mechanism. */
2154
2155 p = buf;
2156 for (i = 0; i < REGISTER_BYTES; i++)
2157 {
2158 if (p[0] == 0)
2159 break;
2160 if (p[1] == 0)
2161 {
2162 warning ("Remote reply is of odd length: %s", buf);
2163 /* Don't change register_bytes_found in this case, and don't
2164 print a second warning. */
2165 goto supply_them;
2166 }
2167 if (p[0] == 'x' && p[1] == 'x')
2168 regs[i] = 0; /* 'x' */
2169 else
2170 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
2171 p += 2;
2172 }
2173
2174 if (i != register_bytes_found)
2175 {
2176 register_bytes_found = i;
2177 #ifdef REGISTER_BYTES_OK
2178 if (!REGISTER_BYTES_OK (i))
2179 warning ("Remote reply is too short: %s", buf);
2180 #endif
2181 }
2182
2183 supply_them:
2184 for (i = 0; i < NUM_REGS; i++)
2185 {
2186 supply_register (i, &regs[REGISTER_BYTE(i)]);
2187 if (buf[REGISTER_BYTE(i) * 2] == 'x')
2188 register_valid[i] = -1; /* register value not available */
2189 }
2190 }
2191
2192 /* Prepare to store registers. Since we may send them all (using a
2193 'G' request), we have to read out the ones we don't want to change
2194 first. */
2195
2196 static void
2197 remote_prepare_to_store ()
2198 {
2199 /* Make sure the entire registers array is valid. */
2200 read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
2201 }
2202
2203 /* Store register REGNO, or all registers if REGNO == -1, from the contents
2204 of REGISTERS. FIXME: ignores errors. */
2205
2206 static void
2207 remote_store_registers (regno)
2208 int regno;
2209 {
2210 char buf[PBUFSIZ];
2211 int i;
2212 char *p;
2213
2214 set_thread (inferior_pid, 1);
2215
2216 if (regno >= 0 && stub_supports_P)
2217 {
2218 /* Try storing a single register. */
2219 char *regp;
2220
2221 sprintf (buf, "P%x=", regno);
2222 p = buf + strlen (buf);
2223 regp = &registers[REGISTER_BYTE (regno)];
2224 for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
2225 {
2226 *p++ = tohex ((regp[i] >> 4) & 0xf);
2227 *p++ = tohex (regp[i] & 0xf);
2228 }
2229 *p = '\0';
2230 remote_send (buf);
2231 if (buf[0] != '\0')
2232 {
2233 /* The stub understands the 'P' request. We are done. */
2234 return;
2235 }
2236
2237 /* The stub does not support the 'P' request. Use 'G' instead,
2238 and don't try using 'P' in the future (it will just waste our
2239 time). */
2240 stub_supports_P = 0;
2241 }
2242
2243 buf[0] = 'G';
2244
2245 /* Command describes registers byte by byte,
2246 each byte encoded as two hex characters. */
2247
2248 p = buf + 1;
2249 /* remote_prepare_to_store insures that register_bytes_found gets set. */
2250 for (i = 0; i < register_bytes_found; i++)
2251 {
2252 *p++ = tohex ((registers[i] >> 4) & 0xf);
2253 *p++ = tohex (registers[i] & 0xf);
2254 }
2255 *p = '\0';
2256
2257 remote_send (buf);
2258 }
2259
2260 /* Use of the data cache *used* to be disabled because it loses for looking
2261 at and changing hardware I/O ports and the like. Accepting `volatile'
2262 would perhaps be one way to fix it. Another idea would be to use the
2263 executable file for the text segment (for all SEC_CODE sections?
2264 For all SEC_READONLY sections?). This has problems if you want to
2265 actually see what the memory contains (e.g. self-modifying code,
2266 clobbered memory, user downloaded the wrong thing).
2267
2268 Because it speeds so much up, it's now enabled, if you're playing
2269 with registers you turn it of (set remotecache 0). */
2270
2271 /* Read a word from remote address ADDR and return it.
2272 This goes through the data cache. */
2273
2274 #if 0 /* unused? */
2275 static int
2276 remote_fetch_word (addr)
2277 CORE_ADDR addr;
2278 {
2279 return dcache_fetch (remote_dcache, addr);
2280 }
2281
2282 /* Write a word WORD into remote address ADDR.
2283 This goes through the data cache. */
2284
2285 static void
2286 remote_store_word (addr, word)
2287 CORE_ADDR addr;
2288 int word;
2289 {
2290 dcache_poke (remote_dcache, addr, word);
2291 }
2292 #endif /* 0 (unused?) */
2293
2294 \f
2295
2296 /* Return the number of hex digits in num. */
2297
2298 static int
2299 hexnumlen (num)
2300 ULONGEST num;
2301 {
2302 int i;
2303
2304 for (i = 0; num != 0; i++)
2305 num >>= 4;
2306
2307 return max (i, 1);
2308 }
2309
2310 /* Set BUF to the hex digits representing NUM. */
2311
2312 static int
2313 hexnumstr (buf, num)
2314 char *buf;
2315 ULONGEST num;
2316 {
2317 int i;
2318 int len = hexnumlen (num);
2319
2320 buf[len] = '\0';
2321
2322 for (i = len - 1; i >= 0; i--)
2323 {
2324 buf[i] = "0123456789abcdef" [(num & 0xf)];
2325 num >>= 4;
2326 }
2327
2328 return len;
2329 }
2330
2331 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
2332
2333 static CORE_ADDR
2334 remote_address_masked (addr)
2335 CORE_ADDR addr;
2336 {
2337 if (remote_address_size > 0
2338 && remote_address_size < (sizeof (ULONGEST) * 8))
2339 {
2340 /* Only create a mask when that mask can safely be constructed
2341 in a ULONGEST variable. */
2342 ULONGEST mask = 1;
2343 mask = (mask << remote_address_size) - 1;
2344 addr &= mask;
2345 }
2346 return addr;
2347 }
2348
2349 /* Determine whether the remote target supports binary downloading.
2350 This is accomplished by sending a no-op memory write of zero length
2351 to the target at the specified address. It does not suffice to send
2352 the whole packet, since many stubs strip the eighth bit and subsequently
2353 compute a wrong checksum, which causes real havoc with remote_write_bytes.
2354
2355 NOTE: This can still lose if the serial line is not eight-bit clean. In
2356 cases like this, the user should clear "remotebinarydownload". */
2357 static void
2358 check_binary_download (addr)
2359 CORE_ADDR addr;
2360 {
2361 if (remote_binary_download && !remote_binary_checked)
2362 {
2363 char buf[PBUFSIZ], *p;
2364 remote_binary_checked = 1;
2365
2366 p = buf;
2367 *p++ = 'X';
2368 p += hexnumstr (p, (ULONGEST) addr);
2369 *p++ = ',';
2370 p += hexnumstr (p, (ULONGEST) 0);
2371 *p++ = ':';
2372 *p = '\0';
2373
2374 putpkt_binary (buf, (int) (p - buf));
2375 getpkt (buf, 0);
2376
2377 if (buf[0] == '\0')
2378 remote_binary_download = 0;
2379 }
2380
2381 if (remote_debug)
2382 {
2383 if (remote_binary_download)
2384 fprintf_unfiltered (gdb_stdlog,
2385 "binary downloading suppported by target\n");
2386 else
2387 fprintf_unfiltered (gdb_stdlog,
2388 "binary downloading NOT suppported by target\n");
2389 }
2390 }
2391
2392 /* Write memory data directly to the remote machine.
2393 This does not inform the data cache; the data cache uses this.
2394 MEMADDR is the address in the remote memory space.
2395 MYADDR is the address of the buffer in our space.
2396 LEN is the number of bytes.
2397
2398 Returns number of bytes transferred, or 0 for error. */
2399
2400 static int
2401 remote_write_bytes (memaddr, myaddr, len)
2402 CORE_ADDR memaddr;
2403 char *myaddr;
2404 int len;
2405 {
2406 int max_buf_size; /* Max size of packet output buffer */
2407 int origlen;
2408
2409 /* Verify that the target can support a binary download */
2410 check_binary_download (memaddr);
2411
2412 /* Chop the transfer down if necessary */
2413
2414 max_buf_size = min (remote_write_size, PBUFSIZ);
2415 if (remote_register_buf_size != 0)
2416 max_buf_size = min (max_buf_size, remote_register_buf_size);
2417
2418 /* Subtract header overhead from max payload size - $M<memaddr>,<len>:#nn */
2419 max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4;
2420
2421 origlen = len;
2422 while (len > 0)
2423 {
2424 unsigned char buf[PBUFSIZ];
2425 unsigned char *p, *plen;
2426 int todo;
2427 int i;
2428
2429 /* construct "M"<memaddr>","<len>":" */
2430 /* sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo); */
2431 memaddr = remote_address_masked (memaddr);
2432 p = buf;
2433 if (remote_binary_download)
2434 {
2435 *p++ = 'X';
2436 todo = min (len, max_buf_size);
2437 }
2438 else
2439 {
2440 *p++ = 'M';
2441 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
2442 }
2443
2444 p += hexnumstr (p, (ULONGEST) memaddr);
2445 *p++ = ',';
2446
2447 plen = p; /* remember where len field goes */
2448 p += hexnumstr (p, (ULONGEST) todo);
2449 *p++ = ':';
2450 *p = '\0';
2451
2452 /* We send target system values byte by byte, in increasing byte
2453 addresses, each byte encoded as two hex characters (or one
2454 binary character). */
2455 if (remote_binary_download)
2456 {
2457 int escaped = 0;
2458 for (i = 0;
2459 (i < todo) && (i + escaped) < (max_buf_size - 2);
2460 i++)
2461 {
2462 switch (myaddr[i] & 0xff)
2463 {
2464 case '$':
2465 case '#':
2466 case 0x7d:
2467 /* These must be escaped */
2468 escaped++;
2469 *p++ = 0x7d;
2470 *p++ = (myaddr[i] & 0xff) ^ 0x20;
2471 break;
2472 default:
2473 *p++ = myaddr[i] & 0xff;
2474 break;
2475 }
2476 }
2477
2478 if (i < todo)
2479 {
2480 /* Escape chars have filled up the buffer prematurely,
2481 and we have actually sent fewer bytes than planned.
2482 Fix-up the length field of the packet. */
2483
2484 /* FIXME: will fail if new len is a shorter string than
2485 old len. */
2486
2487 plen += hexnumstr (plen, (ULONGEST) i);
2488 *plen++ = ':';
2489 }
2490 }
2491 else
2492 {
2493 for (i = 0; i < todo; i++)
2494 {
2495 *p++ = tohex ((myaddr[i] >> 4) & 0xf);
2496 *p++ = tohex (myaddr[i] & 0xf);
2497 }
2498 *p = '\0';
2499 }
2500
2501 putpkt_binary (buf, (int) (p - buf));
2502 getpkt (buf, 0);
2503
2504 if (buf[0] == 'E')
2505 {
2506 /* There is no correspondance between what the remote protocol uses
2507 for errors and errno codes. We would like a cleaner way of
2508 representing errors (big enough to include errno codes, bfd_error
2509 codes, and others). But for now just return EIO. */
2510 errno = EIO;
2511 return 0;
2512 }
2513
2514 /* Increment by i, not by todo, in case escape chars
2515 caused us to send fewer bytes than we'd planned. */
2516 myaddr += i;
2517 memaddr += i;
2518 len -= i;
2519 }
2520 return origlen;
2521 }
2522
2523 /* Read memory data directly from the remote machine.
2524 This does not use the data cache; the data cache uses this.
2525 MEMADDR is the address in the remote memory space.
2526 MYADDR is the address of the buffer in our space.
2527 LEN is the number of bytes.
2528
2529 Returns number of bytes transferred, or 0 for error. */
2530
2531 static int
2532 remote_read_bytes (memaddr, myaddr, len)
2533 CORE_ADDR memaddr;
2534 char *myaddr;
2535 int len;
2536 {
2537 int max_buf_size; /* Max size of packet output buffer */
2538 int origlen;
2539
2540 /* Chop the transfer down if necessary */
2541
2542 max_buf_size = min (remote_write_size, PBUFSIZ);
2543 if (remote_register_buf_size != 0)
2544 max_buf_size = min (max_buf_size, remote_register_buf_size);
2545
2546 origlen = len;
2547 while (len > 0)
2548 {
2549 char buf[PBUFSIZ];
2550 char *p;
2551 int todo;
2552 int i;
2553
2554 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
2555
2556 /* construct "m"<memaddr>","<len>" */
2557 /* sprintf (buf, "m%lx,%x", (unsigned long) memaddr, todo); */
2558 memaddr = remote_address_masked (memaddr);
2559 p = buf;
2560 *p++ = 'm';
2561 p += hexnumstr (p, (ULONGEST) memaddr);
2562 *p++ = ',';
2563 p += hexnumstr (p, (ULONGEST) todo);
2564 *p = '\0';
2565
2566 putpkt (buf);
2567 getpkt (buf, 0);
2568
2569 if (buf[0] == 'E')
2570 {
2571 /* There is no correspondance between what the remote protocol uses
2572 for errors and errno codes. We would like a cleaner way of
2573 representing errors (big enough to include errno codes, bfd_error
2574 codes, and others). But for now just return EIO. */
2575 errno = EIO;
2576 return 0;
2577 }
2578
2579 /* Reply describes memory byte by byte,
2580 each byte encoded as two hex characters. */
2581
2582 p = buf;
2583 for (i = 0; i < todo; i++)
2584 {
2585 if (p[0] == 0 || p[1] == 0)
2586 /* Reply is short. This means that we were able to read
2587 only part of what we wanted to. */
2588 return i + (origlen - len);
2589 myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
2590 p += 2;
2591 }
2592 myaddr += todo;
2593 memaddr += todo;
2594 len -= todo;
2595 }
2596 return origlen;
2597 }
2598 \f
2599 /* Read or write LEN bytes from inferior memory at MEMADDR,
2600 transferring to or from debugger address BUFFER. Write to inferior if
2601 SHOULD_WRITE is nonzero. Returns length of data written or read; 0
2602 for error. */
2603
2604 #ifndef REMOTE_TRANSLATE_XFER_ADDRESS
2605 #define REMOTE_TRANSLATE_XFER_ADDRESS(MEM_ADDR, MEM_LEN, TARG_ADDR, TARG_LEN) \
2606 (*(TARG_ADDR) = (MEM_ADDR), *(TARG_LEN) = (MEM_LEN))
2607 #endif
2608
2609 /* ARGSUSED */
2610 static int
2611 remote_xfer_memory (mem_addr, buffer, mem_len, should_write, target)
2612 CORE_ADDR mem_addr;
2613 char *buffer;
2614 int mem_len;
2615 int should_write;
2616 struct target_ops *target; /* ignored */
2617 {
2618 CORE_ADDR targ_addr;
2619 int targ_len;
2620 REMOTE_TRANSLATE_XFER_ADDRESS (mem_addr, mem_len, &targ_addr, &targ_len);
2621 if (targ_len <= 0)
2622 return 0;
2623
2624 return dcache_xfer_memory (remote_dcache, targ_addr, buffer,
2625 targ_len, should_write);
2626 }
2627
2628
2629 #if 0
2630 /* Enable after 4.12. */
2631
2632 void
2633 remote_search (len, data, mask, startaddr, increment, lorange, hirange
2634 addr_found, data_found)
2635 int len;
2636 char *data;
2637 char *mask;
2638 CORE_ADDR startaddr;
2639 int increment;
2640 CORE_ADDR lorange;
2641 CORE_ADDR hirange;
2642 CORE_ADDR *addr_found;
2643 char *data_found;
2644 {
2645 if (increment == -4 && len == 4)
2646 {
2647 long mask_long, data_long;
2648 long data_found_long;
2649 CORE_ADDR addr_we_found;
2650 char buf[PBUFSIZ];
2651 long returned_long[2];
2652 char *p;
2653
2654 mask_long = extract_unsigned_integer (mask, len);
2655 data_long = extract_unsigned_integer (data, len);
2656 sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
2657 putpkt (buf);
2658 getpkt (buf, 0);
2659 if (buf[0] == '\0')
2660 {
2661 /* The stub doesn't support the 't' request. We might want to
2662 remember this fact, but on the other hand the stub could be
2663 switched on us. Maybe we should remember it only until
2664 the next "target remote". */
2665 generic_search (len, data, mask, startaddr, increment, lorange,
2666 hirange, addr_found, data_found);
2667 return;
2668 }
2669
2670 if (buf[0] == 'E')
2671 /* There is no correspondance between what the remote protocol uses
2672 for errors and errno codes. We would like a cleaner way of
2673 representing errors (big enough to include errno codes, bfd_error
2674 codes, and others). But for now just use EIO. */
2675 memory_error (EIO, startaddr);
2676 p = buf;
2677 addr_we_found = 0;
2678 while (*p != '\0' && *p != ',')
2679 addr_we_found = (addr_we_found << 4) + fromhex (*p++);
2680 if (*p == '\0')
2681 error ("Protocol error: short return for search");
2682
2683 data_found_long = 0;
2684 while (*p != '\0' && *p != ',')
2685 data_found_long = (data_found_long << 4) + fromhex (*p++);
2686 /* Ignore anything after this comma, for future extensions. */
2687
2688 if (addr_we_found < lorange || addr_we_found >= hirange)
2689 {
2690 *addr_found = 0;
2691 return;
2692 }
2693
2694 *addr_found = addr_we_found;
2695 *data_found = store_unsigned_integer (data_we_found, len);
2696 return;
2697 }
2698 generic_search (len, data, mask, startaddr, increment, lorange,
2699 hirange, addr_found, data_found);
2700 }
2701 #endif /* 0 */
2702 \f
2703 static void
2704 remote_files_info (ignore)
2705 struct target_ops *ignore;
2706 {
2707 puts_filtered ("Debugging a target over a serial line.\n");
2708 }
2709 \f
2710 /* Stuff for dealing with the packets which are part of this protocol.
2711 See comment at top of file for details. */
2712
2713 /* Read a single character from the remote end, masking it down to 7 bits. */
2714
2715 static int
2716 readchar (timeout)
2717 int timeout;
2718 {
2719 int ch;
2720
2721 ch = SERIAL_READCHAR (remote_desc, timeout);
2722
2723 switch (ch)
2724 {
2725 case SERIAL_EOF:
2726 error ("Remote connection closed");
2727 case SERIAL_ERROR:
2728 perror_with_name ("Remote communication error");
2729 case SERIAL_TIMEOUT:
2730 return ch;
2731 default:
2732 return ch & 0x7f;
2733 }
2734 }
2735
2736 /* Send the command in BUF to the remote machine, and read the reply
2737 into BUF. Report an error if we get an error reply. */
2738
2739 static void
2740 remote_send (buf)
2741 char *buf;
2742 {
2743 putpkt (buf);
2744 getpkt (buf, 0);
2745
2746 if (buf[0] == 'E')
2747 error ("Remote failure reply: %s", buf);
2748 }
2749
2750 /* Display a null-terminated packet on stdout, for debugging, using C
2751 string notation. */
2752
2753 static void
2754 print_packet (buf)
2755 char *buf;
2756 {
2757 puts_filtered ("\"");
2758 while (*buf)
2759 gdb_printchar (*buf++, gdb_stdout, '"');
2760 puts_filtered ("\"");
2761 }
2762
2763 int
2764 putpkt (buf)
2765 char *buf;
2766 {
2767 return putpkt_binary (buf, strlen (buf));
2768 }
2769
2770 /* Send a packet to the remote machine, with error checking. The data
2771 of the packet is in BUF. The string in BUF can be at most PBUFSIZ - 5
2772 to account for the $, # and checksum, and for a possible /0 if we are
2773 debugging (remote_debug) and want to print the sent packet as a string */
2774
2775 static int
2776 putpkt_binary (buf, cnt)
2777 char *buf;
2778 int cnt;
2779 {
2780 int i;
2781 unsigned char csum = 0;
2782 char buf2[PBUFSIZ];
2783 int ch;
2784 int tcount = 0;
2785 char *p;
2786
2787 /* Copy the packet into buffer BUF2, encapsulating it
2788 and giving it a checksum. */
2789
2790 if (cnt > (int) sizeof (buf2) - 5) /* Prosanity check */
2791 abort ();
2792
2793 p = buf2;
2794 *p++ = '$';
2795
2796 for (i = 0; i < cnt; i++)
2797 {
2798 csum += buf[i];
2799 *p++ = buf[i];
2800 }
2801 *p++ = '#';
2802 *p++ = tohex ((csum >> 4) & 0xf);
2803 *p++ = tohex (csum & 0xf);
2804
2805 /* Send it over and over until we get a positive ack. */
2806
2807 while (1)
2808 {
2809 int started_error_output = 0;
2810
2811 if (remote_debug)
2812 {
2813 *p = '\0';
2814 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", buf2);
2815 gdb_flush (gdb_stdlog);
2816 }
2817 if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
2818 perror_with_name ("putpkt: write failed");
2819
2820 /* read until either a timeout occurs (-2) or '+' is read */
2821 while (1)
2822 {
2823 ch = readchar (remote_timeout);
2824
2825 if (remote_debug)
2826 {
2827 switch (ch)
2828 {
2829 case '+':
2830 case SERIAL_TIMEOUT:
2831 case '$':
2832 if (started_error_output)
2833 {
2834 putchar_unfiltered ('\n');
2835 started_error_output = 0;
2836 }
2837 }
2838 }
2839
2840 switch (ch)
2841 {
2842 case '+':
2843 if (remote_debug)
2844 fprintf_unfiltered (gdb_stdlog, "Ack\n");
2845 return 1;
2846 case SERIAL_TIMEOUT:
2847 tcount ++;
2848 if (tcount > 3)
2849 return 0;
2850 break; /* Retransmit buffer */
2851 case '$':
2852 {
2853 char junkbuf[PBUFSIZ];
2854
2855 /* It's probably an old response, and we're out of sync.
2856 Just gobble up the packet and ignore it. */
2857 getpkt (junkbuf, 0);
2858 continue; /* Now, go look for + */
2859 }
2860 default:
2861 if (remote_debug)
2862 {
2863 if (!started_error_output)
2864 {
2865 started_error_output = 1;
2866 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
2867 }
2868 fputc_unfiltered (ch & 0177, gdb_stdlog);
2869 }
2870 continue;
2871 }
2872 break; /* Here to retransmit */
2873 }
2874
2875 #if 0
2876 /* This is wrong. If doing a long backtrace, the user should be
2877 able to get out next time we call QUIT, without anything as
2878 violent as interrupt_query. If we want to provide a way out of
2879 here without getting to the next QUIT, it should be based on
2880 hitting ^C twice as in remote_wait. */
2881 if (quit_flag)
2882 {
2883 quit_flag = 0;
2884 interrupt_query ();
2885 }
2886 #endif
2887 }
2888 }
2889
2890 static int remote_cisco_mode;
2891
2892 static void remote_cisco_expand (src, dest)
2893 char *src;
2894 char *dest;
2895 {
2896 int i;
2897 int repeat;
2898
2899 do {
2900 if (*src == '*')
2901 {
2902 repeat = (fromhex (src[1]) << 4) + fromhex (src[2]);
2903 for (i = 0; i < repeat; i++)
2904 {
2905 *dest++ = *(src-1);
2906 }
2907 src += 2;
2908 }
2909 else
2910 {
2911 *dest++ = *src;
2912 }
2913 } while (*src++);
2914 }
2915
2916 /* Come here after finding the start of the frame. Collect the rest
2917 into BUF, verifying the checksum, length, and handling run-length
2918 compression. Returns 0 on any error, 1 on success. */
2919
2920 static int
2921 read_frame (buf)
2922 char *buf;
2923 {
2924 unsigned char csum;
2925 char *bp;
2926 int c;
2927
2928 csum = 0;
2929 bp = buf;
2930
2931 while (1)
2932 {
2933 c = readchar (remote_timeout);
2934
2935 switch (c)
2936 {
2937 case SERIAL_TIMEOUT:
2938 if (remote_debug)
2939 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
2940 return 0;
2941 case '$':
2942 if (remote_debug)
2943 fputs_filtered ("Saw new packet start in middle of old one\n",
2944 gdb_stdlog);
2945 return 0; /* Start a new packet, count retries */
2946 case '#':
2947 {
2948 unsigned char pktcsum;
2949
2950 *bp = '\000';
2951
2952 pktcsum = fromhex (readchar (remote_timeout)) << 4;
2953 pktcsum |= fromhex (readchar (remote_timeout));
2954
2955 if (csum == pktcsum)
2956 {
2957 if (remote_cisco_mode) /* variant run-length-encoding */
2958 {
2959 char tmp_buf[PBUFSIZ];
2960
2961 remote_cisco_expand (buf, tmp_buf);
2962 strcpy (buf, tmp_buf);
2963 }
2964 return 1;
2965 }
2966
2967 if (remote_debug)
2968 {
2969 fprintf_filtered (gdb_stdlog,
2970 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
2971 pktcsum, csum);
2972 fputs_filtered (buf, gdb_stdlog);
2973 fputs_filtered ("\n", gdb_stdlog);
2974 }
2975 return 0;
2976 }
2977 case '*': /* Run length encoding */
2978 if (remote_cisco_mode == 0) /* variant run-length-encoding */
2979 {
2980 csum += c;
2981 c = readchar (remote_timeout);
2982 csum += c;
2983 c = c - ' ' + 3; /* Compute repeat count */
2984
2985 if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
2986 {
2987 memset (bp, *(bp - 1), c);
2988 bp += c;
2989 continue;
2990 }
2991
2992 *bp = '\0';
2993 printf_filtered ("Repeat count %d too large for buffer: ", c);
2994 puts_filtered (buf);
2995 puts_filtered ("\n");
2996 return 0;
2997 }
2998 /* else fall thru to treat like default */
2999 default:
3000 if (bp < buf + PBUFSIZ - 1)
3001 {
3002 *bp++ = c;
3003 csum += c;
3004 continue;
3005 }
3006
3007 *bp = '\0';
3008 puts_filtered ("Remote packet too long: ");
3009 puts_filtered (buf);
3010 puts_filtered ("\n");
3011
3012 return 0;
3013 }
3014 }
3015 }
3016
3017 /* Read a packet from the remote machine, with error checking, and
3018 store it in BUF. BUF is expected to be of size PBUFSIZ. If
3019 FOREVER, wait forever rather than timing out; this is used while
3020 the target is executing user code. */
3021
3022 void
3023 getpkt (buf, forever)
3024 char *buf;
3025 int forever;
3026 {
3027 int c;
3028 int tries;
3029 int timeout;
3030 int val;
3031
3032 strcpy (buf,"timeout");
3033
3034 if (forever)
3035 {
3036 timeout = watchdog > 0 ? watchdog : -1;
3037 }
3038
3039 else
3040 timeout = remote_timeout;
3041
3042 #define MAX_TRIES 3
3043
3044 for (tries = 1; tries <= MAX_TRIES; tries++)
3045 {
3046 /* This can loop forever if the remote side sends us characters
3047 continuously, but if it pauses, we'll get a zero from readchar
3048 because of timeout. Then we'll count that as a retry. */
3049
3050 /* Note that we will only wait forever prior to the start of a packet.
3051 After that, we expect characters to arrive at a brisk pace. They
3052 should show up within remote_timeout intervals. */
3053
3054 do
3055 {
3056 c = readchar (timeout);
3057
3058 if (c == SERIAL_TIMEOUT)
3059 {
3060 if (forever) /* Watchdog went off. Kill the target. */
3061 {
3062 target_mourn_inferior ();
3063 error ("Watchdog has expired. Target detached.\n");
3064 }
3065 if (remote_debug)
3066 fputs_filtered ("Timed out.\n", gdb_stdlog);
3067 goto retry;
3068 }
3069 }
3070 while (c != '$');
3071
3072 /* We've found the start of a packet, now collect the data. */
3073
3074 val = read_frame (buf);
3075
3076 if (val == 1)
3077 {
3078 if (remote_debug)
3079 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", buf);
3080 SERIAL_WRITE (remote_desc, "+", 1);
3081 return;
3082 }
3083
3084 /* Try the whole thing again. */
3085 retry:
3086 SERIAL_WRITE (remote_desc, "-", 1);
3087 }
3088
3089 /* We have tried hard enough, and just can't receive the packet. Give up. */
3090
3091 printf_unfiltered ("Ignoring packet error, continuing...\n");
3092 SERIAL_WRITE (remote_desc, "+", 1);
3093 }
3094 \f
3095 static void
3096 remote_kill ()
3097 {
3098 /* For some mysterious reason, wait_for_inferior calls kill instead of
3099 mourn after it gets TARGET_WAITKIND_SIGNALLED. Work around it. */
3100 if (kill_kludge)
3101 {
3102 kill_kludge = 0;
3103 target_mourn_inferior ();
3104 return;
3105 }
3106
3107 /* Use catch_errors so the user can quit from gdb even when we aren't on
3108 speaking terms with the remote system. */
3109 catch_errors ((catch_errors_ftype*) putpkt, "k", "", RETURN_MASK_ERROR);
3110
3111 /* Don't wait for it to die. I'm not really sure it matters whether
3112 we do or not. For the existing stubs, kill is a noop. */
3113 target_mourn_inferior ();
3114 }
3115
3116 static void
3117 remote_mourn ()
3118 {
3119 remote_mourn_1 (&remote_ops);
3120 }
3121
3122 static void
3123 extended_remote_mourn ()
3124 {
3125 /* We do _not_ want to mourn the target like this; this will
3126 remove the extended remote target from the target stack,
3127 and the next time the user says "run" it'll fail.
3128
3129 FIXME: What is the right thing to do here? */
3130 #if 0
3131 remote_mourn_1 (&extended_remote_ops);
3132 #endif
3133 }
3134
3135 /* Worker function for remote_mourn. */
3136 static void
3137 remote_mourn_1 (target)
3138 struct target_ops *target;
3139 {
3140 unpush_target (target);
3141 generic_mourn_inferior ();
3142 }
3143
3144 /* In the extended protocol we want to be able to do things like
3145 "run" and have them basically work as expected. So we need
3146 a special create_inferior function.
3147
3148 FIXME: One day add support for changing the exec file
3149 we're debugging, arguments and an environment. */
3150
3151 static void
3152 extended_remote_create_inferior (exec_file, args, env)
3153 char *exec_file;
3154 char *args;
3155 char **env;
3156 {
3157 /* Rip out the breakpoints; we'll reinsert them after restarting
3158 the remote server. */
3159 remove_breakpoints ();
3160
3161 /* Now restart the remote server. */
3162 extended_remote_restart ();
3163
3164 /* Now put the breakpoints back in. This way we're safe if the
3165 restart function works via a unix fork on the remote side. */
3166 insert_breakpoints ();
3167
3168 /* Clean up from the last time we were running. */
3169 clear_proceed_status ();
3170
3171 /* Let the remote process run. */
3172 proceed (-1, TARGET_SIGNAL_0, 0);
3173 }
3174
3175 \f
3176 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
3177 than other targets; in those use REMOTE_BREAKPOINT instead of just
3178 BREAKPOINT. Also, bi-endian targets may define LITTLE_REMOTE_BREAKPOINT
3179 and BIG_REMOTE_BREAKPOINT. If none of these are defined, we just call
3180 the standard routines that are in mem-break.c. */
3181
3182 /* FIXME, these ought to be done in a more dynamic fashion. For instance,
3183 the choice of breakpoint instruction affects target program design and
3184 vice versa, and by making it user-tweakable, the special code here
3185 goes away and we need fewer special GDB configurations. */
3186
3187 #if defined (LITTLE_REMOTE_BREAKPOINT) && defined (BIG_REMOTE_BREAKPOINT) && !defined(REMOTE_BREAKPOINT)
3188 #define REMOTE_BREAKPOINT
3189 #endif
3190
3191 #ifdef REMOTE_BREAKPOINT
3192
3193 /* If the target isn't bi-endian, just pretend it is. */
3194 #if !defined (LITTLE_REMOTE_BREAKPOINT) && !defined (BIG_REMOTE_BREAKPOINT)
3195 #define LITTLE_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
3196 #define BIG_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
3197 #endif
3198
3199 static unsigned char big_break_insn[] = BIG_REMOTE_BREAKPOINT;
3200 static unsigned char little_break_insn[] = LITTLE_REMOTE_BREAKPOINT;
3201
3202 #endif /* REMOTE_BREAKPOINT */
3203
3204 /* Insert a breakpoint on targets that don't have any better breakpoint
3205 support. We read the contents of the target location and stash it,
3206 then overwrite it with a breakpoint instruction. ADDR is the target
3207 location in the target machine. CONTENTS_CACHE is a pointer to
3208 memory allocated for saving the target contents. It is guaranteed
3209 by the caller to be long enough to save sizeof BREAKPOINT bytes (this
3210 is accomplished via BREAKPOINT_MAX). */
3211
3212 static int
3213 remote_insert_breakpoint (addr, contents_cache)
3214 CORE_ADDR addr;
3215 char *contents_cache;
3216 {
3217 #ifdef REMOTE_BREAKPOINT
3218 int val;
3219
3220 val = target_read_memory (addr, contents_cache, sizeof big_break_insn);
3221
3222 if (val == 0)
3223 {
3224 if (TARGET_BYTE_ORDER == BIG_ENDIAN)
3225 val = target_write_memory (addr, (char *) big_break_insn,
3226 sizeof big_break_insn);
3227 else
3228 val = target_write_memory (addr, (char *) little_break_insn,
3229 sizeof little_break_insn);
3230 }
3231
3232 return val;
3233 #else
3234 return memory_insert_breakpoint (addr, contents_cache);
3235 #endif /* REMOTE_BREAKPOINT */
3236 }
3237
3238 static int
3239 remote_remove_breakpoint (addr, contents_cache)
3240 CORE_ADDR addr;
3241 char *contents_cache;
3242 {
3243 #ifdef REMOTE_BREAKPOINT
3244 return target_write_memory (addr, contents_cache, sizeof big_break_insn);
3245 #else
3246 return memory_remove_breakpoint (addr, contents_cache);
3247 #endif /* REMOTE_BREAKPOINT */
3248 }
3249
3250 /* Some targets are only capable of doing downloads, and afterwards
3251 they switch to the remote serial protocol. This function provides
3252 a clean way to get from the download target to the remote target.
3253 It's basically just a wrapper so that we don't have to expose any
3254 of the internal workings of remote.c.
3255
3256 Prior to calling this routine, you should shutdown the current
3257 target code, else you will get the "A program is being debugged
3258 already..." message. Usually a call to pop_target() suffices. */
3259
3260 void
3261 push_remote_target (name, from_tty)
3262 char *name;
3263 int from_tty;
3264 {
3265 printf_filtered ("Switching to remote protocol\n");
3266 remote_open (name, from_tty);
3267 }
3268
3269 /* Other targets want to use the entire remote serial module but with
3270 certain remote_ops overridden. */
3271
3272 void
3273 open_remote_target (name, from_tty, target, extended_p)
3274 char *name;
3275 int from_tty;
3276 struct target_ops *target;
3277 int extended_p;
3278 {
3279 printf_filtered ("Selecting the %sremote protocol\n",
3280 (extended_p ? "extended-" : ""));
3281 remote_open_1 (name, from_tty, target, extended_p);
3282 }
3283
3284 /* Table used by the crc32 function to calcuate the checksum. */
3285
3286 static unsigned long crc32_table[256] = {0, 0};
3287
3288 static unsigned long
3289 crc32 (buf, len, crc)
3290 unsigned char *buf;
3291 int len;
3292 unsigned int crc;
3293 {
3294 if (! crc32_table[1])
3295 {
3296 /* Initialize the CRC table and the decoding table. */
3297 int i, j;
3298 unsigned int c;
3299
3300 for (i = 0; i < 256; i++)
3301 {
3302 for (c = i << 24, j = 8; j > 0; --j)
3303 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
3304 crc32_table[i] = c;
3305 }
3306 }
3307
3308 while (len--)
3309 {
3310 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
3311 buf++;
3312 }
3313 return crc;
3314 }
3315
3316 /* compare-sections command
3317
3318 With no arguments, compares each loadable section in the exec bfd
3319 with the same memory range on the target, and reports mismatches.
3320 Useful for verifying the image on the target against the exec file.
3321 Depends on the target understanding the new "qCRC:" request. */
3322
3323 static void
3324 compare_sections_command (args, from_tty)
3325 char *args;
3326 int from_tty;
3327 {
3328 asection *s;
3329 unsigned long host_crc, target_crc;
3330 extern bfd *exec_bfd;
3331 struct cleanup *old_chain;
3332 char *tmp, *sectdata, *sectname, buf[PBUFSIZ];
3333 bfd_size_type size;
3334 bfd_vma lma;
3335 int matched = 0;
3336 int mismatched = 0;
3337
3338 if (!exec_bfd)
3339 error ("command cannot be used without an exec file");
3340 if (!current_target.to_shortname ||
3341 strcmp (current_target.to_shortname, "remote") != 0)
3342 error ("command can only be used with remote target");
3343
3344 for (s = exec_bfd->sections; s; s = s->next)
3345 {
3346 if (!(s->flags & SEC_LOAD))
3347 continue; /* skip non-loadable section */
3348
3349 size = bfd_get_section_size_before_reloc (s);
3350 if (size == 0)
3351 continue; /* skip zero-length section */
3352
3353 sectname = (char *) bfd_get_section_name (exec_bfd, s);
3354 if (args && strcmp (args, sectname) != 0)
3355 continue; /* not the section selected by user */
3356
3357 matched = 1; /* do this section */
3358 lma = s->lma;
3359 /* FIXME: assumes lma can fit into long */
3360 sprintf (buf, "qCRC:%lx,%lx", (long) lma, (long) size);
3361 putpkt (buf);
3362
3363 /* be clever; compute the host_crc before waiting for target reply */
3364 sectdata = xmalloc (size);
3365 old_chain = make_cleanup (free, sectdata);
3366 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
3367 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
3368
3369 getpkt (buf, 0);
3370 if (buf[0] == 'E')
3371 error ("target memory fault, section %s, range 0x%08x -- 0x%08x",
3372 sectname, lma, lma + size);
3373 if (buf[0] != 'C')
3374 error ("remote target does not support this operation");
3375
3376 for (target_crc = 0, tmp = &buf[1]; *tmp; tmp++)
3377 target_crc = target_crc * 16 + fromhex (*tmp);
3378
3379 printf_filtered ("Section %s, range 0x%08x -- 0x%08x: ",
3380 sectname, lma, lma + size);
3381 if (host_crc == target_crc)
3382 printf_filtered ("matched.\n");
3383 else
3384 {
3385 printf_filtered ("MIS-MATCHED!\n");
3386 mismatched++;
3387 }
3388
3389 do_cleanups (old_chain);
3390 }
3391 if (mismatched > 0)
3392 warning ("One or more sections of the remote executable does not match\n\
3393 the loaded file\n");
3394 if (args && !matched)
3395 printf_filtered ("No loaded section named '%s'.\n", args);
3396 }
3397
3398 static int
3399 remote_query (query_type, buf, outbuf, bufsiz)
3400 int query_type;
3401 char *buf;
3402 char *outbuf;
3403 int *bufsiz;
3404 {
3405 int i;
3406 char buf2[PBUFSIZ];
3407 char *p2 = &buf2[0];
3408 char *p = buf;
3409
3410 if (! bufsiz)
3411 error ("null pointer to remote bufer size specified");
3412
3413 /* minimum outbuf size is PBUFSIZ - if bufsiz is not large enough let
3414 the caller know and return what the minimum size is */
3415 /* Note: a zero bufsiz can be used to query the minimum buffer size */
3416 if ( *bufsiz < PBUFSIZ )
3417 {
3418 *bufsiz = PBUFSIZ;
3419 return -1;
3420 }
3421
3422 /* except for querying the minimum buffer size, target must be open */
3423 if (! remote_desc)
3424 error ("remote query is only available after target open");
3425
3426 /* we only take uppercase letters as query types, at least for now */
3427 if ( (query_type < 'A') || (query_type > 'Z') )
3428 error ("invalid remote query type");
3429
3430 if (! buf)
3431 error ("null remote query specified");
3432
3433 if (! outbuf)
3434 error ("remote query requires a buffer to receive data");
3435
3436 outbuf[0] = '\0';
3437
3438 *p2++ = 'q';
3439 *p2++ = query_type;
3440
3441 /* we used one buffer char for the remote protocol q command and another
3442 for the query type. As the remote protocol encapsulation uses 4 chars
3443 plus one extra in case we are debugging (remote_debug),
3444 we have PBUFZIZ - 7 left to pack the query string */
3445 i = 0;
3446 while ( buf[i] && (i < (PBUFSIZ - 8)) )
3447 {
3448 /* bad caller may have sent forbidden characters */
3449 if ( (!isprint(buf[i])) || (buf[i] == '$') || (buf[i] == '#') )
3450 error ("illegal characters in query string");
3451
3452 *p2++ = buf[i];
3453 i++;
3454 }
3455 *p2 = buf[i];
3456
3457 if ( buf[i] )
3458 error ("query larger than available buffer");
3459
3460 i = putpkt (buf2);
3461 if ( i < 0 ) return i;
3462
3463 getpkt (outbuf, 0);
3464
3465 return 0;
3466 }
3467
3468 static void
3469 packet_command (args, from_tty)
3470 char *args;
3471 int from_tty;
3472 {
3473 char buf[PBUFSIZ];
3474
3475 if (! remote_desc)
3476 error ("command can only be used with remote target");
3477
3478 if (! args)
3479 error ("remote-packet command requires packet text as argument");
3480
3481 puts_filtered ("sending: ");
3482 print_packet (args);
3483 puts_filtered ("\n");
3484 putpkt (args);
3485
3486 getpkt (buf, 0);
3487 puts_filtered ("received: ");
3488 print_packet (buf);
3489 puts_filtered ("\n");
3490 }
3491
3492 #if 0
3493 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------------- */
3494
3495 static void display_thread_info PARAMS ((struct gdb_ext_thread_info *info));
3496
3497 static void threadset_test_cmd PARAMS ((char *cmd, int tty));
3498
3499 static void threadalive_test PARAMS ((char *cmd, int tty));
3500
3501 static void threadlist_test_cmd PARAMS ((char *cmd, int tty));
3502
3503 int get_and_display_threadinfo PARAMS ((threadref *ref));
3504
3505 static void threadinfo_test_cmd PARAMS ((char *cmd, int tty));
3506
3507 static int thread_display_step PARAMS ((threadref *ref, void *context));
3508
3509 static void threadlist_update_test_cmd PARAMS ((char *cmd, int tty));
3510
3511 static void init_remote_threadtests PARAMS ((void));
3512
3513 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid */
3514
3515 static void
3516 threadset_test_cmd (cmd, tty)
3517 char *cmd;
3518 int tty;
3519 {
3520 int sample_thread = SAMPLE_THREAD;
3521
3522 printf_filtered ("Remote threadset test\n");
3523 set_thread (sample_thread, 1);
3524 }
3525
3526
3527 static void
3528 threadalive_test (cmd, tty)
3529 char *cmd;
3530 int tty;
3531 {
3532 int sample_thread = SAMPLE_THREAD;
3533
3534 if (remote_thread_alive (sample_thread))
3535 printf_filtered ("PASS: Thread alive test\n");
3536 else
3537 printf_filtered ("FAIL: Thread alive test\n");
3538 }
3539
3540 void output_threadid PARAMS ((char *title, threadref * ref));
3541
3542 void
3543 output_threadid (title, ref)
3544 char *title;
3545 threadref *ref;
3546 {
3547 char hexid[20];
3548
3549 pack_threadid (&hexid[0], ref); /* Convert threead id into hex */
3550 hexid[16] = 0;
3551 printf_filtered ("%s %s\n", title, (&hexid[0]));
3552 }
3553
3554 static void
3555 threadlist_test_cmd (cmd, tty)
3556 char *cmd;
3557 int tty;
3558 {
3559 int startflag = 1;
3560 threadref nextthread;
3561 int done, result_count;
3562 threadref threadlist[3];
3563
3564 printf_filtered ("Remote Threadlist test\n");
3565 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
3566 &result_count, &threadlist[0]))
3567 printf_filtered ("FAIL: threadlist test\n");
3568 else
3569 {
3570 threadref *scan = threadlist;
3571 threadref *limit = scan + result_count;
3572
3573 while (scan < limit)
3574 output_threadid (" thread ", scan++);
3575 }
3576 }
3577
3578 void
3579 display_thread_info (info)
3580 struct gdb_ext_thread_info *info;
3581 {
3582 output_threadid ("Threadid: ", &info->threadid);
3583 printf_filtered ("Name: %s\n ", info->shortname);
3584 printf_filtered ("State: %s\n", info->display);
3585 printf_filtered ("other: %s\n\n", info->more_display);
3586 }
3587
3588 int
3589 get_and_display_threadinfo (ref)
3590 threadref *ref;
3591 {
3592 int result;
3593 int set;
3594 struct gdb_ext_thread_info threadinfo;
3595
3596 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3597 | TAG_MOREDISPLAY | TAG_DISPLAY;
3598 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
3599 display_thread_info (&threadinfo);
3600 return result;
3601 }
3602
3603 static void
3604 threadinfo_test_cmd (cmd, tty)
3605 char *cmd;
3606 int tty;
3607 {
3608 int athread = SAMPLE_THREAD;
3609 threadref thread;
3610 int set;
3611
3612 int_to_threadref (&thread, athread);
3613 printf_filtered ("Remote Threadinfo test\n");
3614 if (!get_and_display_threadinfo (&thread))
3615 printf_filtered ("FAIL cannot get thread info\n");
3616 }
3617
3618 static int
3619 thread_display_step (ref, context)
3620 threadref *ref;
3621 void *context;
3622 {
3623 /* output_threadid(" threadstep ",ref); *//* simple test */
3624 return get_and_display_threadinfo (ref);
3625 }
3626
3627 static void
3628 threadlist_update_test_cmd (cmd, tty)
3629 char *cmd;
3630 int tty;
3631 {
3632 printf_filtered ("Remote Threadlist update test\n");
3633 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
3634 }
3635
3636 static void
3637 init_remote_threadtests (void)
3638 {
3639 add_com ("tlist", class_obscure, threadlist_test_cmd,
3640 "Fetch and print the remote list of thread identifiers, one pkt only");
3641 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
3642 "Fetch and display info about one thread");
3643 add_com ("tset", class_obscure, threadset_test_cmd,
3644 "Test setting to a different thread");
3645 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
3646 "Iterate through updating all remote thread info");
3647 add_com ("talive", class_obscure, threadalive_test,
3648 " Remote thread alive test ");
3649 }
3650
3651 #endif /* 0 */
3652
3653 static void
3654 init_remote_ops ()
3655 {
3656 remote_ops.to_shortname = "remote";
3657 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
3658 remote_ops.to_doc =
3659 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
3660 Specify the serial device it is connected to (e.g. /dev/ttya).";
3661 remote_ops.to_open = remote_open;
3662 remote_ops.to_close = remote_close;
3663 remote_ops.to_detach = remote_detach;
3664 remote_ops.to_resume = remote_resume;
3665 remote_ops.to_wait = remote_wait;
3666 remote_ops.to_fetch_registers = remote_fetch_registers;
3667 remote_ops.to_store_registers = remote_store_registers;
3668 remote_ops.to_prepare_to_store = remote_prepare_to_store;
3669 remote_ops.to_xfer_memory = remote_xfer_memory;
3670 remote_ops.to_files_info = remote_files_info;
3671 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
3672 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3673 remote_ops.to_kill = remote_kill;
3674 remote_ops.to_load = generic_load;
3675 remote_ops.to_mourn_inferior = remote_mourn;
3676 remote_ops.to_thread_alive = remote_thread_alive;
3677 remote_ops.to_find_new_threads = remote_threads_info;
3678 remote_ops.to_stop = remote_stop;
3679 remote_ops.to_query = remote_query;
3680 remote_ops.to_stratum = process_stratum;
3681 remote_ops.to_has_all_memory = 1;
3682 remote_ops.to_has_memory = 1;
3683 remote_ops.to_has_stack = 1;
3684 remote_ops.to_has_registers = 1;
3685 remote_ops.to_has_execution = 1;
3686 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
3687 remote_ops.to_magic = OPS_MAGIC;
3688 }
3689
3690 /* Set up the extended remote vector by making a copy of the standard
3691 remote vector and adding to it. */
3692
3693 static void
3694 init_extended_remote_ops ()
3695 {
3696 extended_remote_ops = remote_ops;
3697
3698 extended_remote_ops.to_shortname = "extended-remote";
3699 extended_remote_ops.to_longname =
3700 "Extended remote serial target in gdb-specific protocol";
3701 extended_remote_ops.to_doc =
3702 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
3703 Specify the serial device it is connected to (e.g. /dev/ttya).",
3704 extended_remote_ops.to_open = extended_remote_open;
3705 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
3706 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
3707 }
3708
3709 /*
3710 * Command: info remote-process
3711 *
3712 * This implements Cisco's version of the "info proc" command.
3713 *
3714 * This query allows the target stub to return an arbitrary string
3715 * (or strings) giving arbitrary information about the target process.
3716 * This is optional; the target stub isn't required to implement it.
3717 *
3718 * Syntax: qfProcessInfo request first string
3719 * qsProcessInfo request subsequent string
3720 * reply: 'O'<hex-encoded-string>
3721 * 'l' last reply (empty)
3722 */
3723
3724 static void
3725 remote_info_process (args, from_tty)
3726 char *args;
3727 int from_tty;
3728 {
3729 char buf[PBUFSIZ];
3730
3731 if (remote_desc == 0)
3732 error ("Command can only be used when connected to the remote target.");
3733
3734 putpkt ("qfProcessInfo");
3735 getpkt (buf, 0);
3736 if (buf[0] == 0)
3737 return; /* Silently: target does not support this feature. */
3738
3739 if (buf[0] == 'E')
3740 error ("info proc: target error.");
3741
3742 while (buf[0] == 'O') /* Capitol-O packet */
3743 {
3744 remote_console_output (&buf[1]);
3745 putpkt ("qsProcessInfo");
3746 getpkt (buf, 0);
3747 }
3748 }
3749
3750 /*
3751 * Target Cisco
3752 */
3753
3754 static void
3755 remote_cisco_open (name, from_tty)
3756 char *name;
3757 int from_tty;
3758 {
3759 if (name == 0)
3760 error (
3761 "To open a remote debug connection, you need to specify what \n\
3762 device is attached to the remote system (e.g. host:port).");
3763
3764 target_preopen (from_tty);
3765
3766 unpush_target (&remote_cisco_ops);
3767
3768 remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
3769
3770 remote_desc = SERIAL_OPEN (name);
3771 if (!remote_desc)
3772 perror_with_name (name);
3773
3774 /*
3775 * If a baud rate was specified on the gdb command line it will
3776 * be greater than the initial value of -1. If it is, use it otherwise
3777 * default to 9600
3778 */
3779
3780 baud_rate = (baud_rate > 0) ? baud_rate : 9600;
3781 if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
3782 {
3783 SERIAL_CLOSE (remote_desc);
3784 perror_with_name (name);
3785 }
3786
3787 SERIAL_RAW (remote_desc);
3788
3789 /* If there is something sitting in the buffer we might take it as a
3790 response to a command, which would be bad. */
3791 SERIAL_FLUSH_INPUT (remote_desc);
3792
3793 if (from_tty)
3794 {
3795 puts_filtered ("Remote debugging using ");
3796 puts_filtered (name);
3797 puts_filtered ("\n");
3798 }
3799
3800 remote_cisco_mode = 1;
3801
3802 push_target (&remote_cisco_ops); /* Switch to using cisco target now */
3803
3804 /* Start out by trying the 'P' request to set registers. We set this each
3805 time that we open a new target so that if the user switches from one
3806 stub to another, we can (if the target is closed and reopened) cope. */
3807 stub_supports_P = 1;
3808
3809 general_thread = -2;
3810 continue_thread = -2;
3811
3812 /* Force remote_write_bytes to check whether target supports
3813 binary downloading. */
3814 remote_binary_checked = 0;
3815
3816 /* Without this, some commands which require an active target (such
3817 as kill) won't work. This variable serves (at least) double duty
3818 as both the pid of the target process (if it has such), and as a
3819 flag indicating that a target is active. These functions should
3820 be split out into seperate variables, especially since GDB will
3821 someday have a notion of debugging several processes. */
3822 inferior_pid = MAGIC_NULL_PID;
3823
3824 /* Start the remote connection; if error (0), discard this target. */
3825
3826 if (!catch_errors (remote_start_remote_dummy, (char *) 0,
3827 "Couldn't establish connection to remote target\n",
3828 RETURN_MASK_ALL))
3829 {
3830 pop_target ();
3831 return;
3832 }
3833 }
3834
3835 static void
3836 remote_cisco_close (quitting)
3837 int quitting;
3838 {
3839 remote_cisco_mode = 0;
3840 remote_close (quitting);
3841 }
3842
3843 static void
3844 remote_cisco_mourn PARAMS ((void))
3845 {
3846 remote_mourn_1 (&remote_cisco_ops);
3847 }
3848
3849 enum {
3850 READ_MORE,
3851 FATAL_ERROR,
3852 ENTER_DEBUG,
3853 DISCONNECT_TELNET
3854 } minitelnet_return;
3855
3856 /* shared between readsocket() and readtty() */
3857 static char *tty_input;
3858
3859 static int escape_count;
3860 static int echo_check;
3861 extern int quit_flag;
3862
3863 static int
3864 readsocket ()
3865 {
3866 int data;
3867
3868 /* Loop until the socket doesn't have any more data */
3869
3870 while ((data = readchar (0)) >= 0)
3871 {
3872 /* Check for the escape sequence */
3873 if (data == '|')
3874 {
3875 /* If this is the fourth escape, get out */
3876 if (++escape_count == 4)
3877 {
3878 return ENTER_DEBUG;
3879 }
3880 else
3881 { /* This is a '|', but not the fourth in a row.
3882 Continue without echoing it. If it isn't actually
3883 one of four in a row, it'll be echoed later. */
3884 continue;
3885 }
3886 }
3887 else /* Not a '|' */
3888 {
3889 /* Ensure any pending '|'s are flushed. */
3890
3891 for ( ; escape_count > 0; escape_count--)
3892 putchar('|');
3893 }
3894
3895 if (data == '\r') /* If this is a return character, */
3896 continue; /* - just supress it. */
3897
3898 if (echo_check != -1) /* Check for echo of user input. */
3899 {
3900 if (tty_input[echo_check] == data)
3901 {
3902 echo_check++; /* Character matched user input: */
3903 continue; /* Continue without echoing it. */
3904 }
3905 else if ((data == '\n') && (tty_input[echo_check] == '\r'))
3906 { /* End of the line (and of echo checking). */
3907 echo_check = -1; /* No more echo supression */
3908 continue; /* Continue without echoing. */
3909 }
3910 else
3911 { /* Failed check for echo of user input.
3912 We now have some suppressed output to flush! */
3913 int j;
3914
3915 for (j = 0; j < echo_check; j++)
3916 putchar (tty_input[j]);
3917 echo_check = -1;
3918 }
3919 }
3920 putchar (data); /* Default case: output the char. */
3921 }
3922
3923 if (data == SERIAL_TIMEOUT) /* Timeout returned from readchar. */
3924 return READ_MORE; /* Try to read some more */
3925 else
3926 return FATAL_ERROR; /* Trouble, bail out */
3927 }
3928
3929 static int
3930 readtty ()
3931 {
3932 int status;
3933 int tty_bytecount;
3934
3935 /* First, read a buffer full from the terminal */
3936 tty_bytecount = read (fileno (stdin), tty_input, sizeof (tty_input) - 1);
3937 if (tty_bytecount == -1)
3938 {
3939 perror ("readtty: read failed");
3940 return FATAL_ERROR;
3941 }
3942
3943 /* Remove a quoted newline. */
3944 if (tty_input[tty_bytecount - 1] == '\n' &&
3945 tty_input[tty_bytecount - 2] == '\\') /* line ending in backslash */
3946 {
3947 tty_input[--tty_bytecount] = 0; /* remove newline */
3948 tty_input[--tty_bytecount] = 0; /* remove backslash */
3949 }
3950
3951 /* Turn trailing newlines into returns */
3952 if (tty_input[tty_bytecount - 1] == '\n')
3953 tty_input[tty_bytecount - 1] = '\r';
3954
3955 /* If the line consists of a ~, enter debugging mode. */
3956 if ((tty_input[0] == '~') && (tty_bytecount == 2))
3957 return ENTER_DEBUG;
3958
3959 /* Make this a zero terminated string and write it out */
3960 tty_input[tty_bytecount] = 0;
3961 if (SERIAL_WRITE (remote_desc, tty_input, tty_bytecount))
3962 {
3963 perror_with_name ("readtty: write failed");
3964 return FATAL_ERROR;
3965 }
3966
3967 return READ_MORE;
3968 }
3969
3970 static int
3971 minitelnet ()
3972 {
3973 fd_set input; /* file descriptors for select */
3974 int tablesize; /* max number of FDs for select */
3975 int status;
3976 int quit_count = 0;
3977
3978 extern int escape_count; /* global shared by readsocket */
3979 extern int echo_check; /* ditto */
3980
3981 escape_count = 0;
3982 echo_check = -1;
3983
3984 tablesize = 8 * sizeof (input);
3985
3986 for (;;)
3987 {
3988 /* Check for anything from our socket - doesn't block. Note that
3989 this must be done *before* the select as there may be
3990 buffered I/O waiting to be processed. */
3991
3992 if ((status = readsocket ()) == FATAL_ERROR)
3993 {
3994 error ("Debugging terminated by communications error");
3995 }
3996 else if (status != READ_MORE)
3997 {
3998 return (status);
3999 }
4000
4001 fflush(stdout); /* Flush output before blocking */
4002
4003 /* Now block on more socket input or TTY input */
4004
4005 FD_ZERO (&input);
4006 FD_SET (fileno(stdin), &input);
4007 FD_SET (remote_desc->fd, &input);
4008
4009 status = select (tablesize, &input, 0, 0, 0);
4010 if ((status == -1) && (errno != EINTR))
4011 {
4012 error ("Communications error on select %d", errno);
4013 }
4014
4015 /* Handle Control-C typed */
4016
4017 if (quit_flag)
4018 {
4019 if ((++quit_count) == 2)
4020 {
4021 if (query ("Interrupt GDB? "))
4022 {
4023 printf_filtered ("Interrupted by user.\n");
4024 return_to_top_level (RETURN_QUIT);
4025 }
4026 quit_count = 0;
4027 }
4028 quit_flag = 0;
4029
4030 if (remote_break)
4031 SERIAL_SEND_BREAK (remote_desc);
4032 else
4033 SERIAL_WRITE (remote_desc, "\003", 1);
4034
4035 continue;
4036 }
4037
4038 /* Handle console input */
4039
4040 if (FD_ISSET (fileno (stdin), &input))
4041 {
4042 quit_count = 0;
4043 echo_check = 0;
4044 status = readtty ();
4045 if (status == READ_MORE)
4046 continue;
4047
4048 return status; /* telnet session ended */
4049 }
4050 }
4051 }
4052
4053 static int
4054 remote_cisco_wait (pid, status)
4055 int pid;
4056 struct target_waitstatus *status;
4057 {
4058 if (minitelnet() != ENTER_DEBUG)
4059 {
4060 error ("Debugging session terminated by protocol error");
4061 }
4062 putpkt ("?");
4063 return remote_wait (pid, status);
4064 }
4065
4066 static void
4067 init_remote_cisco_ops ()
4068 {
4069 remote_cisco_ops.to_shortname = "cisco";
4070 remote_cisco_ops.to_longname = "Remote serial target in cisco-specific protocol";
4071 remote_cisco_ops.to_doc =
4072 "Use a remote machine via TCP, using a cisco-specific protocol.\n\
4073 Specify the serial device it is connected to (e.g. host:2020).";
4074 remote_cisco_ops.to_open = remote_cisco_open;
4075 remote_cisco_ops.to_close = remote_cisco_close;
4076 remote_cisco_ops.to_detach = remote_detach;
4077 remote_cisco_ops.to_resume = remote_resume;
4078 remote_cisco_ops.to_wait = remote_cisco_wait;
4079 remote_cisco_ops.to_fetch_registers = remote_fetch_registers;
4080 remote_cisco_ops.to_store_registers = remote_store_registers;
4081 remote_cisco_ops.to_prepare_to_store = remote_prepare_to_store;
4082 remote_cisco_ops.to_xfer_memory = remote_xfer_memory;
4083 remote_cisco_ops.to_files_info = remote_files_info;
4084 remote_cisco_ops.to_insert_breakpoint = remote_insert_breakpoint;
4085 remote_cisco_ops.to_remove_breakpoint = remote_remove_breakpoint;
4086 remote_cisco_ops.to_kill = remote_kill;
4087 remote_cisco_ops.to_load = generic_load;
4088 remote_cisco_ops.to_mourn_inferior = remote_cisco_mourn;
4089 remote_cisco_ops.to_thread_alive = remote_thread_alive;
4090 remote_cisco_ops.to_find_new_threads = remote_threads_info;
4091 remote_cisco_ops.to_stratum = process_stratum;
4092 remote_cisco_ops.to_has_all_memory = 1;
4093 remote_cisco_ops.to_has_memory = 1;
4094 remote_cisco_ops.to_has_stack = 1;
4095 remote_cisco_ops.to_has_registers = 1;
4096 remote_cisco_ops.to_has_execution = 1;
4097 remote_cisco_ops.to_magic = OPS_MAGIC;
4098 }
4099
4100 static void
4101 build_remote_gdbarch_data ()
4102 {
4103 tty_input = xmalloc (PBUFSIZ);
4104 }
4105
4106
4107 void
4108 _initialize_remote ()
4109 {
4110 /* architecture specific data */
4111 build_remote_gdbarch_data ();
4112 register_gdbarch_swap (&tty_input, sizeof (&tty_input), NULL);
4113 register_gdbarch_swap (NULL, 0, build_remote_gdbarch_data);
4114
4115 /* runtime constants - we retain the value of remote_write_size
4116 across architecture swaps. */
4117 remote_write_size = PBUFSIZ;
4118
4119 init_remote_ops ();
4120 add_target (&remote_ops);
4121
4122 init_extended_remote_ops ();
4123 add_target (&extended_remote_ops);
4124
4125 init_remote_cisco_ops ();
4126 add_target (&remote_cisco_ops);
4127
4128 #if 0
4129 init_remote_threadtests ();
4130 #endif
4131
4132 add_cmd ("compare-sections", class_obscure, compare_sections_command,
4133 "Compare section data on target to the exec file.\n\
4134 Argument is a single section name (default: all loaded sections).",
4135 &cmdlist);
4136
4137 add_cmd ("packet", class_maintenance, packet_command,
4138 "Send an arbitrary packet to a remote target.\n\
4139 maintenance packet TEXT\n\
4140 If GDB is talking to an inferior via the GDB serial protocol, then\n\
4141 this command sends the string TEXT to the inferior, and displays the\n\
4142 response packet. GDB supplies the initial `$' character, and the\n\
4143 terminating `#' character and checksum.",
4144 &maintenancelist);
4145
4146 add_show_from_set
4147 (add_set_cmd ("remotetimeout", no_class,
4148 var_integer, (char *)&remote_timeout,
4149 "Set timeout value for remote read.\n",
4150 &setlist),
4151 &showlist);
4152
4153 add_show_from_set
4154 (add_set_cmd ("remotebreak", no_class,
4155 var_integer, (char *)&remote_break,
4156 "Set whether to send break if interrupted.\n",
4157 &setlist),
4158 &showlist);
4159
4160 add_show_from_set
4161 (add_set_cmd ("remotewritesize", no_class,
4162 var_integer, (char *)&remote_write_size,
4163 "Set the maximum number of bytes per memory write packet.\n",
4164 &setlist),
4165 &showlist);
4166
4167 remote_address_size = TARGET_PTR_BIT;
4168 add_show_from_set
4169 (add_set_cmd ("remoteaddresssize", class_obscure,
4170 var_integer, (char *)&remote_address_size,
4171 "Set the maximum size of the address (in bits) \
4172 in a memory packet.\n",
4173 &setlist),
4174 &showlist);
4175
4176 add_show_from_set
4177 (add_set_cmd ("remotebinarydownload", no_class,
4178 var_boolean, (char *) &remote_binary_download,
4179 "Set binary downloads.\n", &setlist),
4180 &showlist);
4181
4182 add_info ("remote-process", remote_info_process,
4183 "Query the remote system for process info.");
4184
4185 }