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