1/* Remote debugging interface for Tandem ST2000 phone switch, for GDB.
2
3   Copyright 1990, 1991, 1992, 1993, 1994, 1995, 1998, 1999, 2000,
4   2001, 2002 Free Software Foundation, Inc.
5
6   Contributed by Cygnus Support.  Written by Jim Kingdon for Cygnus.
7
8   This file is part of GDB.
9
10   This program is free software; you can redistribute it and/or modify
11   it under the terms of the GNU General Public License as published by
12   the Free Software Foundation; either version 2 of the License, or
13   (at your option) any later version.
14
15   This program is distributed in the hope that it will be useful,
16   but WITHOUT ANY WARRANTY; without even the implied warranty of
17   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18   GNU General Public License for more details.
19
20   You should have received a copy of the GNU General Public License
21   along with this program; if not, write to the Free Software
22   Foundation, Inc., 59 Temple Place - Suite 330,
23   Boston, MA 02111-1307, USA.  */
24
25/* This file was derived from remote-eb.c, which did a similar job, but for
26   an AMD-29K running EBMON.  That file was in turn derived from remote.c
27   as mentioned in the following comment (left in for comic relief):
28
29   "This is like remote.c but is for an esoteric situation--
30   having an a29k board in a PC hooked up to a unix machine with
31   a serial line, and running ctty com1 on the PC, through which
32   the unix machine can run ebmon.  Not to mention that the PC
33   has PC/NFS, so it can access the same executables that gdb can,
34   over the net in real time."
35
36   In reality, this module talks to a debug monitor called 'STDEBUG', which
37   runs in a phone switch.  We communicate with STDEBUG via either a direct
38   serial line, or a TCP (or possibly TELNET) stream to a terminal multiplexor,
39   which in turn talks to the phone switch. */
40
41#include "defs.h"
42#include "gdbcore.h"
43#include "target.h"
44#include "gdb_string.h"
45#include <sys/types.h>
46#include "serial.h"
47#include "regcache.h"
48
49extern struct target_ops st2000_ops;	/* Forward declaration */
50
51static void st2000_close ();
52static void st2000_fetch_register ();
53static void st2000_store_register ();
54
55#define LOG_FILE "st2000.log"
56#if defined (LOG_FILE)
57FILE *log_file;
58#endif
59
60static int timeout = 24;
61
62/* Descriptor for I/O to remote machine.  Initialize it to -1 so that
63   st2000_open knows that we don't have a file open when the program
64   starts.  */
65
66static struct serial *st2000_desc;
67
68/* Send data to stdebug.  Works just like printf. */
69
70static void
71printf_stdebug (char *pattern,...)
72{
73  va_list args;
74  char buf[200];
75
76  va_start (args, pattern);
77
78  vsprintf (buf, pattern, args);
79  va_end (args);
80
81  if (serial_write (st2000_desc, buf, strlen (buf)))
82    fprintf_unfiltered (gdb_stderr, "serial_write failed: %s\n",
83			safe_strerror (errno));
84}
85
86/* Read a character from the remote system, doing all the fancy timeout
87   stuff.  */
88
89static int
90readchar (int timeout)
91{
92  int c;
93
94  c = serial_readchar (st2000_desc, timeout);
95
96#ifdef LOG_FILE
97  putc (c & 0x7f, log_file);
98#endif
99
100  if (c >= 0)
101    return c & 0x7f;
102
103  if (c == SERIAL_TIMEOUT)
104    {
105      if (timeout == 0)
106	return c;		/* Polls shouldn't generate timeout errors */
107
108      error ("Timeout reading from remote system.");
109    }
110
111  perror_with_name ("remote-st2000");
112}
113
114/* Scan input from the remote system, until STRING is found.  If DISCARD is
115   non-zero, then discard non-matching input, else print it out.
116   Let the user break out immediately.  */
117static void
118expect (char *string, int discard)
119{
120  char *p = string;
121  int c;
122
123  immediate_quit++;
124  while (1)
125    {
126      c = readchar (timeout);
127      if (c == *p++)
128	{
129	  if (*p == '\0')
130	    {
131	      immediate_quit--;
132	      return;
133	    }
134	}
135      else
136	{
137	  if (!discard)
138	    {
139	      fwrite (string, 1, (p - 1) - string, stdout);
140	      putchar ((char) c);
141	      fflush (stdout);
142	    }
143	  p = string;
144	}
145    }
146}
147
148/* Keep discarding input until we see the STDEBUG prompt.
149
150   The convention for dealing with the prompt is that you
151   o give your command
152   o *then* wait for the prompt.
153
154   Thus the last thing that a procedure does with the serial line
155   will be an expect_prompt().  Exception:  st2000_resume does not
156   wait for the prompt, because the terminal is being handed over
157   to the inferior.  However, the next thing which happens after that
158   is a st2000_wait which does wait for the prompt.
159   Note that this includes abnormal exit, e.g. error().  This is
160   necessary to prevent getting into states from which we can't
161   recover.  */
162static void
163expect_prompt (int discard)
164{
165#if defined (LOG_FILE)
166  /* This is a convenient place to do this.  The idea is to do it often
167     enough that we never lose much data if we terminate abnormally.  */
168  fflush (log_file);
169#endif
170  expect ("dbug> ", discard);
171}
172
173/* Get a hex digit from the remote system & return its value.
174   If ignore_space is nonzero, ignore spaces (not newline, tab, etc).  */
175static int
176get_hex_digit (int ignore_space)
177{
178  int ch;
179  while (1)
180    {
181      ch = readchar (timeout);
182      if (ch >= '0' && ch <= '9')
183	return ch - '0';
184      else if (ch >= 'A' && ch <= 'F')
185	return ch - 'A' + 10;
186      else if (ch >= 'a' && ch <= 'f')
187	return ch - 'a' + 10;
188      else if (ch == ' ' && ignore_space)
189	;
190      else
191	{
192	  expect_prompt (1);
193	  error ("Invalid hex digit from remote system.");
194	}
195    }
196}
197
198/* Get a byte from stdebug and put it in *BYT.  Accept any number
199   leading spaces.  */
200static void
201get_hex_byte (char *byt)
202{
203  int val;
204
205  val = get_hex_digit (1) << 4;
206  val |= get_hex_digit (0);
207  *byt = val;
208}
209
210/* Get N 32-bit words from remote, each preceded by a space,
211   and put them in registers starting at REGNO.  */
212static void
213get_hex_regs (int n, int regno)
214{
215  long val;
216  int i;
217
218  for (i = 0; i < n; i++)
219    {
220      int j;
221
222      val = 0;
223      for (j = 0; j < 8; j++)
224	val = (val << 4) + get_hex_digit (j == 0);
225      regcache_raw_supply (current_regcache, regno++, (char *) &val);
226    }
227}
228
229/* This is called not only when we first attach, but also when the
230   user types "run" after having attached.  */
231static void
232st2000_create_inferior (char *execfile, char *args, char **env,
233			int from_tty)
234{
235  int entry_pt;
236
237  if (args && *args)
238    error ("Can't pass arguments to remote STDEBUG process");
239
240  if (execfile == 0 || exec_bfd == 0)
241    error ("No executable file specified");
242
243  entry_pt = (int) bfd_get_start_address (exec_bfd);
244
245/* The "process" (board) is already stopped awaiting our commands, and
246   the program is already downloaded.  We just set its PC and go.  */
247
248  clear_proceed_status ();
249
250  /* Tell wait_for_inferior that we've started a new process.  */
251  init_wait_for_inferior ();
252
253  /* Set up the "saved terminal modes" of the inferior
254     based on what modes we are starting it with.  */
255  target_terminal_init ();
256
257  /* Install inferior's terminal modes.  */
258  target_terminal_inferior ();
259
260  /* insert_step_breakpoint ();  FIXME, do we need this?  */
261  /* Let 'er rip... */
262  proceed ((CORE_ADDR) entry_pt, TARGET_SIGNAL_DEFAULT, 0);
263}
264
265/* Open a connection to a remote debugger.
266   NAME is the filename used for communication.  */
267
268static int baudrate = 9600;
269static char dev_name[100];
270
271static void
272st2000_open (char *args, int from_tty)
273{
274  int n;
275  char junk[100];
276
277  target_preopen (from_tty);
278
279  n = sscanf (args, " %s %d %s", dev_name, &baudrate, junk);
280
281  if (n != 2)
282    error ("Bad arguments.  Usage: target st2000 <device> <speed>\n\
283or target st2000 <host> <port>\n");
284
285  st2000_close (0);
286
287  st2000_desc = serial_open (dev_name);
288
289  if (!st2000_desc)
290    perror_with_name (dev_name);
291
292  if (serial_setbaudrate (st2000_desc, baudrate))
293    {
294      serial_close (dev_name);
295      perror_with_name (dev_name);
296    }
297
298  serial_raw (st2000_desc);
299
300  push_target (&st2000_ops);
301
302#if defined (LOG_FILE)
303  log_file = fopen (LOG_FILE, "w");
304  if (log_file == NULL)
305    perror_with_name (LOG_FILE);
306#endif
307
308  /* Hello?  Are you there?  */
309  printf_stdebug ("\003");	/* ^C wakes up dbug */
310
311  expect_prompt (1);
312
313  if (from_tty)
314    printf ("Remote %s connected to %s\n", target_shortname,
315	    dev_name);
316}
317
318/* Close out all files and local state before this target loses control. */
319
320static void
321st2000_close (int quitting)
322{
323  serial_close (st2000_desc);
324
325#if defined (LOG_FILE)
326  if (log_file)
327    {
328      if (ferror (log_file))
329	fprintf_unfiltered (gdb_stderr, "Error writing log file.\n");
330      if (fclose (log_file) != 0)
331	fprintf_unfiltered (gdb_stderr, "Error closing log file.\n");
332    }
333#endif
334}
335
336/* Terminate the open connection to the remote debugger.
337   Use this when you want to detach and do something else
338   with your gdb.  */
339static void
340st2000_detach (int from_tty)
341{
342  pop_target ();		/* calls st2000_close to do the real work */
343  if (from_tty)
344    printf ("Ending remote %s debugging\n", target_shortname);
345}
346
347/* Tell the remote machine to resume.  */
348
349static void
350st2000_resume (ptid_t ptid, int step, enum target_signal sig)
351{
352  if (step)
353    {
354      printf_stdebug ("ST\r");
355      /* Wait for the echo.  */
356      expect ("ST\r", 1);
357    }
358  else
359    {
360      printf_stdebug ("GO\r");
361      /* Swallow the echo.  */
362      expect ("GO\r", 1);
363    }
364}
365
366/* Wait until the remote machine stops, then return,
367   storing status in STATUS just as `wait' would.  */
368
369static ptid_t
370st2000_wait (ptid_t ptid, struct target_waitstatus *status)
371{
372  int old_timeout = timeout;
373
374  status->kind = TARGET_WAITKIND_EXITED;
375  status->value.integer = 0;
376
377  timeout = 0;			/* Don't time out -- user program is running. */
378
379  expect_prompt (0);		/* Wait for prompt, outputting extraneous text */
380
381  status->kind = TARGET_WAITKIND_STOPPED;
382  status->value.sig = TARGET_SIGNAL_TRAP;
383
384  timeout = old_timeout;
385
386  return inferior_ptid;
387}
388
389/* Return the name of register number REGNO in the form input and
390   output by STDEBUG.  Currently, REGISTER_NAME just happens return
391   exactly what STDEBUG wants.  Lets take advantage of that just as
392   long as possible! */
393
394static char *
395get_reg_name (int regno)
396{
397  static char buf[50];
398  const char *p;
399  char *b;
400
401  b = buf;
402
403  for (p = REGISTER_NAME (regno); *p; p++)
404    *b++ = toupper (*p);
405  *b = '\000';
406
407  return buf;
408}
409
410/* Read the remote registers into the block REGS.  */
411
412static void
413st2000_fetch_registers (void)
414{
415  int regno;
416
417  /* Yeah yeah, I know this is horribly inefficient.  But it isn't done
418     very often...  I'll clean it up later.  */
419
420  for (regno = 0; regno <= PC_REGNUM; regno++)
421    st2000_fetch_register (regno);
422}
423
424/* Fetch register REGNO, or all registers if REGNO is -1.
425   Returns errno value.  */
426static void
427st2000_fetch_register (int regno)
428{
429  if (regno == -1)
430    st2000_fetch_registers ();
431  else
432    {
433      char *name = get_reg_name (regno);
434      printf_stdebug ("DR %s\r", name);
435      expect (name, 1);
436      expect (" : ", 1);
437      get_hex_regs (1, regno);
438      expect_prompt (1);
439    }
440  return;
441}
442
443/* Store the remote registers from the contents of the block REGS.  */
444
445static void
446st2000_store_registers (void)
447{
448  int regno;
449
450  for (regno = 0; regno <= PC_REGNUM; regno++)
451    st2000_store_register (regno);
452
453  registers_changed ();
454}
455
456/* Store register REGNO, or all if REGNO == 0.
457   Return errno value.  */
458static void
459st2000_store_register (int regno)
460{
461  if (regno == -1)
462    st2000_store_registers ();
463  else
464    {
465      printf_stdebug ("PR %s %x\r", get_reg_name (regno),
466		      read_register (regno));
467
468      expect_prompt (1);
469    }
470}
471
472/* Get ready to modify the registers array.  On machines which store
473   individual registers, this doesn't need to do anything.  On machines
474   which store all the registers in one fell swoop, this makes sure
475   that registers contains all the registers from the program being
476   debugged.  */
477
478static void
479st2000_prepare_to_store (void)
480{
481  /* Do nothing, since we can store individual regs */
482}
483
484static void
485st2000_files_info (void)
486{
487  printf ("\tAttached to %s at %d baud.\n",
488	  dev_name, baudrate);
489}
490
491/* Copy LEN bytes of data from debugger memory at MYADDR
492   to inferior's memory at MEMADDR.  Returns length moved.  */
493static int
494st2000_write_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
495{
496  int i;
497
498  for (i = 0; i < len; i++)
499    {
500      printf_stdebug ("PM.B %x %x\r", memaddr + i, myaddr[i]);
501      expect_prompt (1);
502    }
503  return len;
504}
505
506/* Read LEN bytes from inferior memory at MEMADDR.  Put the result
507   at debugger address MYADDR.  Returns length moved.  */
508static int
509st2000_read_inferior_memory (CORE_ADDR memaddr, char *myaddr, int len)
510{
511  int i;
512
513  /* Number of bytes read so far.  */
514  int count;
515
516  /* Starting address of this pass.  */
517  unsigned long startaddr;
518
519  /* Number of bytes to read in this pass.  */
520  int len_this_pass;
521
522  /* Note that this code works correctly if startaddr is just less
523     than UINT_MAX (well, really CORE_ADDR_MAX if there was such a
524     thing).  That is, something like
525     st2000_read_bytes (CORE_ADDR_MAX - 4, foo, 4)
526     works--it never adds len to memaddr and gets 0.  */
527  /* However, something like
528     st2000_read_bytes (CORE_ADDR_MAX - 3, foo, 4)
529     doesn't need to work.  Detect it and give up if there's an attempt
530     to do that.  */
531  if (((memaddr - 1) + len) < memaddr)
532    {
533      errno = EIO;
534      return 0;
535    }
536
537  startaddr = memaddr;
538  count = 0;
539  while (count < len)
540    {
541      len_this_pass = 16;
542      if ((startaddr % 16) != 0)
543	len_this_pass -= startaddr % 16;
544      if (len_this_pass > (len - count))
545	len_this_pass = (len - count);
546
547      printf_stdebug ("DI.L %x %x\r", startaddr, len_this_pass);
548      expect (":  ", 1);
549
550      for (i = 0; i < len_this_pass; i++)
551	get_hex_byte (&myaddr[count++]);
552
553      expect_prompt (1);
554
555      startaddr += len_this_pass;
556    }
557  return len;
558}
559
560/* Transfer LEN bytes between GDB address MYADDR and target address
561   MEMADDR.  If WRITE is non-zero, transfer them to the target,
562   otherwise transfer them from the target.  TARGET is unused.
563
564   Returns the number of bytes transferred. */
565
566static int
567st2000_xfer_inferior_memory (CORE_ADDR memaddr, char *myaddr, int len,
568			     int write, struct mem_attrib *attrib,
569			     struct target_ops *target)
570{
571  if (write)
572    return st2000_write_inferior_memory (memaddr, myaddr, len);
573  else
574    return st2000_read_inferior_memory (memaddr, myaddr, len);
575}
576
577static void
578st2000_kill (char *args, int from_tty)
579{
580  return;			/* Ignore attempts to kill target system */
581}
582
583/* Clean up when a program exits.
584
585   The program actually lives on in the remote processor's RAM, and may be
586   run again without a download.  Don't leave it full of breakpoint
587   instructions.  */
588
589static void
590st2000_mourn_inferior (void)
591{
592  remove_breakpoints ();
593  unpush_target (&st2000_ops);
594  generic_mourn_inferior ();	/* Do all the proper things now */
595}
596
597#define MAX_STDEBUG_BREAKPOINTS 16
598
599static CORE_ADDR breakaddr[MAX_STDEBUG_BREAKPOINTS] =
600{0};
601
602static int
603st2000_insert_breakpoint (CORE_ADDR addr, char *shadow)
604{
605  int i;
606  CORE_ADDR bp_addr = addr;
607  int bp_size = 0;
608
609  BREAKPOINT_FROM_PC (&bp_addr, &bp_size);
610
611  for (i = 0; i <= MAX_STDEBUG_BREAKPOINTS; i++)
612    if (breakaddr[i] == 0)
613      {
614	breakaddr[i] = addr;
615
616	st2000_read_inferior_memory (bp_addr, shadow, bp_size);
617	printf_stdebug ("BR %x H\r", addr);
618	expect_prompt (1);
619	return 0;
620      }
621
622  fprintf_unfiltered (gdb_stderr, "Too many breakpoints (> 16) for STDBUG\n");
623  return 1;
624}
625
626static int
627st2000_remove_breakpoint (CORE_ADDR addr, char *shadow)
628{
629  int i;
630
631  for (i = 0; i < MAX_STDEBUG_BREAKPOINTS; i++)
632    if (breakaddr[i] == addr)
633      {
634	breakaddr[i] = 0;
635
636	printf_stdebug ("CB %d\r", i);
637	expect_prompt (1);
638	return 0;
639      }
640
641  fprintf_unfiltered (gdb_stderr,
642		      "Can't find breakpoint associated with 0x%x\n", addr);
643  return 1;
644}
645
646
647/* Put a command string, in args, out to STDBUG.  Output from STDBUG is placed
648   on the users terminal until the prompt is seen. */
649
650static void
651st2000_command (char *args, int fromtty)
652{
653  if (!st2000_desc)
654    error ("st2000 target not open.");
655
656  if (!args)
657    error ("Missing command.");
658
659  printf_stdebug ("%s\r", args);
660  expect_prompt (0);
661}
662
663/* Connect the user directly to STDBUG.  This command acts just like the
664   'cu' or 'tip' command.  Use <CR>~. or <CR>~^D to break out.  */
665
666/*static struct ttystate ttystate; */
667
668static void
669cleanup_tty (void)
670{
671  printf ("\r\n[Exiting connect mode]\r\n");
672/*  serial_restore(0, &ttystate); */
673}
674
675#if 0
676/* This all should now be in serial.c */
677
678static void
679connect_command (char *args, int fromtty)
680{
681  fd_set readfds;
682  int numfds;
683  int c;
684  char cur_esc = 0;
685
686  dont_repeat ();
687
688  if (st2000_desc < 0)
689    error ("st2000 target not open.");
690
691  if (args)
692    fprintf ("This command takes no args.  They have been ignored.\n");
693
694  printf ("[Entering connect mode.  Use ~. or ~^D to escape]\n");
695
696  serial_raw (0, &ttystate);
697
698  make_cleanup (cleanup_tty, 0);
699
700  FD_ZERO (&readfds);
701
702  while (1)
703    {
704      do
705	{
706	  FD_SET (0, &readfds);
707	  FD_SET (deprecated_serial_fd (st2000_desc), &readfds);
708	  numfds = select (sizeof (readfds) * 8, &readfds, 0, 0, 0);
709	}
710      while (numfds == 0);
711
712      if (numfds < 0)
713	perror_with_name ("select");
714
715      if (FD_ISSET (0, &readfds))
716	{			/* tty input, send to stdebug */
717	  c = getchar ();
718	  if (c < 0)
719	    perror_with_name ("connect");
720
721	  printf_stdebug ("%c", c);
722	  switch (cur_esc)
723	    {
724	    case 0:
725	      if (c == '\r')
726		cur_esc = c;
727	      break;
728	    case '\r':
729	      if (c == '~')
730		cur_esc = c;
731	      else
732		cur_esc = 0;
733	      break;
734	    case '~':
735	      if (c == '.' || c == '\004')
736		return;
737	      else
738		cur_esc = 0;
739	    }
740	}
741
742      if (FD_ISSET (deprecated_serial_fd (st2000_desc), &readfds))
743	{
744	  while (1)
745	    {
746	      c = readchar (0);
747	      if (c < 0)
748		break;
749	      putchar (c);
750	    }
751	  fflush (stdout);
752	}
753    }
754}
755#endif /* 0 */
756
757/* Define the target subroutine names */
758
759struct target_ops st2000_ops;
760
761static void
762init_st2000_ops (void)
763{
764  st2000_ops.to_shortname = "st2000";
765  st2000_ops.to_longname = "Remote serial Tandem ST2000 target";
766  st2000_ops.to_doc = "Use a remote computer running STDEBUG connected by a serial line;\n\
767or a network connection.\n\
768Arguments are the name of the device for the serial line,\n\
769the speed to connect at in bits per second.";
770  st2000_ops.to_open = st2000_open;
771  st2000_ops.to_close = st2000_close;
772  st2000_ops.to_detach = st2000_detach;
773  st2000_ops.to_resume = st2000_resume;
774  st2000_ops.to_wait = st2000_wait;
775  st2000_ops.to_fetch_registers = st2000_fetch_register;
776  st2000_ops.to_store_registers = st2000_store_register;
777  st2000_ops.to_prepare_to_store = st2000_prepare_to_store;
778  st2000_ops.deprecated_xfer_memory = st2000_xfer_inferior_memory;
779  st2000_ops.to_files_info = st2000_files_info;
780  st2000_ops.to_insert_breakpoint = st2000_insert_breakpoint;
781  st2000_ops.to_remove_breakpoint = st2000_remove_breakpoint;	/* Breakpoints */
782  st2000_ops.to_kill = st2000_kill;
783  st2000_ops.to_create_inferior = st2000_create_inferior;
784  st2000_ops.to_mourn_inferior = st2000_mourn_inferior;
785  st2000_ops.to_stratum = process_stratum;
786  st2000_ops.to_has_all_memory = 1;
787  st2000_ops.to_has_memory = 1;
788  st2000_ops.to_has_stack = 1;
789  st2000_ops.to_has_registers = 1;
790  st2000_ops.to_has_execution = 1;	/* all mem, mem, stack, regs, exec */
791  st2000_ops.to_magic = OPS_MAGIC;	/* Always the last thing */
792};
793
794void
795_initialize_remote_st2000 (void)
796{
797  init_st2000_ops ();
798  add_target (&st2000_ops);
799  add_com ("st2000 <command>", class_obscure, st2000_command,
800	   "Send a command to the STDBUG monitor.");
801  add_com ("connect", class_obscure, connect_command,
802	   "Connect the terminal directly up to the STDBUG command monitor.\n\
803Use <CR>~. or <CR>~^D to break out.");
804}
805