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