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