remote.c revision 21738
1/* Remote target communications for serial-line targets in custom GDB protocol
2   Copyright 1988, 1991, 1992, 1993, 1994, 1995, 1996 Free Software Foundation, Inc.
3
4This file is part of GDB.
5
6This program is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation; either version 2 of the License, or
9(at your option) any later version.
10
11This program is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with this program; if not, write to the Free Software
18Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20/* Remote communication protocol.
21
22   A debug packet whose contents are <data>
23   is encapsulated for transmission in the form:
24
25	$ <data> # CSUM1 CSUM2
26
27	<data> must be ASCII alphanumeric and cannot include characters
28	'$' or '#'.  If <data> starts with two characters followed by
29	':', then the existing stubs interpret this as a sequence number.
30
31	CSUM1 and CSUM2 are ascii hex representation of an 8-bit
32	checksum of <data>, the most significant nibble is sent first.
33	the hex digits 0-9,a-f are used.
34
35   Receiver responds with:
36
37	+	- if CSUM is correct and ready for next packet
38	-	- if CSUM is incorrect
39
40   <data> is as follows:
41   Most values are encoded in ascii hex digits.  Signal numbers are according
42   to the numbering in target.h.
43
44	Request		Packet
45
46	set thread	Hct...		Set thread for subsequent operations.
47					c = 'c' for thread used in step and
48					continue; t... can be -1 for all
49					threads.
50					c = 'g' for thread used in other
51					operations.  If zero, pick a thread,
52					any thread.
53	reply		OK		for success
54			ENN		for an error.
55
56	read registers  g
57	reply		XX....X		Each byte of register data
58					is described by two hex digits.
59					Registers are in the internal order
60					for GDB, and the bytes in a register
61					are in the same order the machine uses.
62			or ENN		for an error.
63
64	write regs	GXX..XX		Each byte of register data
65					is described by two hex digits.
66	reply		OK		for success
67			ENN		for an error
68
69        write reg	Pn...=r...	Write register n... with value r...,
70					which contains two hex digits for each
71					byte in the register (target byte
72					order).
73	reply		OK		for success
74			ENN		for an error
75	(not supported by all stubs).
76
77	read mem	mAA..AA,LLLL	AA..AA is address, LLLL is length.
78	reply		XX..XX		XX..XX is mem contents
79					Can be fewer bytes than requested
80					if able to read only part of the data.
81			or ENN		NN is errno
82
83	write mem	MAA..AA,LLLL:XX..XX
84					AA..AA is address,
85					LLLL is number of bytes,
86					XX..XX is data
87	reply		OK		for success
88			ENN		for an error (this includes the case
89					where only part of the data was
90					written).
91
92	continue	cAA..AA		AA..AA is address to resume
93					If AA..AA is omitted,
94					resume at same address.
95
96	step		sAA..AA		AA..AA is address to resume
97					If AA..AA is omitted,
98					resume at same address.
99
100	continue with	Csig;AA		Continue with signal sig (hex signal
101	signal				number).
102
103	step with	Ssig;AA		Like 'C' but step not continue.
104	signal
105
106	last signal     ?               Reply the current reason for stopping.
107                                        This is the same reply as is generated
108					for step or cont : SAA where AA is the
109					signal number.
110
111	detach          D               Reply OK.
112
113	There is no immediate reply to step or cont.
114	The reply comes when the machine stops.
115	It is		SAA		AA is the signal number.
116
117	or...		TAAn...:r...;n...:r...;n...:r...;
118					AA = signal number
119					n... = register number (hex)
120					  r... = register contents
121					n... = `thread'
122					  r... = thread process ID.  This is
123						 a hex integer.
124					n... = other string not starting
125					    with valid hex digit.
126					  gdb should ignore this n,r pair
127					  and go on to the next.  This way
128					  we can extend the protocol.
129	or...		WAA		The process exited, and AA is
130					the exit status.  This is only
131					applicable for certains sorts of
132					targets.
133	or...		XAA		The process terminated with signal
134					AA.
135        or...           OXX..XX	XX..XX  is hex encoding of ASCII data. This
136					can happen at any time while the program is
137					running and the debugger should
138					continue to wait for 'W', 'T', etc.
139
140	thread alive	TXX		Find out if the thread XX is alive.
141	reply		OK		thread is still alive
142			ENN		thread is dead
143
144	remote restart	RXX		Restart the remote server
145
146	extended ops 	!		Use the extended remote protocol.
147					Sticky -- only needs to be set once.
148
149	kill request	k
150
151	toggle debug	d		toggle debug flag (see 386 & 68k stubs)
152	reset		r		reset -- see sparc stub.
153	reserved	<other>		On other requests, the stub should
154					ignore the request and send an empty
155					response ($#<checksum>).  This way
156					we can extend the protocol and GDB
157					can tell whether the stub it is
158					talking to uses the old or the new.
159	search		tAA:PP,MM	Search backwards starting at address
160					AA for a match with pattern PP and
161					mask MM.  PP and MM are 4 bytes.
162					Not supported by all stubs.
163
164	general query	qXXXX		Request info about XXXX.
165	general set	QXXXX=yyyy	Set value of XXXX to yyyy.
166	query sect offs	qOffsets	Get section offsets.  Reply is
167					Text=xxx;Data=yyy;Bss=zzz
168
169	Responses can be run-length encoded to save space.  A '*' means that
170	the next character is an ASCII encoding giving a repeat count which
171	stands for that many repititions of the character preceding the '*'.
172	The encoding is n+29, yielding a printable character where n >=3
173	(which is where rle starts to win).  Don't use an n > 126.
174
175	So
176	"0* " means the same as "0000".  */
177
178#include "defs.h"
179#include "gdb_string.h"
180#include <fcntl.h>
181#include "frame.h"
182#include "inferior.h"
183#include "bfd.h"
184#include "symfile.h"
185#include "target.h"
186#include "wait.h"
187/*#include "terminal.h"*/
188#include "gdbcmd.h"
189#include "objfiles.h"
190#include "gdb-stabs.h"
191#include "thread.h"
192
193#include "dcache.h"
194
195#ifdef USG
196#include <sys/types.h>
197#endif
198
199#include <signal.h>
200#include "serial.h"
201
202/* Prototypes for local functions */
203
204static int remote_write_bytes PARAMS ((CORE_ADDR memaddr,
205				       char *myaddr, int len));
206
207static int remote_read_bytes PARAMS ((CORE_ADDR memaddr,
208				      char *myaddr, int len));
209
210static void remote_files_info PARAMS ((struct target_ops *ignore));
211
212static int remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr,
213				       int len, int should_write,
214				       struct target_ops *target));
215
216static void remote_prepare_to_store PARAMS ((void));
217
218static void remote_fetch_registers PARAMS ((int regno));
219
220static void remote_resume PARAMS ((int pid, int step,
221				   enum target_signal siggnal));
222
223static int remote_start_remote PARAMS ((char *dummy));
224
225static void remote_open PARAMS ((char *name, int from_tty));
226
227static void extended_remote_open PARAMS ((char *name, int from_tty));
228
229static void remote_open_1 PARAMS ((char *, int, struct target_ops *));
230
231static void remote_close PARAMS ((int quitting));
232
233static void remote_store_registers PARAMS ((int regno));
234
235static void remote_mourn PARAMS ((void));
236
237static void extended_remote_restart PARAMS ((void));
238
239static void extended_remote_mourn PARAMS ((void));
240
241static void extended_remote_create_inferior PARAMS ((char *, char *, char **));
242
243static void remote_mourn_1 PARAMS ((struct target_ops *));
244
245static void getpkt PARAMS ((char *buf, int forever));
246
247static int putpkt PARAMS ((char *buf));
248
249static void remote_send PARAMS ((char *buf));
250
251static int readchar PARAMS ((int timeout));
252
253static int remote_wait PARAMS ((int pid, struct target_waitstatus *status));
254
255static void remote_kill PARAMS ((void));
256
257static int tohex PARAMS ((int nib));
258
259static int fromhex PARAMS ((int a));
260
261static void remote_detach PARAMS ((char *args, int from_tty));
262
263static void remote_interrupt PARAMS ((int signo));
264
265static void remote_interrupt_twice PARAMS ((int signo));
266
267static void interrupt_query PARAMS ((void));
268
269extern struct target_ops remote_ops;	/* Forward decl */
270extern struct target_ops extended_remote_ops;	/* Forward decl */
271
272/* This was 5 seconds, which is a long time to sit and wait.
273   Unless this is going though some terminal server or multiplexer or
274   other form of hairy serial connection, I would think 2 seconds would
275   be plenty.  */
276
277static int remote_timeout = 2;
278
279/* This variable chooses whether to send a ^C or a break when the user
280   requests program interruption.  Although ^C is usually what remote
281   systems expect, and that is the default here, sometimes a break is
282   preferable instead.  */
283
284static int remote_break;
285
286/* Descriptor for I/O to remote machine.  Initialize it to NULL so that
287   remote_open knows that we don't have a file open when the program
288   starts.  */
289serial_t remote_desc = NULL;
290
291/* Having this larger than 400 causes us to be incompatible with m68k-stub.c
292   and i386-stub.c.  Normally, no one would notice because it only matters
293   for writing large chunks of memory (e.g. in downloads).  Also, this needs
294   to be more than 400 if required to hold the registers (see below, where
295   we round it up based on REGISTER_BYTES).  */
296#define	PBUFSIZ	400
297
298/* Maximum number of bytes to read/write at once.  The value here
299   is chosen to fill up a packet (the headers account for the 32).  */
300#define MAXBUFBYTES ((PBUFSIZ-32)/2)
301
302/* Round up PBUFSIZ to hold all the registers, at least.  */
303/* The blank line after the #if seems to be required to work around a
304   bug in HP's PA compiler.  */
305#if REGISTER_BYTES > MAXBUFBYTES
306
307#undef PBUFSIZ
308#define	PBUFSIZ	(REGISTER_BYTES * 2 + 32)
309#endif
310
311/* Should we try the 'P' request?  If this is set to one when the stub
312   doesn't support 'P', the only consequence is some unnecessary traffic.  */
313static int stub_supports_P = 1;
314
315
316/*
317 * Support for quasi-interactive control of device through GDB port.
318 * While we're waiting for an event to occur, chat with the running device.
319 */
320#define	REMOTE_CHAT
321#ifdef	REMOTE_CHAT
322
323extern int      quit_flag;
324
325static char     tty_input[256];
326static int      escape_count;
327static int      echo_check;
328static int	remote_chat = 0;
329
330enum read_stat {
331    READ_MORE,
332    FATAL_ERROR,
333    ENTER_DEBUG
334};
335
336static enum read_stat
337readtarget()
338{
339    int             j;
340    int             data;
341
342    /* Loop until the socket doesn't have any more data */
343    while ((data = readchar(0)) >= 0) {
344
345	/* Check for the escape sequence */
346	if (data == '|') {
347	    /* If this is the fourth escape, get out */
348	    if (++escape_count == 4)
349		return (ENTER_DEBUG);
350	    continue;		/* Not the fourth, continue */
351
352	} else {
353	    /*
354	     * Not an escape any more, Ensure any pending ones are flushed
355	     */
356	    for (j = 1; j <= escape_count; j++)
357		putchar('|');
358	    escape_count = 0;
359	}
360
361	if (data == '\r')	/* If this is a return character */
362	    continue;		/* just supress it */
363
364	if (echo_check != -1) {	/* If we are checking for an echo */
365	    /* If this might be an echo */
366	    if (tty_input[echo_check] == data) {
367		echo_check++;	/* Note one more character match */
368		continue;	/* Go and loop */
369	    } else {
370
371		if ((data == '\n') && (tty_input[echo_check] == '\r')) {
372		    /* If this is the end of the line */
373		    echo_check = -1;	/* No more echo supression */
374		    continue;	/* Go and loop */
375		}
376
377		/* Not an echo, print out the data */
378		for (j = 0; j < echo_check; j++)
379		    putchar(tty_input[j]);
380
381		echo_check = -1;/* No more echo checking */
382	    }
383	}
384	putchar(data);		/* Output the character */
385    }
386    return (READ_MORE);		/* Indicate to read some more */
387}
388
389static enum read_stat
390readtty()
391{
392    enum read_stat  status;
393    int             tty_bc;
394
395    /* First, read a buffer full from the terminal */
396    if ((tty_bc = read(fileno(stdin), tty_input, sizeof(tty_input) - 1)) < 0) {
397	perror_with_name("readtty: read failed");
398	return (FATAL_ERROR);
399    }
400
401    /* Turn trailing newlines into returns */
402    if (tty_input[tty_bc - 1] == '\n')
403	tty_input[tty_bc - 1] = '\r';
404
405    if ((tty_input[0] == '~') && (tty_bc == 3))
406	switch (tty_input[1]) {
407	case 'b':				/* ~b\n = send break & gdb */
408	    SERIAL_SEND_BREAK (remote_desc);
409	    /* fall through */
410
411	case 'c':				/* ~c\n = return to gdb */
412	    return (ENTER_DEBUG);
413	}
414
415    /* Make this a zero terminated string and write it out */
416    tty_input[tty_bc] = '\0';
417
418    if (SERIAL_WRITE(remote_desc, tty_input, tty_bc)) {
419	perror_with_name("readtty: write failed");
420	return (FATAL_ERROR);
421    }
422
423    return (READ_MORE);
424}
425
426static int
427remote_talk()
428{
429    fd_set          input;
430    int             tablesize;
431    enum read_stat  status;
432    int             panic_flag = 0;
433    char            buf[4];
434
435    escape_count = 0;
436    echo_check = -1;
437
438    tablesize = getdtablesize();
439
440    for (;;) {
441
442	/*
443	 * Check for anything from our socket - doesn't block. Note that this
444	 * must be done *before* the select as there may be buffered I/O
445	 * waiting to be processed.
446	 */
447	if ((status = readtarget()) != READ_MORE)
448	    return (status);
449
450	fflush(stdout);		/* Flush output before blocking */
451
452	/* Now block on more socket input or TTY input */
453	FD_ZERO(&input);
454	FD_SET(fileno(stdin), &input);
455	FD_SET(remote_desc->fd, &input);
456
457	status = select(tablesize, &input, 0, 0, 0);
458	if ((status < 0) && (errno != EINTR)) {
459	    perror_with_name("remote_talk: select");
460	    return (FATAL_ERROR);
461	}
462
463	/* Handle Control-C typed */
464	if (quit_flag) {
465	    if ((++panic_flag) == 3) {
466		printf("\nAre you repeating Control-C to terminate "
467		       "the session? (y/n) [n] ");
468		fgets(buf, 3, stdin);
469		if (buf[0] == 'y') {
470		    pop_target();	/* Clean up */
471		    error("Debugging terminated by user interrupt");
472		}
473		panic_flag = 0;
474	    }
475	    quit_flag = 0;
476	    SERIAL_WRITE(remote_desc, "\003", 1);
477	    continue;
478	}
479
480	/* Handle terminal input */
481	if (FD_ISSET(fileno(stdin), &input)) {
482	    panic_flag = 0;
483	    status = readtty();
484	    if (status != READ_MORE)
485		return (status);
486	    echo_check = 0;
487	}
488    }
489}
490
491#endif /* REMOTE_CHAT */
492
493/* These are the threads which we last sent to the remote system.  -1 for all
494   or -2 for not sent yet.  */
495int general_thread;
496int cont_thread;
497
498static void
499set_thread (th, gen)
500     int th;
501     int gen;
502{
503  char buf[PBUFSIZ];
504  int state = gen ? general_thread : cont_thread;
505  if (state == th)
506    return;
507  buf[0] = 'H';
508  buf[1] = gen ? 'g' : 'c';
509  if (th == 42000)
510    {
511      buf[2] = '0';
512      buf[3] = '\0';
513    }
514  else if (th < 0)
515    sprintf (&buf[2], "-%x", -th);
516  else
517    sprintf (&buf[2], "%x", th);
518  putpkt (buf);
519  getpkt (buf, 0);
520  if (gen)
521    general_thread = th;
522  else
523    cont_thread = th;
524}
525
526/*  Return nonzero if the thread TH is still alive on the remote system.  */
527
528static int
529remote_thread_alive (th)
530     int th;
531{
532  char buf[PBUFSIZ];
533
534  buf[0] = 'T';
535  if (th < 0)
536    sprintf (&buf[1], "-%x", -th);
537  else
538    sprintf (&buf[1], "%x", th);
539  putpkt (buf);
540  getpkt (buf, 0);
541  return (buf[0] == 'O' && buf[1] == 'K');
542}
543
544/*  Restart the remote side; this is an extended protocol operation.  */
545
546static void
547extended_remote_restart ()
548{
549  char buf[PBUFSIZ];
550
551  /* Send the restart command; for reasons I don't understand the
552     remote side really expects a number after the "R".  */
553  buf[0] = 'R';
554  sprintf (&buf[1], "%x", 0);
555  putpkt (buf);
556
557  /* Now query for status so this looks just like we restarted
558     gdbserver from scratch.  */
559  putpkt ("?");
560  getpkt (buf, 0);
561}
562
563/* Clean up connection to a remote debugger.  */
564
565/* ARGSUSED */
566static void
567remote_close (quitting)
568     int quitting;
569{
570  if (remote_desc)
571    SERIAL_CLOSE (remote_desc);
572  remote_desc = NULL;
573}
574
575/* Query the remote side for the text, data and bss offsets. */
576
577static void
578get_offsets ()
579{
580  char buf[PBUFSIZ];
581  int nvals;
582  CORE_ADDR text_addr, data_addr, bss_addr;
583  struct section_offsets *offs;
584
585#ifdef	REMOTE_CHAT
586      if (remote_chat)
587	  (void) remote_talk();
588#endif	/* REMOTE_CHAT */
589
590  putpkt ("qOffsets");
591
592  getpkt (buf, 0);
593
594  if (buf[0] == '\000')
595    return;			/* Return silently.  Stub doesn't support this
596				   command. */
597  if (buf[0] == 'E')
598    {
599      warning ("Remote failure reply: %s", buf);
600      return;
601    }
602
603  nvals = sscanf (buf, "Text=%lx;Data=%lx;Bss=%lx", &text_addr, &data_addr,
604		  &bss_addr);
605  if (nvals != 3)
606    error ("Malformed response to offset query, %s", buf);
607
608  if (symfile_objfile == NULL)
609    return;
610
611  offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
612					    + symfile_objfile->num_sections
613					    * sizeof (offs->offsets));
614  memcpy (offs, symfile_objfile->section_offsets,
615	  sizeof (struct section_offsets)
616	  + symfile_objfile->num_sections
617	  * sizeof (offs->offsets));
618
619  ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
620
621  /* This is a temporary kludge to force data and bss to use the same offsets
622     because that's what nlmconv does now.  The real solution requires changes
623     to the stub and remote.c that I don't have time to do right now.  */
624
625  ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
626  ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
627
628  objfile_relocate (symfile_objfile, offs);
629}
630
631/* Stub for catch_errors.  */
632
633static int
634remote_start_remote (dummy)
635     char *dummy;
636{
637  immediate_quit = 1;		/* Allow user to interrupt it */
638
639  /* Ack any packet which the remote side has already sent.  */
640  SERIAL_WRITE (remote_desc, "+", 1);
641
642  /* Let the stub know that we want it to return the thread.  */
643  set_thread (-1, 0);
644
645  get_offsets ();		/* Get text, data & bss offsets */
646
647  putpkt ("?");			/* initiate a query from remote machine */
648  immediate_quit = 0;
649
650  start_remote ();		/* Initialize gdb process mechanisms */
651  return 1;
652}
653
654/* Open a connection to a remote debugger.
655   NAME is the filename used for communication.  */
656
657static void
658remote_open (name, from_tty)
659     char *name;
660     int from_tty;
661{
662  remote_open_1 (name, from_tty, &remote_ops);
663}
664
665/* Open a connection to a remote debugger using the extended
666   remote gdb protocol.  NAME is the filename used for communication.  */
667
668static void
669extended_remote_open (name, from_tty)
670     char *name;
671     int from_tty;
672{
673  char buf[PBUFSIZ];
674
675  /* Do the basic remote open stuff.  */
676  remote_open_1 (name, from_tty, &extended_remote_ops);
677
678  /* Now tell the remote that we're using the extended protocol.  */
679  putpkt ("!");
680  getpkt (buf, 0);
681
682}
683
684/* Generic code for opening a connection to a remote target.  */
685static DCACHE *remote_dcache;
686
687static void
688remote_open_1 (name, from_tty, target)
689     char *name;
690     int from_tty;
691     struct target_ops *target;
692{
693  if (name == 0)
694    error ("To open a remote debug connection, you need to specify what serial\n\
695device is attached to the remote system (e.g. /dev/ttya).");
696
697  target_preopen (from_tty);
698
699  unpush_target (target);
700
701  remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
702
703  remote_desc = SERIAL_OPEN (name);
704  if (!remote_desc)
705    perror_with_name (name);
706
707  if (baud_rate != -1)
708    {
709      if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
710	{
711	  SERIAL_CLOSE (remote_desc);
712	  perror_with_name (name);
713	}
714    }
715
716
717  SERIAL_RAW (remote_desc);
718
719  /* If there is something sitting in the buffer we might take it as a
720     response to a command, which would be bad.  */
721  SERIAL_FLUSH_INPUT (remote_desc);
722
723  if (from_tty)
724    {
725      puts_filtered ("Remote debugging using ");
726      puts_filtered (name);
727      puts_filtered ("\n");
728    }
729  push_target (target);	/* Switch to using remote target now */
730
731  /* Start out by trying the 'P' request to set registers.  We set this each
732     time that we open a new target so that if the user switches from one
733     stub to another, we can (if the target is closed and reopened) cope.  */
734  stub_supports_P = 1;
735
736  general_thread = -2;
737  cont_thread = -2;
738
739  /* Without this, some commands which require an active target (such as kill)
740     won't work.  This variable serves (at least) double duty as both the pid
741     of the target process (if it has such), and as a flag indicating that a
742     target is active.  These functions should be split out into seperate
743     variables, especially since GDB will someday have a notion of debugging
744     several processes.  */
745
746  inferior_pid = 42000;
747  /* Start the remote connection; if error (0), discard this target.
748     In particular, if the user quits, be sure to discard it
749     (we'd be in an inconsistent state otherwise).  */
750  if (!catch_errors (remote_start_remote, (char *)0,
751		     "Couldn't establish connection to remote target\n", RETURN_MASK_ALL))
752    pop_target();
753}
754
755/* This takes a program previously attached to and detaches it.  After
756   this is done, GDB can be used to debug some other program.  We
757   better not have left any breakpoints in the target program or it'll
758   die when it hits one.  */
759
760static void
761remote_detach (args, from_tty)
762     char *args;
763     int from_tty;
764{
765  char buf[PBUFSIZ];
766
767  if (args)
768    error ("Argument given to \"detach\" when remotely debugging.");
769
770  /* Tell the remote target to detach.  */
771  strcpy (buf, "D");
772  remote_send (buf);
773
774  pop_target ();
775  if (from_tty)
776    puts_filtered ("Ending remote debugging.\n");
777}
778
779/* Convert hex digit A to a number.  */
780
781static int
782fromhex (a)
783     int a;
784{
785  if (a >= '0' && a <= '9')
786    return a - '0';
787  else if (a >= 'a' && a <= 'f')
788    return a - 'a' + 10;
789  else
790    error ("Reply contains invalid hex digit %d", a);
791}
792
793/* Convert number NIB to a hex digit.  */
794
795static int
796tohex (nib)
797     int nib;
798{
799  if (nib < 10)
800    return '0'+nib;
801  else
802    return 'a'+nib-10;
803}
804
805/* Tell the remote machine to resume.  */
806
807static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
808int last_sent_step;
809
810static void
811remote_resume (pid, step, siggnal)
812     int pid, step;
813     enum target_signal siggnal;
814{
815  char buf[PBUFSIZ];
816
817  if (pid == -1)
818    set_thread (inferior_pid, 0);
819  else
820    set_thread (pid, 0);
821
822  dcache_flush (remote_dcache);
823
824  last_sent_signal = siggnal;
825  last_sent_step = step;
826
827  if (siggnal != TARGET_SIGNAL_0)
828    {
829      buf[0] = step ? 'S' : 'C';
830      buf[1] = tohex (((int)siggnal >> 4) & 0xf);
831      buf[2] = tohex ((int)siggnal & 0xf);
832      buf[3] = '\0';
833    }
834  else
835    strcpy (buf, step ? "s": "c");
836
837  putpkt (buf);
838}
839
840/* Send ^C to target to halt it.  Target will respond, and send us a
841   packet.  */
842
843static void
844remote_interrupt (signo)
845     int signo;
846{
847  /* If this doesn't work, try more severe steps.  */
848  signal (signo, remote_interrupt_twice);
849
850  if (remote_debug)
851    printf_unfiltered ("remote_interrupt called\n");
852
853  /* Send a break or a ^C, depending on user preference.  */
854  if (remote_break)
855    SERIAL_SEND_BREAK (remote_desc);
856  else
857    SERIAL_WRITE (remote_desc, "\003", 1);
858}
859
860static void (*ofunc)();
861
862/* The user typed ^C twice.  */
863static void
864remote_interrupt_twice (signo)
865     int signo;
866{
867  signal (signo, ofunc);
868
869  interrupt_query ();
870
871  signal (signo, remote_interrupt);
872}
873
874/* Ask the user what to do when an interrupt is received.  */
875
876static void
877interrupt_query ()
878{
879  target_terminal_ours ();
880
881  if (query ("Interrupted while waiting for the program.\n\
882Give up (and stop debugging it)? "))
883    {
884      target_mourn_inferior ();
885      return_to_top_level (RETURN_QUIT);
886    }
887
888  target_terminal_inferior ();
889}
890
891/* If nonzero, ignore the next kill.  */
892int kill_kludge;
893
894/* Wait until the remote machine stops, then return,
895   storing status in STATUS just as `wait' would.
896   Returns "pid" (though it's not clear what, if anything, that
897   means in the case of this target).  */
898
899static int
900remote_wait (pid, status)
901     int pid;
902     struct target_waitstatus *status;
903{
904  unsigned char buf[PBUFSIZ];
905  int thread_num = -1;
906
907  status->kind = TARGET_WAITKIND_EXITED;
908  status->value.integer = 0;
909
910  while (1)
911    {
912      unsigned char *p;
913
914#ifdef	REMOTE_CHAT
915      if (remote_chat)
916	  (void) remote_talk();
917#endif	/* REMOTE_CHAT */
918
919      ofunc = (void (*)()) signal (SIGINT, remote_interrupt);
920      getpkt ((char *) buf, 1);
921      signal (SIGINT, ofunc);
922
923      switch (buf[0])
924	{
925	case 'E':		/* Error of some sort */
926	  warning ("Remote failure reply: %s", buf);
927	  continue;
928	case 'T':		/* Status with PC, SP, FP, ... */
929	  {
930	    int i;
931	    long regno;
932	    char regs[MAX_REGISTER_RAW_SIZE];
933
934	    /* Expedited reply, containing Signal, {regno, reg} repeat */
935	    /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
936		ss = signal number
937		n... = register number
938		r... = register contents
939		*/
940
941	    p = &buf[3];	/* after Txx */
942
943	    while (*p)
944	      {
945		unsigned char *p1;
946		char *p_temp;
947
948		regno = strtol ((const char *) p, &p_temp, 16); /* Read the register number */
949		p1 = (unsigned char *)p_temp;
950
951		if (p1 == p)
952		  {
953		    p1 = (unsigned char *) strchr ((const char *) p, ':');
954		    if (p1 == NULL)
955		      warning ("Malformed packet (missing colon): %s\n\
956Packet: '%s'\n",
957			       p, buf);
958		    if (strncmp ((const char *) p, "thread", p1 - p) == 0)
959		      {
960			thread_num = strtol ((const char *) ++p1, &p_temp, 16);
961			p = (unsigned char *)p_temp;
962		      }
963		  }
964		else
965		  {
966		    p = p1;
967
968		    if (*p++ != ':')
969		      warning ("Malformed packet (missing colon): %s\n\
970Packet: '%s'\n",
971			       p, buf);
972
973		    if (regno >= NUM_REGS)
974		      warning ("Remote sent bad register number %ld: %s\n\
975Packet: '%s'\n",
976			       regno, p, buf);
977
978		    for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
979		      {
980			if (p[0] == 0 || p[1] == 0)
981			  warning ("Remote reply is too short: %s", buf);
982			regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
983			p += 2;
984		      }
985		    supply_register (regno, regs);
986		  }
987
988		if (*p++ != ';')
989		  warning ("Remote register badly formatted: %s", buf);
990	      }
991	  }
992	  /* fall through */
993	case 'S':		/* Old style status, just signal only */
994	  status->kind = TARGET_WAITKIND_STOPPED;
995	  status->value.sig = (enum target_signal)
996	    (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
997
998	  goto got_status;
999	case 'W':		/* Target exited */
1000	  {
1001	    /* The remote process exited.  */
1002	    status->kind = TARGET_WAITKIND_EXITED;
1003	    status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
1004	    goto got_status;
1005	  }
1006	case 'X':
1007	  status->kind = TARGET_WAITKIND_SIGNALLED;
1008	  status->value.sig = (enum target_signal)
1009	    (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
1010	  kill_kludge = 1;
1011
1012	  goto got_status;
1013	case 'O':		/* Console output */
1014 	  for (p = buf + 1; *p; p +=2)
1015 	    {
1016 	      char tb[2];
1017 	      char c = fromhex (p[0]) * 16 + fromhex (p[1]);
1018 	      tb[0] = c;
1019 	      tb[1] = 0;
1020 	      if (target_output_hook)
1021 		target_output_hook (tb);
1022 	      else
1023 		fputs_filtered (tb, gdb_stdout);
1024 	    }
1025	  continue;
1026	case '\0':
1027	  if (last_sent_signal != TARGET_SIGNAL_0)
1028	    {
1029	      /* Zero length reply means that we tried 'S' or 'C' and
1030		 the remote system doesn't support it.  */
1031	      target_terminal_ours_for_output ();
1032	      printf_filtered
1033		("Can't send signals to this remote system.  %s not sent.\n",
1034		 target_signal_to_name (last_sent_signal));
1035	      last_sent_signal = TARGET_SIGNAL_0;
1036	      target_terminal_inferior ();
1037
1038	      strcpy ((char *) buf, last_sent_step ? "s" : "c");
1039	      putpkt ((char *) buf);
1040	      continue;
1041	    }
1042	  /* else fallthrough */
1043	default:
1044	  warning ("Invalid remote reply: %s", buf);
1045	  continue;
1046	}
1047    }
1048 got_status:
1049  if (thread_num != -1)
1050    {
1051      /* Initial thread value can only be acquired via wait, so deal with
1052	 this marker which is used before the first thread value is
1053	 acquired.  */
1054      if (inferior_pid == 42000)
1055	{
1056	  inferior_pid = thread_num;
1057	  add_thread (inferior_pid);
1058	}
1059      return thread_num;
1060    }
1061  return inferior_pid;
1062}
1063
1064/* Number of bytes of registers this stub implements.  */
1065static int register_bytes_found;
1066
1067/* Read the remote registers into the block REGS.  */
1068/* Currently we just read all the registers, so we don't use regno.  */
1069/* ARGSUSED */
1070static void
1071remote_fetch_registers (regno)
1072     int regno;
1073{
1074  char buf[PBUFSIZ];
1075  int i;
1076  char *p;
1077  char regs[REGISTER_BYTES];
1078
1079  set_thread (inferior_pid, 1);
1080
1081  sprintf (buf, "g");
1082  remote_send (buf);
1083
1084  /* Unimplemented registers read as all bits zero.  */
1085  memset (regs, 0, REGISTER_BYTES);
1086
1087  /* We can get out of synch in various cases.  If the first character
1088     in the buffer is not a hex character, assume that has happened
1089     and try to fetch another packet to read.  */
1090  while ((buf[0] < '0' || buf[0] > '9')
1091	 && (buf[0] < 'a' || buf[0] > 'f'))
1092    {
1093      if (remote_debug)
1094	printf_unfiltered ("Bad register packet; fetching a new packet\n");
1095      getpkt (buf, 0);
1096    }
1097
1098  /* Reply describes registers byte by byte, each byte encoded as two
1099     hex characters.  Suck them all up, then supply them to the
1100     register cacheing/storage mechanism.  */
1101
1102  p = buf;
1103  for (i = 0; i < REGISTER_BYTES; i++)
1104    {
1105      if (p[0] == 0)
1106	break;
1107      if (p[1] == 0)
1108	{
1109	  warning ("Remote reply is of odd length: %s", buf);
1110	  /* Don't change register_bytes_found in this case, and don't
1111	     print a second warning.  */
1112	  goto supply_them;
1113	}
1114      regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
1115      p += 2;
1116    }
1117
1118  if (i != register_bytes_found)
1119    {
1120      register_bytes_found = i;
1121#ifdef REGISTER_BYTES_OK
1122      if (!REGISTER_BYTES_OK (i))
1123	warning ("Remote reply is too short: %s", buf);
1124#endif
1125    }
1126
1127 supply_them:
1128  for (i = 0; i < NUM_REGS; i++)
1129    supply_register (i, &regs[REGISTER_BYTE(i)]);
1130}
1131
1132/* Prepare to store registers.  Since we may send them all (using a
1133   'G' request), we have to read out the ones we don't want to change
1134   first.  */
1135
1136static void
1137remote_prepare_to_store ()
1138{
1139  /* Make sure the entire registers array is valid.  */
1140  read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
1141}
1142
1143/* Store register REGNO, or all registers if REGNO == -1, from the contents
1144   of REGISTERS.  FIXME: ignores errors.  */
1145
1146static void
1147remote_store_registers (regno)
1148     int regno;
1149{
1150  char buf[PBUFSIZ];
1151  int i;
1152  char *p;
1153
1154  set_thread (inferior_pid, 1);
1155
1156  if (regno >= 0 && stub_supports_P)
1157    {
1158      /* Try storing a single register.  */
1159      char *regp;
1160
1161      sprintf (buf, "P%x=", regno);
1162      p = buf + strlen (buf);
1163      regp = &registers[REGISTER_BYTE (regno)];
1164      for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
1165	{
1166	  *p++ = tohex ((regp[i] >> 4) & 0xf);
1167	  *p++ = tohex (regp[i] & 0xf);
1168	}
1169      *p = '\0';
1170      remote_send (buf);
1171      if (buf[0] != '\0')
1172	{
1173	  /* The stub understands the 'P' request.  We are done.  */
1174	  return;
1175	}
1176
1177      /* The stub does not support the 'P' request.  Use 'G' instead,
1178	 and don't try using 'P' in the future (it will just waste our
1179	 time).  */
1180      stub_supports_P = 0;
1181    }
1182
1183  buf[0] = 'G';
1184
1185  /* Command describes registers byte by byte,
1186     each byte encoded as two hex characters.  */
1187
1188  p = buf + 1;
1189  /* remote_prepare_to_store insures that register_bytes_found gets set.  */
1190  for (i = 0; i < register_bytes_found; i++)
1191    {
1192      *p++ = tohex ((registers[i] >> 4) & 0xf);
1193      *p++ = tohex (registers[i] & 0xf);
1194    }
1195  *p = '\0';
1196
1197  remote_send (buf);
1198}
1199
1200/*
1201   Use of the data cache *used* to be disabled because it loses for looking at
1202   and changing hardware I/O ports and the like.  Accepting `volatile'
1203   would perhaps be one way to fix it.  Another idea would be to use the
1204   executable file for the text segment (for all SEC_CODE sections?
1205   For all SEC_READONLY sections?).  This has problems if you want to
1206   actually see what the memory contains (e.g. self-modifying code,
1207   clobbered memory, user downloaded the wrong thing).
1208
1209   Because it speeds so much up, it's now enabled, if you're playing
1210   with registers you turn it of (set remotecache 0)
1211*/
1212
1213/* Read a word from remote address ADDR and return it.
1214   This goes through the data cache.  */
1215
1216#if 0	/* unused? */
1217static int
1218remote_fetch_word (addr)
1219     CORE_ADDR addr;
1220{
1221  return dcache_fetch (remote_dcache, addr);
1222}
1223
1224/* Write a word WORD into remote address ADDR.
1225   This goes through the data cache.  */
1226
1227static void
1228remote_store_word (addr, word)
1229     CORE_ADDR addr;
1230     int word;
1231{
1232  dcache_poke (remote_dcache, addr, word);
1233}
1234#endif	/* 0 (unused?) */
1235
1236
1237/* Write memory data directly to the remote machine.
1238   This does not inform the data cache; the data cache uses this.
1239   MEMADDR is the address in the remote memory space.
1240   MYADDR is the address of the buffer in our space.
1241   LEN is the number of bytes.
1242
1243   Returns number of bytes transferred, or 0 for error.  */
1244
1245static int
1246remote_write_bytes (memaddr, myaddr, len)
1247     CORE_ADDR memaddr;
1248     char *myaddr;
1249     int len;
1250{
1251  char buf[PBUFSIZ];
1252  int i;
1253  char *p;
1254  int done;
1255  /* Chop the transfer down if necessary */
1256
1257  done = 0;
1258  while (done < len)
1259    {
1260      int todo = len - done;
1261      int cando = PBUFSIZ /2 - 32; /* number of bytes that will fit. */
1262      if (todo > cando)
1263	todo = cando;
1264
1265      /* FIXME-32x64: Need a version of print_address_numeric which puts the
1266	 result in a buffer like sprintf.  */
1267      sprintf (buf, "M%lx,%x:", (unsigned long) memaddr + done, todo);
1268
1269      /* We send target system values byte by byte, in increasing byte addresses,
1270	 each byte encoded as two hex characters.  */
1271
1272      p = buf + strlen (buf);
1273      for (i = 0; i < todo; i++)
1274	{
1275	  *p++ = tohex ((myaddr[i + done] >> 4) & 0xf);
1276	  *p++ = tohex (myaddr[i + done] & 0xf);
1277	}
1278      *p = '\0';
1279
1280      putpkt (buf);
1281      getpkt (buf, 0);
1282
1283      if (buf[0] == 'E')
1284	{
1285	  /* There is no correspondance between what the remote protocol uses
1286	     for errors and errno codes.  We would like a cleaner way of
1287	     representing errors (big enough to include errno codes, bfd_error
1288	     codes, and others).  But for now just return EIO.  */
1289	  errno = EIO;
1290	  return 0;
1291	}
1292      done += todo;
1293    }
1294  return len;
1295}
1296
1297/* Read memory data directly from the remote machine.
1298   This does not use the data cache; the data cache uses this.
1299   MEMADDR is the address in the remote memory space.
1300   MYADDR is the address of the buffer in our space.
1301   LEN is the number of bytes.
1302
1303   Returns number of bytes transferred, or 0 for error.  */
1304
1305static int
1306remote_read_bytes (memaddr, myaddr, len)
1307     CORE_ADDR memaddr;
1308     char *myaddr;
1309     int len;
1310{
1311  char buf[PBUFSIZ];
1312  int i;
1313  char *p;
1314  int done;
1315  /* Chop transfer down if neccessary */
1316
1317#if 0
1318  /* FIXME: This is wrong for larger packets */
1319  if (len > PBUFSIZ / 2 - 1)
1320    abort ();
1321#endif
1322  done = 0;
1323  while (done < len)
1324    {
1325      int todo = len - done;
1326      int cando = PBUFSIZ / 2 - 32; /* number of bytes that will fit. */
1327      if (todo > cando)
1328	todo = cando;
1329
1330      /* FIXME-32x64: Need a version of print_address_numeric which puts the
1331	 result in a buffer like sprintf.  */
1332      sprintf (buf, "m%lx,%x", (unsigned long) memaddr + done, todo);
1333      putpkt (buf);
1334      getpkt (buf, 0);
1335
1336      if (buf[0] == 'E')
1337	{
1338	  /* There is no correspondance between what the remote protocol uses
1339	     for errors and errno codes.  We would like a cleaner way of
1340	     representing errors (big enough to include errno codes, bfd_error
1341	     codes, and others).  But for now just return EIO.  */
1342	  errno = EIO;
1343	  return 0;
1344	}
1345
1346  /* Reply describes memory byte by byte,
1347     each byte encoded as two hex characters.  */
1348
1349      p = buf;
1350      for (i = 0; i < todo; i++)
1351	{
1352	  if (p[0] == 0 || p[1] == 0)
1353	    /* Reply is short.  This means that we were able to read only part
1354	       of what we wanted to.  */
1355	    return i + done;
1356	  myaddr[i + done] = fromhex (p[0]) * 16 + fromhex (p[1]);
1357	  p += 2;
1358	}
1359      done += todo;
1360    }
1361  return len;
1362}
1363
1364/* Read or write LEN bytes from inferior memory at MEMADDR, transferring
1365   to or from debugger address MYADDR.  Write to inferior if SHOULD_WRITE is
1366   nonzero.  Returns length of data written or read; 0 for error.  */
1367
1368/* ARGSUSED */
1369static int
1370remote_xfer_memory(memaddr, myaddr, len, should_write, target)
1371     CORE_ADDR memaddr;
1372     char *myaddr;
1373     int len;
1374     int should_write;
1375     struct target_ops *target;			/* ignored */
1376{
1377  return dcache_xfer_memory (remote_dcache, memaddr, myaddr, len, should_write);
1378}
1379
1380
1381#if 0
1382/* Enable after 4.12.  */
1383
1384void
1385remote_search (len, data, mask, startaddr, increment, lorange, hirange
1386	       addr_found, data_found)
1387     int len;
1388     char *data;
1389     char *mask;
1390     CORE_ADDR startaddr;
1391     int increment;
1392     CORE_ADDR lorange;
1393     CORE_ADDR hirange;
1394     CORE_ADDR *addr_found;
1395     char *data_found;
1396{
1397  if (increment == -4 && len == 4)
1398    {
1399      long mask_long, data_long;
1400      long data_found_long;
1401      CORE_ADDR addr_we_found;
1402      char buf[PBUFSIZ];
1403      long returned_long[2];
1404      char *p;
1405
1406      mask_long = extract_unsigned_integer (mask, len);
1407      data_long = extract_unsigned_integer (data, len);
1408      sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
1409      putpkt (buf);
1410      getpkt (buf, 0);
1411      if (buf[0] == '\0')
1412	{
1413	  /* The stub doesn't support the 't' request.  We might want to
1414	     remember this fact, but on the other hand the stub could be
1415	     switched on us.  Maybe we should remember it only until
1416	     the next "target remote".  */
1417	  generic_search (len, data, mask, startaddr, increment, lorange,
1418			  hirange, addr_found, data_found);
1419	  return;
1420	}
1421
1422      if (buf[0] == 'E')
1423	/* There is no correspondance between what the remote protocol uses
1424	   for errors and errno codes.  We would like a cleaner way of
1425	   representing errors (big enough to include errno codes, bfd_error
1426	   codes, and others).  But for now just use EIO.  */
1427	memory_error (EIO, startaddr);
1428      p = buf;
1429      addr_we_found = 0;
1430      while (*p != '\0' && *p != ',')
1431	addr_we_found = (addr_we_found << 4) + fromhex (*p++);
1432      if (*p == '\0')
1433	error ("Protocol error: short return for search");
1434
1435      data_found_long = 0;
1436      while (*p != '\0' && *p != ',')
1437	data_found_long = (data_found_long << 4) + fromhex (*p++);
1438      /* Ignore anything after this comma, for future extensions.  */
1439
1440      if (addr_we_found < lorange || addr_we_found >= hirange)
1441	{
1442	  *addr_found = 0;
1443	  return;
1444	}
1445
1446      *addr_found = addr_we_found;
1447      *data_found = store_unsigned_integer (data_we_found, len);
1448      return;
1449    }
1450  generic_search (len, data, mask, startaddr, increment, lorange,
1451		  hirange, addr_found, data_found);
1452}
1453#endif /* 0 */
1454
1455static void
1456remote_files_info (ignore)
1457     struct target_ops *ignore;
1458{
1459  puts_filtered ("Debugging a target over a serial line.\n");
1460}
1461
1462/* Stuff for dealing with the packets which are part of this protocol.
1463   See comment at top of file for details.  */
1464
1465/* Read a single character from the remote end, masking it down to 7 bits. */
1466
1467static int
1468readchar (timeout)
1469     int timeout;
1470{
1471  int ch;
1472
1473  ch = SERIAL_READCHAR (remote_desc, timeout);
1474
1475  switch (ch)
1476    {
1477    case SERIAL_EOF:
1478      error ("Remote connection closed");
1479    case SERIAL_ERROR:
1480      perror_with_name ("Remote communication error");
1481    case SERIAL_TIMEOUT:
1482      return ch;
1483    default:
1484      return ch & 0x7f;
1485    }
1486}
1487
1488/* Send the command in BUF to the remote machine,
1489   and read the reply into BUF.
1490   Report an error if we get an error reply.  */
1491
1492static void
1493remote_send (buf)
1494     char *buf;
1495{
1496  putpkt (buf);
1497  getpkt (buf, 0);
1498
1499  if (buf[0] == 'E')
1500    error ("Remote failure reply: %s", buf);
1501}
1502
1503/* Send a packet to the remote machine, with error checking.
1504   The data of the packet is in BUF.  */
1505
1506static int
1507putpkt (buf)
1508     char *buf;
1509{
1510  int i;
1511  unsigned char csum = 0;
1512  char buf2[PBUFSIZ];
1513  int cnt = strlen (buf);
1514  int ch;
1515  int tcount = 0;
1516  char *p;
1517
1518  /* Copy the packet into buffer BUF2, encapsulating it
1519     and giving it a checksum.  */
1520
1521  if (cnt > (int) sizeof (buf2) - 5)		/* Prosanity check */
1522    abort();
1523
1524  p = buf2;
1525  *p++ = '$';
1526
1527  for (i = 0; i < cnt; i++)
1528    {
1529      csum += buf[i];
1530      *p++ = buf[i];
1531    }
1532  *p++ = '#';
1533  *p++ = tohex ((csum >> 4) & 0xf);
1534  *p++ = tohex (csum & 0xf);
1535
1536  /* Send it over and over until we get a positive ack.  */
1537
1538  while (1)
1539    {
1540      int started_error_output = 0;
1541
1542      if (remote_debug)
1543	{
1544	  *p = '\0';
1545	  printf_unfiltered ("Sending packet: %s...", buf2);
1546	  gdb_flush(gdb_stdout);
1547	}
1548      if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
1549	perror_with_name ("putpkt: write failed");
1550
1551      /* read until either a timeout occurs (-2) or '+' is read */
1552      while (1)
1553	{
1554	  ch = readchar (remote_timeout);
1555
1556 	  if (remote_debug)
1557	    {
1558	      switch (ch)
1559		{
1560		case '+':
1561		case SERIAL_TIMEOUT:
1562		case '$':
1563		  if (started_error_output)
1564		    {
1565		      putchar_unfiltered ('\n');
1566		      started_error_output = 0;
1567		    }
1568		}
1569	    }
1570
1571	  switch (ch)
1572	    {
1573	    case '+':
1574	      if (remote_debug)
1575		printf_unfiltered("Ack\n");
1576	      return 1;
1577	    case SERIAL_TIMEOUT:
1578	      tcount ++;
1579	      if (tcount > 3)
1580		return 0;
1581	      break;		/* Retransmit buffer */
1582	    case '$':
1583	      {
1584		char junkbuf[PBUFSIZ];
1585
1586	      /* It's probably an old response, and we're out of sync.  Just
1587		 gobble up the packet and ignore it.  */
1588		getpkt (junkbuf, 0);
1589		continue;		/* Now, go look for + */
1590	      }
1591
1592#ifdef	REMOTE_CHAT
1593	    case '|':
1594	      {
1595		if (!started_error_output)
1596		    continue;
1597		/* else fall through */
1598	      }
1599#endif	/* REMOTE_CHAT */
1600
1601	    default:
1602	      if (remote_debug)
1603		{
1604		  if (!started_error_output)
1605		    {
1606		      started_error_output = 1;
1607		      printf_unfiltered ("putpkt: Junk: ");
1608		    }
1609		  putchar_unfiltered (ch & 0177);
1610		}
1611	      continue;
1612	    }
1613	  break;		/* Here to retransmit */
1614	}
1615
1616#if 0
1617      /* This is wrong.  If doing a long backtrace, the user should be
1618	 able to get out next time we call QUIT, without anything as violent
1619	 as interrupt_query.  If we want to provide a way out of here
1620	 without getting to the next QUIT, it should be based on hitting
1621	 ^C twice as in remote_wait.  */
1622      if (quit_flag)
1623	{
1624	  quit_flag = 0;
1625	  interrupt_query ();
1626	}
1627#endif
1628    }
1629}
1630
1631/* Come here after finding the start of the frame.  Collect the rest into BUF,
1632   verifying the checksum, length, and handling run-length compression.
1633   Returns 0 on any error, 1 on success.  */
1634
1635static int
1636read_frame (buf)
1637     char *buf;
1638{
1639  unsigned char csum;
1640  char *bp;
1641  int c;
1642
1643  csum = 0;
1644  bp = buf;
1645
1646  while (1)
1647    {
1648      c = readchar (remote_timeout);
1649
1650      switch (c)
1651	{
1652	case SERIAL_TIMEOUT:
1653	  if (remote_debug)
1654	    puts_filtered ("Timeout in mid-packet, retrying\n");
1655	  return 0;
1656	case '$':
1657	  if (remote_debug)
1658	    puts_filtered ("Saw new packet start in middle of old one\n");
1659	  return 0;		/* Start a new packet, count retries */
1660	case '#':
1661	  {
1662	    unsigned char pktcsum;
1663
1664	    *bp = '\000';
1665
1666	    pktcsum = fromhex (readchar (remote_timeout)) << 4;
1667	    pktcsum |= fromhex (readchar (remote_timeout));
1668
1669	    if (csum == pktcsum)
1670	      return 1;
1671
1672	    if (remote_debug)
1673	      {
1674		printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
1675				 pktcsum, csum);
1676		puts_filtered (buf);
1677		puts_filtered ("\n");
1678	      }
1679	    return 0;
1680	  }
1681	case '*':		/* Run length encoding */
1682	  csum += c;
1683	  c = readchar (remote_timeout);
1684	  csum += c;
1685	  c = c - ' ' + 3;	/* Compute repeat count */
1686
1687
1688	  if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
1689	    {
1690	      memset (bp, *(bp - 1), c);
1691	      bp += c;
1692	      continue;
1693	    }
1694
1695	  *bp = '\0';
1696	  printf_filtered ("Repeat count %d too large for buffer: ", c);
1697	  puts_filtered (buf);
1698	  puts_filtered ("\n");
1699	  return 0;
1700
1701	default:
1702	  if (bp < buf + PBUFSIZ - 1)
1703	    {
1704	      *bp++ = c;
1705	      csum += c;
1706	      continue;
1707	    }
1708
1709	  *bp = '\0';
1710	  puts_filtered ("Remote packet too long: ");
1711	  puts_filtered (buf);
1712	  puts_filtered ("\n");
1713
1714	  return 0;
1715	}
1716    }
1717}
1718
1719/* Read a packet from the remote machine, with error checking,
1720   and store it in BUF.  BUF is expected to be of size PBUFSIZ.
1721   If FOREVER, wait forever rather than timing out; this is used
1722   while the target is executing user code.  */
1723
1724static void
1725getpkt (buf, forever)
1726     char *buf;
1727     int forever;
1728{
1729  int c;
1730  int tries;
1731  int timeout;
1732  int val;
1733
1734  strcpy (buf,"timeout");
1735
1736  if (forever)
1737    {
1738#ifdef MAINTENANCE_CMDS
1739      timeout = watchdog > 0 ? watchdog : -1;
1740#else
1741      timeout = -1;
1742#endif
1743    }
1744
1745  else
1746    timeout = remote_timeout;
1747
1748#define MAX_TRIES 3
1749
1750  for (tries = 1; tries <= MAX_TRIES; tries++)
1751    {
1752      /* This can loop forever if the remote side sends us characters
1753	 continuously, but if it pauses, we'll get a zero from readchar
1754	 because of timeout.  Then we'll count that as a retry.  */
1755
1756      /* Note that we will only wait forever prior to the start of a packet.
1757	 After that, we expect characters to arrive at a brisk pace.  They
1758	 should show up within remote_timeout intervals.  */
1759
1760      do
1761	{
1762	  c = readchar (timeout);
1763
1764	  if (c == SERIAL_TIMEOUT)
1765	    {
1766#ifdef MAINTENANCE_CMDS
1767	      if (forever)	/* Watchdog went off.  Kill the target. */
1768		{
1769		  target_mourn_inferior ();
1770		  error ("Watchdog has expired.  Target detached.\n");
1771		}
1772#endif
1773	      if (remote_debug)
1774		puts_filtered ("Timed out.\n");
1775	      goto retry;
1776	    }
1777	}
1778      while (c != '$');
1779
1780      /* We've found the start of a packet, now collect the data.  */
1781
1782      val = read_frame (buf);
1783
1784      if (val == 1)
1785	{
1786	  if (remote_debug)
1787	    fprintf_unfiltered (gdb_stderr, "Packet received: %s\n", buf);
1788	  SERIAL_WRITE (remote_desc, "+", 1);
1789	  return;
1790	}
1791
1792      /* Try the whole thing again.  */
1793    retry:
1794      SERIAL_WRITE (remote_desc, "-", 1);
1795    }
1796
1797  /* We have tried hard enough, and just can't receive the packet.  Give up. */
1798
1799  printf_unfiltered ("Ignoring packet error, continuing...\n");
1800  SERIAL_WRITE (remote_desc, "+", 1);
1801}
1802
1803static void
1804remote_kill ()
1805{
1806  /* For some mysterious reason, wait_for_inferior calls kill instead of
1807     mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
1808  if (kill_kludge)
1809    {
1810      kill_kludge = 0;
1811      target_mourn_inferior ();
1812      return;
1813    }
1814
1815  /* Use catch_errors so the user can quit from gdb even when we aren't on
1816     speaking terms with the remote system.  */
1817  catch_errors (putpkt, "k", "", RETURN_MASK_ERROR);
1818
1819  /* Don't wait for it to die.  I'm not really sure it matters whether
1820     we do or not.  For the existing stubs, kill is a noop.  */
1821  target_mourn_inferior ();
1822}
1823
1824static void
1825remote_mourn ()
1826{
1827  remote_mourn_1 (&remote_ops);
1828}
1829
1830static void
1831extended_remote_mourn ()
1832{
1833  /* We do _not_ want to mourn the target like this; this will
1834     remove the extended remote target  from the target stack,
1835     and the next time the user says "run" it'll fail.
1836
1837     FIXME: What is the right thing to do here?  */
1838#if 0
1839  remote_mourn_1 (&extended_remote_ops);
1840#endif
1841}
1842
1843/* Worker function for remote_mourn.  */
1844static void
1845remote_mourn_1 (target)
1846     struct target_ops *target;
1847{
1848  unpush_target (target);
1849  generic_mourn_inferior ();
1850}
1851
1852/* In the extended protocol we want to be able to do things like
1853   "run" and have them basically work as expected.  So we need
1854   a special create_inferior function.
1855
1856   FIXME: One day add support for changing the exec file
1857   we're debugging, arguments and an environment.  */
1858
1859static void
1860extended_remote_create_inferior (exec_file, args, env)
1861     char *exec_file;
1862     char *args;
1863     char **env;
1864{
1865  /* Rip out the breakpoints; we'll reinsert them after restarting
1866     the remote server.  */
1867  remove_breakpoints ();
1868
1869  /* Now restart the remote server.  */
1870  extended_remote_restart ();
1871
1872  /* Now put the breakpoints back in.  This way we're safe if the
1873     restart function works via a unix fork on the remote side.  */
1874  insert_breakpoints ();
1875
1876  /* Clean up from the last time we were running.  */
1877  clear_proceed_status ();
1878
1879  /* Let the remote process run.  */
1880  proceed (-1, TARGET_SIGNAL_0, 0);
1881}
1882
1883
1884#ifdef REMOTE_BREAKPOINT
1885
1886/* On some machines, e.g. 68k, we may use a different breakpoint instruction
1887   than other targets.  */
1888static unsigned char break_insn[] = REMOTE_BREAKPOINT;
1889
1890#else /* No REMOTE_BREAKPOINT.  */
1891
1892/* Same old breakpoint instruction.  This code does nothing different
1893   than mem-break.c.  */
1894static unsigned char break_insn[] = BREAKPOINT;
1895
1896#endif /* No REMOTE_BREAKPOINT.  */
1897
1898/* Insert a breakpoint on targets that don't have any better breakpoint
1899   support.  We read the contents of the target location and stash it,
1900   then overwrite it with a breakpoint instruction.  ADDR is the target
1901   location in the target machine.  CONTENTS_CACHE is a pointer to
1902   memory allocated for saving the target contents.  It is guaranteed
1903   by the caller to be long enough to save sizeof BREAKPOINT bytes (this
1904   is accomplished via BREAKPOINT_MAX).  */
1905
1906static int
1907remote_insert_breakpoint (addr, contents_cache)
1908     CORE_ADDR addr;
1909     char *contents_cache;
1910{
1911  int val;
1912
1913  val = target_read_memory (addr, contents_cache, sizeof break_insn);
1914
1915  if (val == 0)
1916    val = target_write_memory (addr, (char *)break_insn, sizeof break_insn);
1917
1918  return val;
1919}
1920
1921static int
1922remote_remove_breakpoint (addr, contents_cache)
1923     CORE_ADDR addr;
1924     char *contents_cache;
1925{
1926  return target_write_memory (addr, contents_cache, sizeof break_insn);
1927}
1928
1929/* Define the target subroutine names */
1930
1931struct target_ops remote_ops = {
1932  "remote",			/* to_shortname */
1933  "Remote serial target in gdb-specific protocol",	/* to_longname */
1934  "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
1935Specify the serial device it is connected to (e.g. /dev/ttya).",  /* to_doc */
1936  remote_open,			/* to_open */
1937  remote_close,			/* to_close */
1938  NULL,				/* to_attach */
1939  remote_detach,		/* to_detach */
1940  remote_resume,		/* to_resume */
1941  remote_wait,			/* to_wait */
1942  remote_fetch_registers,	/* to_fetch_registers */
1943  remote_store_registers,	/* to_store_registers */
1944  remote_prepare_to_store,	/* to_prepare_to_store */
1945  remote_xfer_memory,		/* to_xfer_memory */
1946  remote_files_info,		/* to_files_info */
1947  remote_insert_breakpoint,	/* to_insert_breakpoint */
1948  remote_remove_breakpoint,	/* to_remove_breakpoint */
1949  NULL,				/* to_terminal_init */
1950  NULL,				/* to_terminal_inferior */
1951  NULL,				/* to_terminal_ours_for_output */
1952  NULL,				/* to_terminal_ours */
1953  NULL,				/* to_terminal_info */
1954  remote_kill,			/* to_kill */
1955  generic_load,			/* to_load */
1956  NULL,				/* to_lookup_symbol */
1957  NULL,				/* to_create_inferior */
1958  remote_mourn,			/* to_mourn_inferior */
1959  0,				/* to_can_run */
1960  0,				/* to_notice_signals */
1961  remote_thread_alive,		/* to_thread_alive */
1962  0,				/* to_stop */
1963  process_stratum,		/* to_stratum */
1964  NULL,				/* to_next */
1965  1,				/* to_has_all_memory */
1966  1,				/* to_has_memory */
1967  1,				/* to_has_stack */
1968  1,				/* to_has_registers */
1969  1,				/* to_has_execution */
1970  NULL,				/* sections */
1971  NULL,				/* sections_end */
1972  OPS_MAGIC			/* to_magic */
1973};
1974
1975struct target_ops extended_remote_ops = {
1976  "extended-remote",			/* to_shortname */
1977  "Extended remote serial target in gdb-specific protocol",/* to_longname */
1978  "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
1979Specify the serial device it is connected to (e.g. /dev/ttya).",  /* to_doc */
1980  extended_remote_open,			/* to_open */
1981  remote_close,			/* to_close */
1982  NULL,				/* to_attach */
1983  remote_detach,		/* to_detach */
1984  remote_resume,		/* to_resume */
1985  remote_wait,			/* to_wait */
1986  remote_fetch_registers,	/* to_fetch_registers */
1987  remote_store_registers,	/* to_store_registers */
1988  remote_prepare_to_store,	/* to_prepare_to_store */
1989  remote_xfer_memory,		/* to_xfer_memory */
1990  remote_files_info,		/* to_files_info */
1991
1992  remote_insert_breakpoint,	/* to_insert_breakpoint */
1993  remote_remove_breakpoint,	/* to_remove_breakpoint */
1994
1995  NULL,				/* to_terminal_init */
1996  NULL,				/* to_terminal_inferior */
1997  NULL,				/* to_terminal_ours_for_output */
1998  NULL,				/* to_terminal_ours */
1999  NULL,				/* to_terminal_info */
2000  remote_kill,			/* to_kill */
2001  generic_load,			/* to_load */
2002  NULL,				/* to_lookup_symbol */
2003  extended_remote_create_inferior,/* to_create_inferior */
2004  extended_remote_mourn,	/* to_mourn_inferior */
2005  0,				/* to_can_run */
2006  0,				/* to_notice_signals */
2007  remote_thread_alive,		/* to_thread_alive */
2008  0,				/* to_stop */
2009  process_stratum,		/* to_stratum */
2010  NULL,				/* to_next */
2011  1,				/* to_has_all_memory */
2012  1,				/* to_has_memory */
2013  1,				/* to_has_stack */
2014  1,				/* to_has_registers */
2015  1,				/* to_has_execution */
2016  NULL,				/* sections */
2017  NULL,				/* sections_end */
2018  OPS_MAGIC			/* to_magic */
2019};
2020
2021void
2022_initialize_remote ()
2023{
2024  add_target (&remote_ops);
2025  add_target (&extended_remote_ops);
2026
2027  add_show_from_set (add_set_cmd ("remotetimeout", no_class,
2028				  var_integer, (char *)&remote_timeout,
2029				  "Set timeout value for remote read.\n", &setlist),
2030		     &showlist);
2031
2032  add_show_from_set (add_set_cmd ("remotebreak", no_class,
2033				  var_integer, (char *)&remote_break,
2034				  "Set whether to send break if interrupted.\n", &setlist),
2035		     &showlist);
2036
2037#ifdef	REMOTE_CHAT
2038  add_show_from_set (add_set_cmd ("remotechat", no_class,
2039				  var_zinteger, (char *)&remote_chat,
2040				   "Set remote port interacts with target.\n", &setlist),
2041		     &showlist);
2042#endif	/* REMOTE_CHAT */
2043}
2044
2045