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