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