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