remote.c revision 19371
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/* These are the threads which we last sent to the remote system.  -1 for all
317   or -2 for not sent yet.  */
318int general_thread;
319int cont_thread;
320
321static void
322set_thread (th, gen)
323     int th;
324     int gen;
325{
326  char buf[PBUFSIZ];
327  int state = gen ? general_thread : cont_thread;
328  if (state == th)
329    return;
330  buf[0] = 'H';
331  buf[1] = gen ? 'g' : 'c';
332  if (th == 42000)
333    {
334      buf[2] = '0';
335      buf[3] = '\0';
336    }
337  else if (th < 0)
338    sprintf (&buf[2], "-%x", -th);
339  else
340    sprintf (&buf[2], "%x", th);
341  putpkt (buf);
342  getpkt (buf, 0);
343  if (gen)
344    general_thread = th;
345  else
346    cont_thread = th;
347}
348
349/*  Return nonzero if the thread TH is still alive on the remote system.  */
350
351static int
352remote_thread_alive (th)
353     int th;
354{
355  char buf[PBUFSIZ];
356
357  buf[0] = 'T';
358  if (th < 0)
359    sprintf (&buf[1], "-%x", -th);
360  else
361    sprintf (&buf[1], "%x", th);
362  putpkt (buf);
363  getpkt (buf, 0);
364  return (buf[0] == 'O' && buf[1] == 'K');
365}
366
367/*  Restart the remote side; this is an extended protocol operation.  */
368
369static void
370extended_remote_restart ()
371{
372  char buf[PBUFSIZ];
373
374  /* Send the restart command; for reasons I don't understand the
375     remote side really expects a number after the "R".  */
376  buf[0] = 'R';
377  sprintf (&buf[1], "%x", 0);
378  putpkt (buf);
379
380  /* Now query for status so this looks just like we restarted
381     gdbserver from scratch.  */
382  putpkt ("?");
383  getpkt (buf, 0);
384}
385
386/* Clean up connection to a remote debugger.  */
387
388/* ARGSUSED */
389static void
390remote_close (quitting)
391     int quitting;
392{
393  if (remote_desc)
394    SERIAL_CLOSE (remote_desc);
395  remote_desc = NULL;
396}
397
398/* Query the remote side for the text, data and bss offsets. */
399
400static void
401get_offsets ()
402{
403  char buf[PBUFSIZ];
404  int nvals;
405  CORE_ADDR text_addr, data_addr, bss_addr;
406  struct section_offsets *offs;
407
408  putpkt ("qOffsets");
409
410  getpkt (buf, 0);
411
412  if (buf[0] == '\000')
413    return;			/* Return silently.  Stub doesn't support this
414				   command. */
415  if (buf[0] == 'E')
416    {
417      warning ("Remote failure reply: %s", buf);
418      return;
419    }
420
421  nvals = sscanf (buf, "Text=%lx;Data=%lx;Bss=%lx", &text_addr, &data_addr,
422		  &bss_addr);
423  if (nvals != 3)
424    error ("Malformed response to offset query, %s", buf);
425
426  if (symfile_objfile == NULL)
427    return;
428
429  offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
430					    + symfile_objfile->num_sections
431					    * sizeof (offs->offsets));
432  memcpy (offs, symfile_objfile->section_offsets,
433	  sizeof (struct section_offsets)
434	  + symfile_objfile->num_sections
435	  * sizeof (offs->offsets));
436
437  ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
438
439  /* This is a temporary kludge to force data and bss to use the same offsets
440     because that's what nlmconv does now.  The real solution requires changes
441     to the stub and remote.c that I don't have time to do right now.  */
442
443  ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
444  ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
445
446  objfile_relocate (symfile_objfile, offs);
447}
448
449/* Stub for catch_errors.  */
450
451static int
452remote_start_remote (dummy)
453     char *dummy;
454{
455  immediate_quit = 1;		/* Allow user to interrupt it */
456
457  /* Ack any packet which the remote side has already sent.  */
458  SERIAL_WRITE (remote_desc, "+", 1);
459
460  /* Let the stub know that we want it to return the thread.  */
461  set_thread (-1, 0);
462
463  get_offsets ();		/* Get text, data & bss offsets */
464
465  putpkt ("?");			/* initiate a query from remote machine */
466  immediate_quit = 0;
467
468  start_remote ();		/* Initialize gdb process mechanisms */
469  return 1;
470}
471
472/* Open a connection to a remote debugger.
473   NAME is the filename used for communication.  */
474
475static void
476remote_open (name, from_tty)
477     char *name;
478     int from_tty;
479{
480  remote_open_1 (name, from_tty, &remote_ops);
481}
482
483/* Open a connection to a remote debugger using the extended
484   remote gdb protocol.  NAME is the filename used for communication.  */
485
486static void
487extended_remote_open (name, from_tty)
488     char *name;
489     int from_tty;
490{
491  char buf[PBUFSIZ];
492
493  /* Do the basic remote open stuff.  */
494  remote_open_1 (name, from_tty, &extended_remote_ops);
495
496  /* Now tell the remote that we're using the extended protocol.  */
497  putpkt ("!");
498  getpkt (buf, 0);
499
500}
501
502/* Generic code for opening a connection to a remote target.  */
503static DCACHE *remote_dcache;
504
505static void
506remote_open_1 (name, from_tty, target)
507     char *name;
508     int from_tty;
509     struct target_ops *target;
510{
511  if (name == 0)
512    error ("To open a remote debug connection, you need to specify what serial\n\
513device is attached to the remote system (e.g. /dev/ttya).");
514
515  target_preopen (from_tty);
516
517  unpush_target (target);
518
519  remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
520
521  remote_desc = SERIAL_OPEN (name);
522  if (!remote_desc)
523    perror_with_name (name);
524
525  if (baud_rate != -1)
526    {
527      if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
528	{
529	  SERIAL_CLOSE (remote_desc);
530	  perror_with_name (name);
531	}
532    }
533
534
535  SERIAL_RAW (remote_desc);
536
537  /* If there is something sitting in the buffer we might take it as a
538     response to a command, which would be bad.  */
539  SERIAL_FLUSH_INPUT (remote_desc);
540
541  if (from_tty)
542    {
543      puts_filtered ("Remote debugging using ");
544      puts_filtered (name);
545      puts_filtered ("\n");
546    }
547  push_target (target);	/* Switch to using remote target now */
548
549  /* Start out by trying the 'P' request to set registers.  We set this each
550     time that we open a new target so that if the user switches from one
551     stub to another, we can (if the target is closed and reopened) cope.  */
552  stub_supports_P = 1;
553
554  general_thread = -2;
555  cont_thread = -2;
556
557  /* Without this, some commands which require an active target (such as kill)
558     won't work.  This variable serves (at least) double duty as both the pid
559     of the target process (if it has such), and as a flag indicating that a
560     target is active.  These functions should be split out into seperate
561     variables, especially since GDB will someday have a notion of debugging
562     several processes.  */
563
564  inferior_pid = 42000;
565  /* Start the remote connection; if error (0), discard this target.
566     In particular, if the user quits, be sure to discard it
567     (we'd be in an inconsistent state otherwise).  */
568  if (!catch_errors (remote_start_remote, (char *)0,
569		     "Couldn't establish connection to remote target\n", RETURN_MASK_ALL))
570    pop_target();
571}
572
573/* This takes a program previously attached to and detaches it.  After
574   this is done, GDB can be used to debug some other program.  We
575   better not have left any breakpoints in the target program or it'll
576   die when it hits one.  */
577
578static void
579remote_detach (args, from_tty)
580     char *args;
581     int from_tty;
582{
583  char buf[PBUFSIZ];
584
585  if (args)
586    error ("Argument given to \"detach\" when remotely debugging.");
587
588  /* Tell the remote target to detach.  */
589  strcpy (buf, "D");
590  remote_send (buf);
591
592  pop_target ();
593  if (from_tty)
594    puts_filtered ("Ending remote debugging.\n");
595}
596
597/* Convert hex digit A to a number.  */
598
599static int
600fromhex (a)
601     int a;
602{
603  if (a >= '0' && a <= '9')
604    return a - '0';
605  else if (a >= 'a' && a <= 'f')
606    return a - 'a' + 10;
607  else
608    error ("Reply contains invalid hex digit %d", a);
609}
610
611/* Convert number NIB to a hex digit.  */
612
613static int
614tohex (nib)
615     int nib;
616{
617  if (nib < 10)
618    return '0'+nib;
619  else
620    return 'a'+nib-10;
621}
622
623/* Tell the remote machine to resume.  */
624
625static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
626int last_sent_step;
627
628static void
629remote_resume (pid, step, siggnal)
630     int pid, step;
631     enum target_signal siggnal;
632{
633  char buf[PBUFSIZ];
634
635  if (pid == -1)
636    set_thread (inferior_pid, 0);
637  else
638    set_thread (pid, 0);
639
640  dcache_flush (remote_dcache);
641
642  last_sent_signal = siggnal;
643  last_sent_step = step;
644
645  if (siggnal != TARGET_SIGNAL_0)
646    {
647      buf[0] = step ? 'S' : 'C';
648      buf[1] = tohex (((int)siggnal >> 4) & 0xf);
649      buf[2] = tohex ((int)siggnal & 0xf);
650      buf[3] = '\0';
651    }
652  else
653    strcpy (buf, step ? "s": "c");
654
655  putpkt (buf);
656}
657
658/* Send ^C to target to halt it.  Target will respond, and send us a
659   packet.  */
660
661static void
662remote_interrupt (signo)
663     int signo;
664{
665  /* If this doesn't work, try more severe steps.  */
666  signal (signo, remote_interrupt_twice);
667
668  if (remote_debug)
669    printf_unfiltered ("remote_interrupt called\n");
670
671  /* Send a break or a ^C, depending on user preference.  */
672  if (remote_break)
673    SERIAL_SEND_BREAK (remote_desc);
674  else
675    SERIAL_WRITE (remote_desc, "\003", 1);
676}
677
678static void (*ofunc)();
679
680/* The user typed ^C twice.  */
681static void
682remote_interrupt_twice (signo)
683     int signo;
684{
685  signal (signo, ofunc);
686
687  interrupt_query ();
688
689  signal (signo, remote_interrupt);
690}
691
692/* Ask the user what to do when an interrupt is received.  */
693
694static void
695interrupt_query ()
696{
697  target_terminal_ours ();
698
699  if (query ("Interrupted while waiting for the program.\n\
700Give up (and stop debugging it)? "))
701    {
702      target_mourn_inferior ();
703      return_to_top_level (RETURN_QUIT);
704    }
705
706  target_terminal_inferior ();
707}
708
709/* If nonzero, ignore the next kill.  */
710int kill_kludge;
711
712/* Wait until the remote machine stops, then return,
713   storing status in STATUS just as `wait' would.
714   Returns "pid" (though it's not clear what, if anything, that
715   means in the case of this target).  */
716
717static int
718remote_wait (pid, status)
719     int pid;
720     struct target_waitstatus *status;
721{
722  unsigned char buf[PBUFSIZ];
723  int thread_num = -1;
724
725  status->kind = TARGET_WAITKIND_EXITED;
726  status->value.integer = 0;
727
728  while (1)
729    {
730      unsigned char *p;
731
732      ofunc = (void (*)()) signal (SIGINT, remote_interrupt);
733      getpkt ((char *) buf, 1);
734      signal (SIGINT, ofunc);
735
736      switch (buf[0])
737	{
738	case 'E':		/* Error of some sort */
739	  warning ("Remote failure reply: %s", buf);
740	  continue;
741	case 'T':		/* Status with PC, SP, FP, ... */
742	  {
743	    int i;
744	    long regno;
745	    char regs[MAX_REGISTER_RAW_SIZE];
746
747	    /* Expedited reply, containing Signal, {regno, reg} repeat */
748	    /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
749		ss = signal number
750		n... = register number
751		r... = register contents
752		*/
753
754	    p = &buf[3];	/* after Txx */
755
756	    while (*p)
757	      {
758		unsigned char *p1;
759		char *p_temp;
760
761		regno = strtol ((const char *) p, &p_temp, 16); /* Read the register number */
762		p1 = (unsigned char *)p_temp;
763
764		if (p1 == p)
765		  {
766		    p1 = (unsigned char *) strchr ((const char *) p, ':');
767		    if (p1 == NULL)
768		      warning ("Malformed packet (missing colon): %s\n\
769Packet: '%s'\n",
770			       p, buf);
771		    if (strncmp ((const char *) p, "thread", p1 - p) == 0)
772		      {
773			thread_num = strtol ((const char *) ++p1, &p_temp, 16);
774			p = (unsigned char *)p_temp;
775		      }
776		  }
777		else
778		  {
779		    p = p1;
780
781		    if (*p++ != ':')
782		      warning ("Malformed packet (missing colon): %s\n\
783Packet: '%s'\n",
784			       p, buf);
785
786		    if (regno >= NUM_REGS)
787		      warning ("Remote sent bad register number %ld: %s\n\
788Packet: '%s'\n",
789			       regno, p, buf);
790
791		    for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
792		      {
793			if (p[0] == 0 || p[1] == 0)
794			  warning ("Remote reply is too short: %s", buf);
795			regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
796			p += 2;
797		      }
798		    supply_register (regno, regs);
799		  }
800
801		if (*p++ != ';')
802		  warning ("Remote register badly formatted: %s", buf);
803	      }
804	  }
805	  /* fall through */
806	case 'S':		/* Old style status, just signal only */
807	  status->kind = TARGET_WAITKIND_STOPPED;
808	  status->value.sig = (enum target_signal)
809	    (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
810
811	  goto got_status;
812	case 'W':		/* Target exited */
813	  {
814	    /* The remote process exited.  */
815	    status->kind = TARGET_WAITKIND_EXITED;
816	    status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
817	    goto got_status;
818	  }
819	case 'X':
820	  status->kind = TARGET_WAITKIND_SIGNALLED;
821	  status->value.sig = (enum target_signal)
822	    (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
823	  kill_kludge = 1;
824
825	  goto got_status;
826	case 'O':		/* Console output */
827 	  for (p = buf + 1; *p; p +=2)
828 	    {
829 	      char tb[2];
830 	      char c = fromhex (p[0]) * 16 + fromhex (p[1]);
831 	      tb[0] = c;
832 	      tb[1] = 0;
833 	      if (target_output_hook)
834 		target_output_hook (tb);
835 	      else
836 		fputs_filtered (tb, gdb_stdout);
837 	    }
838	  continue;
839	case '\0':
840	  if (last_sent_signal != TARGET_SIGNAL_0)
841	    {
842	      /* Zero length reply means that we tried 'S' or 'C' and
843		 the remote system doesn't support it.  */
844	      target_terminal_ours_for_output ();
845	      printf_filtered
846		("Can't send signals to this remote system.  %s not sent.\n",
847		 target_signal_to_name (last_sent_signal));
848	      last_sent_signal = TARGET_SIGNAL_0;
849	      target_terminal_inferior ();
850
851	      strcpy ((char *) buf, last_sent_step ? "s" : "c");
852	      putpkt ((char *) buf);
853	      continue;
854	    }
855	  /* else fallthrough */
856	default:
857	  warning ("Invalid remote reply: %s", buf);
858	  continue;
859	}
860    }
861 got_status:
862  if (thread_num != -1)
863    {
864      /* Initial thread value can only be acquired via wait, so deal with
865	 this marker which is used before the first thread value is
866	 acquired.  */
867      if (inferior_pid == 42000)
868	{
869	  inferior_pid = thread_num;
870	  add_thread (inferior_pid);
871	}
872      return thread_num;
873    }
874  return inferior_pid;
875}
876
877/* Number of bytes of registers this stub implements.  */
878static int register_bytes_found;
879
880/* Read the remote registers into the block REGS.  */
881/* Currently we just read all the registers, so we don't use regno.  */
882/* ARGSUSED */
883static void
884remote_fetch_registers (regno)
885     int regno;
886{
887  char buf[PBUFSIZ];
888  int i;
889  char *p;
890  char regs[REGISTER_BYTES];
891
892  set_thread (inferior_pid, 1);
893
894  sprintf (buf, "g");
895  remote_send (buf);
896
897  /* Unimplemented registers read as all bits zero.  */
898  memset (regs, 0, REGISTER_BYTES);
899
900  /* We can get out of synch in various cases.  If the first character
901     in the buffer is not a hex character, assume that has happened
902     and try to fetch another packet to read.  */
903  while ((buf[0] < '0' || buf[0] > '9')
904	 && (buf[0] < 'a' || buf[0] > 'f'))
905    {
906      if (remote_debug)
907	printf_unfiltered ("Bad register packet; fetching a new packet\n");
908      getpkt (buf, 0);
909    }
910
911  /* Reply describes registers byte by byte, each byte encoded as two
912     hex characters.  Suck them all up, then supply them to the
913     register cacheing/storage mechanism.  */
914
915  p = buf;
916  for (i = 0; i < REGISTER_BYTES; i++)
917    {
918      if (p[0] == 0)
919	break;
920      if (p[1] == 0)
921	{
922	  warning ("Remote reply is of odd length: %s", buf);
923	  /* Don't change register_bytes_found in this case, and don't
924	     print a second warning.  */
925	  goto supply_them;
926	}
927      regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
928      p += 2;
929    }
930
931  if (i != register_bytes_found)
932    {
933      register_bytes_found = i;
934#ifdef REGISTER_BYTES_OK
935      if (!REGISTER_BYTES_OK (i))
936	warning ("Remote reply is too short: %s", buf);
937#endif
938    }
939
940 supply_them:
941  for (i = 0; i < NUM_REGS; i++)
942    supply_register (i, &regs[REGISTER_BYTE(i)]);
943}
944
945/* Prepare to store registers.  Since we may send them all (using a
946   'G' request), we have to read out the ones we don't want to change
947   first.  */
948
949static void
950remote_prepare_to_store ()
951{
952  /* Make sure the entire registers array is valid.  */
953  read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
954}
955
956/* Store register REGNO, or all registers if REGNO == -1, from the contents
957   of REGISTERS.  FIXME: ignores errors.  */
958
959static void
960remote_store_registers (regno)
961     int regno;
962{
963  char buf[PBUFSIZ];
964  int i;
965  char *p;
966
967  set_thread (inferior_pid, 1);
968
969  if (regno >= 0 && stub_supports_P)
970    {
971      /* Try storing a single register.  */
972      char *regp;
973
974      sprintf (buf, "P%x=", regno);
975      p = buf + strlen (buf);
976      regp = &registers[REGISTER_BYTE (regno)];
977      for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
978	{
979	  *p++ = tohex ((regp[i] >> 4) & 0xf);
980	  *p++ = tohex (regp[i] & 0xf);
981	}
982      *p = '\0';
983      remote_send (buf);
984      if (buf[0] != '\0')
985	{
986	  /* The stub understands the 'P' request.  We are done.  */
987	  return;
988	}
989
990      /* The stub does not support the 'P' request.  Use 'G' instead,
991	 and don't try using 'P' in the future (it will just waste our
992	 time).  */
993      stub_supports_P = 0;
994    }
995
996  buf[0] = 'G';
997
998  /* Command describes registers byte by byte,
999     each byte encoded as two hex characters.  */
1000
1001  p = buf + 1;
1002  /* remote_prepare_to_store insures that register_bytes_found gets set.  */
1003  for (i = 0; i < register_bytes_found; i++)
1004    {
1005      *p++ = tohex ((registers[i] >> 4) & 0xf);
1006      *p++ = tohex (registers[i] & 0xf);
1007    }
1008  *p = '\0';
1009
1010  remote_send (buf);
1011}
1012
1013/*
1014   Use of the data cache *used* to be disabled because it loses for looking at
1015   and changing hardware I/O ports and the like.  Accepting `volatile'
1016   would perhaps be one way to fix it.  Another idea would be to use the
1017   executable file for the text segment (for all SEC_CODE sections?
1018   For all SEC_READONLY sections?).  This has problems if you want to
1019   actually see what the memory contains (e.g. self-modifying code,
1020   clobbered memory, user downloaded the wrong thing).
1021
1022   Because it speeds so much up, it's now enabled, if you're playing
1023   with registers you turn it of (set remotecache 0)
1024*/
1025
1026/* Read a word from remote address ADDR and return it.
1027   This goes through the data cache.  */
1028
1029#if 0	/* unused? */
1030static int
1031remote_fetch_word (addr)
1032     CORE_ADDR addr;
1033{
1034  return dcache_fetch (remote_dcache, addr);
1035}
1036
1037/* Write a word WORD into remote address ADDR.
1038   This goes through the data cache.  */
1039
1040static void
1041remote_store_word (addr, word)
1042     CORE_ADDR addr;
1043     int word;
1044{
1045  dcache_poke (remote_dcache, addr, word);
1046}
1047#endif	/* 0 (unused?) */
1048
1049
1050/* Write memory data directly to the remote machine.
1051   This does not inform the data cache; the data cache uses this.
1052   MEMADDR is the address in the remote memory space.
1053   MYADDR is the address of the buffer in our space.
1054   LEN is the number of bytes.
1055
1056   Returns number of bytes transferred, or 0 for error.  */
1057
1058static int
1059remote_write_bytes (memaddr, myaddr, len)
1060     CORE_ADDR memaddr;
1061     char *myaddr;
1062     int len;
1063{
1064  char buf[PBUFSIZ];
1065  int i;
1066  char *p;
1067  int done;
1068  /* Chop the transfer down if necessary */
1069
1070  done = 0;
1071  while (done < len)
1072    {
1073      int todo = len - done;
1074      int cando = PBUFSIZ /2 - 32; /* number of bytes that will fit. */
1075      if (todo > cando)
1076	todo = cando;
1077
1078      /* FIXME-32x64: Need a version of print_address_numeric which puts the
1079	 result in a buffer like sprintf.  */
1080      sprintf (buf, "M%lx,%x:", (unsigned long) memaddr + done, todo);
1081
1082      /* We send target system values byte by byte, in increasing byte addresses,
1083	 each byte encoded as two hex characters.  */
1084
1085      p = buf + strlen (buf);
1086      for (i = 0; i < todo; i++)
1087	{
1088	  *p++ = tohex ((myaddr[i + done] >> 4) & 0xf);
1089	  *p++ = tohex (myaddr[i + done] & 0xf);
1090	}
1091      *p = '\0';
1092
1093      putpkt (buf);
1094      getpkt (buf, 0);
1095
1096      if (buf[0] == 'E')
1097	{
1098	  /* There is no correspondance between what the remote protocol uses
1099	     for errors and errno codes.  We would like a cleaner way of
1100	     representing errors (big enough to include errno codes, bfd_error
1101	     codes, and others).  But for now just return EIO.  */
1102	  errno = EIO;
1103	  return 0;
1104	}
1105      done += todo;
1106    }
1107  return len;
1108}
1109
1110/* Read memory data directly from the remote machine.
1111   This does not use the data cache; the data cache uses this.
1112   MEMADDR is the address in the remote memory space.
1113   MYADDR is the address of the buffer in our space.
1114   LEN is the number of bytes.
1115
1116   Returns number of bytes transferred, or 0 for error.  */
1117
1118static int
1119remote_read_bytes (memaddr, myaddr, len)
1120     CORE_ADDR memaddr;
1121     char *myaddr;
1122     int len;
1123{
1124  char buf[PBUFSIZ];
1125  int i;
1126  char *p;
1127  int done;
1128  /* Chop transfer down if neccessary */
1129
1130#if 0
1131  /* FIXME: This is wrong for larger packets */
1132  if (len > PBUFSIZ / 2 - 1)
1133    abort ();
1134#endif
1135  done = 0;
1136  while (done < len)
1137    {
1138      int todo = len - done;
1139      int cando = PBUFSIZ / 2 - 32; /* number of bytes that will fit. */
1140      if (todo > cando)
1141	todo = cando;
1142
1143      /* FIXME-32x64: Need a version of print_address_numeric which puts the
1144	 result in a buffer like sprintf.  */
1145      sprintf (buf, "m%lx,%x", (unsigned long) memaddr + done, todo);
1146      putpkt (buf);
1147      getpkt (buf, 0);
1148
1149      if (buf[0] == 'E')
1150	{
1151	  /* There is no correspondance between what the remote protocol uses
1152	     for errors and errno codes.  We would like a cleaner way of
1153	     representing errors (big enough to include errno codes, bfd_error
1154	     codes, and others).  But for now just return EIO.  */
1155	  errno = EIO;
1156	  return 0;
1157	}
1158
1159  /* Reply describes memory byte by byte,
1160     each byte encoded as two hex characters.  */
1161
1162      p = buf;
1163      for (i = 0; i < todo; i++)
1164	{
1165	  if (p[0] == 0 || p[1] == 0)
1166	    /* Reply is short.  This means that we were able to read only part
1167	       of what we wanted to.  */
1168	    return i + done;
1169	  myaddr[i + done] = fromhex (p[0]) * 16 + fromhex (p[1]);
1170	  p += 2;
1171	}
1172      done += todo;
1173    }
1174  return len;
1175}
1176
1177/* Read or write LEN bytes from inferior memory at MEMADDR, transferring
1178   to or from debugger address MYADDR.  Write to inferior if SHOULD_WRITE is
1179   nonzero.  Returns length of data written or read; 0 for error.  */
1180
1181/* ARGSUSED */
1182static int
1183remote_xfer_memory(memaddr, myaddr, len, should_write, target)
1184     CORE_ADDR memaddr;
1185     char *myaddr;
1186     int len;
1187     int should_write;
1188     struct target_ops *target;			/* ignored */
1189{
1190  return dcache_xfer_memory (remote_dcache, memaddr, myaddr, len, should_write);
1191}
1192
1193
1194#if 0
1195/* Enable after 4.12.  */
1196
1197void
1198remote_search (len, data, mask, startaddr, increment, lorange, hirange
1199	       addr_found, data_found)
1200     int len;
1201     char *data;
1202     char *mask;
1203     CORE_ADDR startaddr;
1204     int increment;
1205     CORE_ADDR lorange;
1206     CORE_ADDR hirange;
1207     CORE_ADDR *addr_found;
1208     char *data_found;
1209{
1210  if (increment == -4 && len == 4)
1211    {
1212      long mask_long, data_long;
1213      long data_found_long;
1214      CORE_ADDR addr_we_found;
1215      char buf[PBUFSIZ];
1216      long returned_long[2];
1217      char *p;
1218
1219      mask_long = extract_unsigned_integer (mask, len);
1220      data_long = extract_unsigned_integer (data, len);
1221      sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
1222      putpkt (buf);
1223      getpkt (buf, 0);
1224      if (buf[0] == '\0')
1225	{
1226	  /* The stub doesn't support the 't' request.  We might want to
1227	     remember this fact, but on the other hand the stub could be
1228	     switched on us.  Maybe we should remember it only until
1229	     the next "target remote".  */
1230	  generic_search (len, data, mask, startaddr, increment, lorange,
1231			  hirange, addr_found, data_found);
1232	  return;
1233	}
1234
1235      if (buf[0] == 'E')
1236	/* There is no correspondance between what the remote protocol uses
1237	   for errors and errno codes.  We would like a cleaner way of
1238	   representing errors (big enough to include errno codes, bfd_error
1239	   codes, and others).  But for now just use EIO.  */
1240	memory_error (EIO, startaddr);
1241      p = buf;
1242      addr_we_found = 0;
1243      while (*p != '\0' && *p != ',')
1244	addr_we_found = (addr_we_found << 4) + fromhex (*p++);
1245      if (*p == '\0')
1246	error ("Protocol error: short return for search");
1247
1248      data_found_long = 0;
1249      while (*p != '\0' && *p != ',')
1250	data_found_long = (data_found_long << 4) + fromhex (*p++);
1251      /* Ignore anything after this comma, for future extensions.  */
1252
1253      if (addr_we_found < lorange || addr_we_found >= hirange)
1254	{
1255	  *addr_found = 0;
1256	  return;
1257	}
1258
1259      *addr_found = addr_we_found;
1260      *data_found = store_unsigned_integer (data_we_found, len);
1261      return;
1262    }
1263  generic_search (len, data, mask, startaddr, increment, lorange,
1264		  hirange, addr_found, data_found);
1265}
1266#endif /* 0 */
1267
1268static void
1269remote_files_info (ignore)
1270     struct target_ops *ignore;
1271{
1272  puts_filtered ("Debugging a target over a serial line.\n");
1273}
1274
1275/* Stuff for dealing with the packets which are part of this protocol.
1276   See comment at top of file for details.  */
1277
1278/* Read a single character from the remote end, masking it down to 7 bits. */
1279
1280static int
1281readchar (timeout)
1282     int timeout;
1283{
1284  int ch;
1285
1286  ch = SERIAL_READCHAR (remote_desc, timeout);
1287
1288  switch (ch)
1289    {
1290    case SERIAL_EOF:
1291      error ("Remote connection closed");
1292    case SERIAL_ERROR:
1293      perror_with_name ("Remote communication error");
1294    case SERIAL_TIMEOUT:
1295      return ch;
1296    default:
1297      return ch & 0x7f;
1298    }
1299}
1300
1301/* Send the command in BUF to the remote machine,
1302   and read the reply into BUF.
1303   Report an error if we get an error reply.  */
1304
1305static void
1306remote_send (buf)
1307     char *buf;
1308{
1309  putpkt (buf);
1310  getpkt (buf, 0);
1311
1312  if (buf[0] == 'E')
1313    error ("Remote failure reply: %s", buf);
1314}
1315
1316/* Send a packet to the remote machine, with error checking.
1317   The data of the packet is in BUF.  */
1318
1319static int
1320putpkt (buf)
1321     char *buf;
1322{
1323  int i;
1324  unsigned char csum = 0;
1325  char buf2[PBUFSIZ];
1326  int cnt = strlen (buf);
1327  int ch;
1328  int tcount = 0;
1329  char *p;
1330
1331  /* Copy the packet into buffer BUF2, encapsulating it
1332     and giving it a checksum.  */
1333
1334  if (cnt > (int) sizeof (buf2) - 5)		/* Prosanity check */
1335    abort();
1336
1337  p = buf2;
1338  *p++ = '$';
1339
1340  for (i = 0; i < cnt; i++)
1341    {
1342      csum += buf[i];
1343      *p++ = buf[i];
1344    }
1345  *p++ = '#';
1346  *p++ = tohex ((csum >> 4) & 0xf);
1347  *p++ = tohex (csum & 0xf);
1348
1349  /* Send it over and over until we get a positive ack.  */
1350
1351  while (1)
1352    {
1353      int started_error_output = 0;
1354
1355      if (remote_debug)
1356	{
1357	  *p = '\0';
1358	  printf_unfiltered ("Sending packet: %s...", buf2);
1359	  gdb_flush(gdb_stdout);
1360	}
1361      if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
1362	perror_with_name ("putpkt: write failed");
1363
1364      /* read until either a timeout occurs (-2) or '+' is read */
1365      while (1)
1366	{
1367	  ch = readchar (remote_timeout);
1368
1369 	  if (remote_debug)
1370	    {
1371	      switch (ch)
1372		{
1373		case '+':
1374		case SERIAL_TIMEOUT:
1375		case '$':
1376		  if (started_error_output)
1377		    {
1378		      putchar_unfiltered ('\n');
1379		      started_error_output = 0;
1380		    }
1381		}
1382	    }
1383
1384	  switch (ch)
1385	    {
1386	    case '+':
1387	      if (remote_debug)
1388		printf_unfiltered("Ack\n");
1389	      return 1;
1390	    case SERIAL_TIMEOUT:
1391	      tcount ++;
1392	      if (tcount > 3)
1393		return 0;
1394	      break;		/* Retransmit buffer */
1395	    case '$':
1396	      {
1397		char junkbuf[PBUFSIZ];
1398
1399	      /* It's probably an old response, and we're out of sync.  Just
1400		 gobble up the packet and ignore it.  */
1401		getpkt (junkbuf, 0);
1402		continue;		/* Now, go look for + */
1403	      }
1404	    default:
1405	      if (remote_debug)
1406		{
1407		  if (!started_error_output)
1408		    {
1409		      started_error_output = 1;
1410		      printf_unfiltered ("putpkt: Junk: ");
1411		    }
1412		  putchar_unfiltered (ch & 0177);
1413		}
1414	      continue;
1415	    }
1416	  break;		/* Here to retransmit */
1417	}
1418
1419#if 0
1420      /* This is wrong.  If doing a long backtrace, the user should be
1421	 able to get out next time we call QUIT, without anything as violent
1422	 as interrupt_query.  If we want to provide a way out of here
1423	 without getting to the next QUIT, it should be based on hitting
1424	 ^C twice as in remote_wait.  */
1425      if (quit_flag)
1426	{
1427	  quit_flag = 0;
1428	  interrupt_query ();
1429	}
1430#endif
1431    }
1432}
1433
1434/* Come here after finding the start of the frame.  Collect the rest into BUF,
1435   verifying the checksum, length, and handling run-length compression.
1436   Returns 0 on any error, 1 on success.  */
1437
1438static int
1439read_frame (buf)
1440     char *buf;
1441{
1442  unsigned char csum;
1443  char *bp;
1444  int c;
1445
1446  csum = 0;
1447  bp = buf;
1448
1449  while (1)
1450    {
1451      c = readchar (remote_timeout);
1452
1453      switch (c)
1454	{
1455	case SERIAL_TIMEOUT:
1456	  if (remote_debug)
1457	    puts_filtered ("Timeout in mid-packet, retrying\n");
1458	  return 0;
1459	case '$':
1460	  if (remote_debug)
1461	    puts_filtered ("Saw new packet start in middle of old one\n");
1462	  return 0;		/* Start a new packet, count retries */
1463	case '#':
1464	  {
1465	    unsigned char pktcsum;
1466
1467	    *bp = '\000';
1468
1469	    pktcsum = fromhex (readchar (remote_timeout)) << 4;
1470	    pktcsum |= fromhex (readchar (remote_timeout));
1471
1472	    if (csum == pktcsum)
1473	      return 1;
1474
1475	    if (remote_debug)
1476	      {
1477		printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
1478				 pktcsum, csum);
1479		puts_filtered (buf);
1480		puts_filtered ("\n");
1481	      }
1482	    return 0;
1483	  }
1484	case '*':		/* Run length encoding */
1485	  csum += c;
1486	  c = readchar (remote_timeout);
1487	  csum += c;
1488	  c = c - ' ' + 3;	/* Compute repeat count */
1489
1490
1491	  if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
1492	    {
1493	      memset (bp, *(bp - 1), c);
1494	      bp += c;
1495	      continue;
1496	    }
1497
1498	  *bp = '\0';
1499	  printf_filtered ("Repeat count %d too large for buffer: ", c);
1500	  puts_filtered (buf);
1501	  puts_filtered ("\n");
1502	  return 0;
1503
1504	default:
1505	  if (bp < buf + PBUFSIZ - 1)
1506	    {
1507	      *bp++ = c;
1508	      csum += c;
1509	      continue;
1510	    }
1511
1512	  *bp = '\0';
1513	  puts_filtered ("Remote packet too long: ");
1514	  puts_filtered (buf);
1515	  puts_filtered ("\n");
1516
1517	  return 0;
1518	}
1519    }
1520}
1521
1522/* Read a packet from the remote machine, with error checking,
1523   and store it in BUF.  BUF is expected to be of size PBUFSIZ.
1524   If FOREVER, wait forever rather than timing out; this is used
1525   while the target is executing user code.  */
1526
1527static void
1528getpkt (buf, forever)
1529     char *buf;
1530     int forever;
1531{
1532  int c;
1533  int tries;
1534  int timeout;
1535  int val;
1536
1537  strcpy (buf,"timeout");
1538
1539  if (forever)
1540    {
1541#ifdef MAINTENANCE_CMDS
1542      timeout = watchdog > 0 ? watchdog : -1;
1543#else
1544      timeout = -1;
1545#endif
1546    }
1547
1548  else
1549    timeout = remote_timeout;
1550
1551#define MAX_TRIES 3
1552
1553  for (tries = 1; tries <= MAX_TRIES; tries++)
1554    {
1555      /* This can loop forever if the remote side sends us characters
1556	 continuously, but if it pauses, we'll get a zero from readchar
1557	 because of timeout.  Then we'll count that as a retry.  */
1558
1559      /* Note that we will only wait forever prior to the start of a packet.
1560	 After that, we expect characters to arrive at a brisk pace.  They
1561	 should show up within remote_timeout intervals.  */
1562
1563      do
1564	{
1565	  c = readchar (timeout);
1566
1567	  if (c == SERIAL_TIMEOUT)
1568	    {
1569#ifdef MAINTENANCE_CMDS
1570	      if (forever)	/* Watchdog went off.  Kill the target. */
1571		{
1572		  target_mourn_inferior ();
1573		  error ("Watchdog has expired.  Target detached.\n");
1574		}
1575#endif
1576	      if (remote_debug)
1577		puts_filtered ("Timed out.\n");
1578	      goto retry;
1579	    }
1580	}
1581      while (c != '$');
1582
1583      /* We've found the start of a packet, now collect the data.  */
1584
1585      val = read_frame (buf);
1586
1587      if (val == 1)
1588	{
1589	  if (remote_debug)
1590	    fprintf_unfiltered (gdb_stderr, "Packet received: %s\n", buf);
1591	  SERIAL_WRITE (remote_desc, "+", 1);
1592	  return;
1593	}
1594
1595      /* Try the whole thing again.  */
1596    retry:
1597      SERIAL_WRITE (remote_desc, "-", 1);
1598    }
1599
1600  /* We have tried hard enough, and just can't receive the packet.  Give up. */
1601
1602  printf_unfiltered ("Ignoring packet error, continuing...\n");
1603  SERIAL_WRITE (remote_desc, "+", 1);
1604}
1605
1606static void
1607remote_kill ()
1608{
1609  /* For some mysterious reason, wait_for_inferior calls kill instead of
1610     mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
1611  if (kill_kludge)
1612    {
1613      kill_kludge = 0;
1614      target_mourn_inferior ();
1615      return;
1616    }
1617
1618  /* Use catch_errors so the user can quit from gdb even when we aren't on
1619     speaking terms with the remote system.  */
1620  catch_errors (putpkt, "k", "", RETURN_MASK_ERROR);
1621
1622  /* Don't wait for it to die.  I'm not really sure it matters whether
1623     we do or not.  For the existing stubs, kill is a noop.  */
1624  target_mourn_inferior ();
1625}
1626
1627static void
1628remote_mourn ()
1629{
1630  remote_mourn_1 (&remote_ops);
1631}
1632
1633static void
1634extended_remote_mourn ()
1635{
1636  /* We do _not_ want to mourn the target like this; this will
1637     remove the extended remote target  from the target stack,
1638     and the next time the user says "run" it'll fail.
1639
1640     FIXME: What is the right thing to do here?  */
1641#if 0
1642  remote_mourn_1 (&extended_remote_ops);
1643#endif
1644}
1645
1646/* Worker function for remote_mourn.  */
1647static void
1648remote_mourn_1 (target)
1649     struct target_ops *target;
1650{
1651  unpush_target (target);
1652  generic_mourn_inferior ();
1653}
1654
1655/* In the extended protocol we want to be able to do things like
1656   "run" and have them basically work as expected.  So we need
1657   a special create_inferior function.
1658
1659   FIXME: One day add support for changing the exec file
1660   we're debugging, arguments and an environment.  */
1661
1662static void
1663extended_remote_create_inferior (exec_file, args, env)
1664     char *exec_file;
1665     char *args;
1666     char **env;
1667{
1668  /* Rip out the breakpoints; we'll reinsert them after restarting
1669     the remote server.  */
1670  remove_breakpoints ();
1671
1672  /* Now restart the remote server.  */
1673  extended_remote_restart ();
1674
1675  /* Now put the breakpoints back in.  This way we're safe if the
1676     restart function works via a unix fork on the remote side.  */
1677  insert_breakpoints ();
1678
1679  /* Clean up from the last time we were running.  */
1680  clear_proceed_status ();
1681
1682  /* Let the remote process run.  */
1683  proceed (-1, TARGET_SIGNAL_0, 0);
1684}
1685
1686
1687#ifdef REMOTE_BREAKPOINT
1688
1689/* On some machines, e.g. 68k, we may use a different breakpoint instruction
1690   than other targets.  */
1691static unsigned char break_insn[] = REMOTE_BREAKPOINT;
1692
1693#else /* No REMOTE_BREAKPOINT.  */
1694
1695/* Same old breakpoint instruction.  This code does nothing different
1696   than mem-break.c.  */
1697static unsigned char break_insn[] = BREAKPOINT;
1698
1699#endif /* No REMOTE_BREAKPOINT.  */
1700
1701/* Insert a breakpoint on targets that don't have any better breakpoint
1702   support.  We read the contents of the target location and stash it,
1703   then overwrite it with a breakpoint instruction.  ADDR is the target
1704   location in the target machine.  CONTENTS_CACHE is a pointer to
1705   memory allocated for saving the target contents.  It is guaranteed
1706   by the caller to be long enough to save sizeof BREAKPOINT bytes (this
1707   is accomplished via BREAKPOINT_MAX).  */
1708
1709static int
1710remote_insert_breakpoint (addr, contents_cache)
1711     CORE_ADDR addr;
1712     char *contents_cache;
1713{
1714  int val;
1715
1716  val = target_read_memory (addr, contents_cache, sizeof break_insn);
1717
1718  if (val == 0)
1719    val = target_write_memory (addr, (char *)break_insn, sizeof break_insn);
1720
1721  return val;
1722}
1723
1724static int
1725remote_remove_breakpoint (addr, contents_cache)
1726     CORE_ADDR addr;
1727     char *contents_cache;
1728{
1729  return target_write_memory (addr, contents_cache, sizeof break_insn);
1730}
1731
1732/* Define the target subroutine names */
1733
1734struct target_ops remote_ops = {
1735  "remote",			/* to_shortname */
1736  "Remote serial target in gdb-specific protocol",	/* to_longname */
1737  "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
1738Specify the serial device it is connected to (e.g. /dev/ttya).",  /* to_doc */
1739  remote_open,			/* to_open */
1740  remote_close,			/* to_close */
1741  NULL,				/* to_attach */
1742  remote_detach,		/* to_detach */
1743  remote_resume,		/* to_resume */
1744  remote_wait,			/* to_wait */
1745  remote_fetch_registers,	/* to_fetch_registers */
1746  remote_store_registers,	/* to_store_registers */
1747  remote_prepare_to_store,	/* to_prepare_to_store */
1748  remote_xfer_memory,		/* to_xfer_memory */
1749  remote_files_info,		/* to_files_info */
1750  remote_insert_breakpoint,	/* to_insert_breakpoint */
1751  remote_remove_breakpoint,	/* to_remove_breakpoint */
1752  NULL,				/* to_terminal_init */
1753  NULL,				/* to_terminal_inferior */
1754  NULL,				/* to_terminal_ours_for_output */
1755  NULL,				/* to_terminal_ours */
1756  NULL,				/* to_terminal_info */
1757  remote_kill,			/* to_kill */
1758  generic_load,			/* to_load */
1759  NULL,				/* to_lookup_symbol */
1760  NULL,				/* to_create_inferior */
1761  remote_mourn,			/* to_mourn_inferior */
1762  0,				/* to_can_run */
1763  0,				/* to_notice_signals */
1764  remote_thread_alive,		/* to_thread_alive */
1765  0,				/* to_stop */
1766  process_stratum,		/* to_stratum */
1767  NULL,				/* to_next */
1768  1,				/* to_has_all_memory */
1769  1,				/* to_has_memory */
1770  1,				/* to_has_stack */
1771  1,				/* to_has_registers */
1772  1,				/* to_has_execution */
1773  NULL,				/* sections */
1774  NULL,				/* sections_end */
1775  OPS_MAGIC			/* to_magic */
1776};
1777
1778struct target_ops extended_remote_ops = {
1779  "extended-remote",			/* to_shortname */
1780  "Extended remote serial target in gdb-specific protocol",/* to_longname */
1781  "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
1782Specify the serial device it is connected to (e.g. /dev/ttya).",  /* to_doc */
1783  extended_remote_open,			/* to_open */
1784  remote_close,			/* to_close */
1785  NULL,				/* to_attach */
1786  remote_detach,		/* to_detach */
1787  remote_resume,		/* to_resume */
1788  remote_wait,			/* to_wait */
1789  remote_fetch_registers,	/* to_fetch_registers */
1790  remote_store_registers,	/* to_store_registers */
1791  remote_prepare_to_store,	/* to_prepare_to_store */
1792  remote_xfer_memory,		/* to_xfer_memory */
1793  remote_files_info,		/* to_files_info */
1794
1795  remote_insert_breakpoint,	/* to_insert_breakpoint */
1796  remote_remove_breakpoint,	/* to_remove_breakpoint */
1797
1798  NULL,				/* to_terminal_init */
1799  NULL,				/* to_terminal_inferior */
1800  NULL,				/* to_terminal_ours_for_output */
1801  NULL,				/* to_terminal_ours */
1802  NULL,				/* to_terminal_info */
1803  remote_kill,			/* to_kill */
1804  generic_load,			/* to_load */
1805  NULL,				/* to_lookup_symbol */
1806  extended_remote_create_inferior,/* to_create_inferior */
1807  extended_remote_mourn,	/* to_mourn_inferior */
1808  0,				/* to_can_run */
1809  0,				/* to_notice_signals */
1810  remote_thread_alive,		/* to_thread_alive */
1811  0,				/* to_stop */
1812  process_stratum,		/* to_stratum */
1813  NULL,				/* to_next */
1814  1,				/* to_has_all_memory */
1815  1,				/* to_has_memory */
1816  1,				/* to_has_stack */
1817  1,				/* to_has_registers */
1818  1,				/* to_has_execution */
1819  NULL,				/* sections */
1820  NULL,				/* sections_end */
1821  OPS_MAGIC			/* to_magic */
1822};
1823
1824void
1825_initialize_remote ()
1826{
1827  add_target (&remote_ops);
1828  add_target (&extended_remote_ops);
1829
1830  add_show_from_set (add_set_cmd ("remotetimeout", no_class,
1831				  var_integer, (char *)&remote_timeout,
1832				  "Set timeout value for remote read.\n", &setlist),
1833		     &showlist);
1834
1835  add_show_from_set (add_set_cmd ("remotebreak", no_class,
1836				  var_integer, (char *)&remote_break,
1837				  "Set whether to send break if interrupted.\n", &setlist),
1838		     &showlist);
1839}
1840