Hmm.. The ChangeLog went in, but not the code....
[platform/upstream/binutils.git] / gdb / remote-hms.c
1 /* Remote debugging interface for Hitachi HMS Monitor Version 1.0
2    Copyright 1995 Free Software Foundation, Inc.
3    Contributed by Cygnus Support.  Written by Steve Chamberlain
4    (sac@cygnus.com).
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
21
22 #include "defs.h"
23 #include "gdbcore.h"
24 #include "target.h"
25 #include "monitor.h"
26 #include "serial.h"
27
28 static void hms_open PARAMS ((char *args, int from_tty));
29
30 static void
31 hms_supply_register (regname, regnamelen, val, vallen)
32      char *regname;
33      int regnamelen;
34      char *val;
35      int vallen;
36 {
37   int regno;
38
39   if (regnamelen != 2)
40     return;
41   if (regname[0] != 'P')
42     return;
43   /* We scan off all the registers in one go */
44
45   val = monitor_supply_register (PC_REGNUM, val);
46   /* Skip the ccr string */
47   while (*val != '=' && *val)
48     val++;
49
50   val = monitor_supply_register (CCR_REGNUM, val + 1);
51
52   /* Skip up to rest of regs */
53   while (*val != '=' && *val)
54     val++;
55
56   for (regno = 0; regno < 7; regno++)
57     {
58       val = monitor_supply_register (regno, val + 1);
59     }
60 }
61
62 /*
63  * This array of registers needs to match the indexes used by GDB. The
64  * whole reason this exists is because the various ROM monitors use
65  * different names than GDB does, and don't support all the
66  * registers either. So, typing "info reg sp" becomes a "r30".
67  */
68
69 static char *hms_regnames[NUM_REGS] =
70 {
71   "R0", "R1", "R2", "R3", "R4", "R5", "R6", "R7", "CCR", "PC"
72 };
73
74 /*
75  * Define the monitor command strings. Since these are passed directly
76  * through to a printf style function, we need can include formatting
77  * strings. We also need a CR or LF on the end.
78  */
79
80 static struct target_ops hms_ops;
81
82 static char *hms_inits[] =
83 {"\003",                        /* Resets the prompt, and clears repeated cmds */
84  NULL};
85
86 static struct monitor_ops hms_cmds =
87 {
88   MO_CLR_BREAK_USES_ADDR | MO_FILL_USES_ADDR | MO_GETMEM_NEEDS_RANGE,
89   hms_inits,                    /* Init strings */
90   "g\r",                        /* continue command */
91   "s\r",                        /* single step */
92   "\003",                       /* ^C interrupts the program */
93   "b %x\r",                     /* set a breakpoint */
94   "b - %x\r",                   /* clear a breakpoint */
95   "b -\r",                      /* clear all breakpoints */
96   "f %x %x %x\r",               /* fill (start end val) */
97   {
98     "m.b %x=%x\r",              /* setmem.cmdb (addr, value) */
99     "m.w %x=%x\r",              /* setmem.cmdw (addr, value) */
100     NULL,                       /* setmem.cmdl (addr, value) */
101     NULL,                       /* setmem.cmdll (addr, value) */
102     NULL,                       /* setreg.resp_delim */
103     NULL,                       /* setreg.term */
104     NULL,                       /* setreg.term_cmd */
105   },
106   {
107     "m.b %x %x\r",              /* getmem.cmdb (addr, addr) */
108     "m.w %x %x\r",              /* getmem.cmdw (addr, addr) */
109     NULL,                       /* getmem.cmdl (addr, addr) */
110     NULL,                       /* getmem.cmdll (addr, addr) */
111     ": ",                       /* getmem.resp_delim */
112     ">",                        /* getmem.term */
113     "\003",                     /* getmem.term_cmd */
114   },
115   {
116     "\003r %s=%x\r",            /* setreg.cmd (name, value) */
117     NULL,                       /* setreg.resp_delim */
118     NULL,                       /* setreg.term */
119     NULL                        /* setreg.term_cmd */
120   },
121   {
122     "r %s\r",                   /* getreg.cmd (name) */
123     " (",                       /* getreg.resp_delim */
124     "):",                       /* getreg.term */
125     "\003",                     /* getreg.term_cmd */
126   },
127   "r\r",                        /* dump_registers */
128   "\\(\\w+\\)=\\([0-9a-fA-F]+\\)",      /* register_pattern */
129   hms_supply_register,          /* supply_register */
130   NULL,                         /* load_routine (defaults to SRECs) */
131   "tl\r",                       /* download command */
132   NULL,                         /* load response */
133   ">",                          /* monitor command prompt */
134   "\r",                         /* end-of-command delimitor */
135   NULL,                         /* optional command terminator */
136   &hms_ops,                     /* target operations */
137   SERIAL_1_STOPBITS,            /* number of stop bits */
138   hms_regnames,                 /* registers names */
139   MONITOR_OPS_MAGIC             /* magic */
140 };
141
142 static void
143 hms_open (args, from_tty)
144      char *args;
145      int from_tty;
146 {
147   monitor_open (args, &hms_cmds, from_tty);
148 }
149
150 int write_dos_tick_delay;
151
152 void
153 _initialize_remote_hms ()
154 {
155   init_monitor_ops (&hms_ops);
156
157   hms_ops.to_shortname = "hms";
158   hms_ops.to_longname = "Hitachi Microsystems H8/300 debug monitor";
159   hms_ops.to_doc = "Debug via the HMS monitor.\n\
160 Specify the serial device it is connected to (e.g. /dev/ttya).";
161   hms_ops.to_open = hms_open;
162   /* By trial and error I've found that this delay doesn't break things */
163   write_dos_tick_delay = 1;
164   add_target (&hms_ops);
165 }
166
167
168 #if 0
169 /* This is kept here because we used to support the H8/500 in this module,
170    and I haven't done the H8/500 yet */
171 #include "defs.h"
172 #include "inferior.h"
173 #include "wait.h"
174 #include "value.h"
175 #include <string.h>
176 #include <ctype.h>
177 #include <fcntl.h>
178 #include <signal.h>
179 #include <setjmp.h>
180 #include <errno.h>
181 #include "terminal.h"
182 #include "target.h"
183 #include "gdbcore.h"
184 #include "serial.h"
185 #include "remote-utils.h"
186 /* External data declarations */
187 extern int stop_soon_quietly;   /* for wait_for_inferior */
188
189 /* Forward data declarations */
190 extern struct target_ops hms_ops;       /* Forward declaration */
191
192 /* Forward function declarations */
193 static void hms_fetch_registers ();
194 static int hms_store_registers ();
195 static void hms_close ();
196 static int hms_clear_breakpoints ();
197
198 extern struct target_ops hms_ops;
199 static void hms_drain ();
200 static void add_commands ();
201 static void remove_commands ();
202
203 static int quiet = 1;           /* FIXME - can be removed after Dec '94 */
204
205
206
207 /***********************************************************************
208  * I/O stuff stolen from remote-eb.c
209  ***********************************************************************/
210
211 static int timeout = 2;
212
213 static const char *dev_name;
214
215 /* Descriptor for I/O to remote machine.  Initialize it to -1 so that
216    hms_open knows that we don't have a file open when the program
217    starts.  */
218
219 static int before = 0xdead;
220 static int is_open = 0;
221 static int after = 0xdead;
222 int
223 check_open ()
224 {
225   if (before != 0xdead
226       || after != 0xdead)
227     printf ("OUTCH! \n");
228   if (!is_open)
229     {
230       error ("remote device not open");
231     }
232 }
233
234 #define ON      1
235 #define OFF     0
236
237 /* Read a character from the remote system, doing all the fancy
238    timeout stuff.  */
239 static int
240 readchar ()
241 {
242   int buf;
243
244   buf = SERIAL_READCHAR (desc, timeout);
245
246   if (buf == SERIAL_TIMEOUT)
247     {
248       hms_write (".\r\n", 3);
249       error ("Timeout reading from remote system.");
250     }
251   if (buf == SERIAL_ERROR)
252     {
253       error ("Serial port error!");
254     }
255
256   if (!quiet || remote_debug)
257     printf_unfiltered ("%c", buf);
258
259   return buf & 0x7f;
260 }
261
262 static void
263 flush ()
264 {
265   while (1)
266     {
267       int b = SERIAL_READCHAR (desc, 0);
268       if (b == SERIAL_TIMEOUT)
269         return;
270     }
271 }
272
273 static int
274 readchar_nofail ()
275 {
276   int buf;
277
278   buf = SERIAL_READCHAR (desc, timeout);
279   if (buf == SERIAL_TIMEOUT)
280     buf = 0;
281   if (!quiet || remote_debug)
282     printf_unfiltered ("%c", buf);
283
284   return buf & 0x7f;
285
286 }
287
288 /* Keep discarding input from the remote system, until STRING is found.
289    Let the user break out immediately.  */
290 static void
291 expect (string)
292      char *string;
293 {
294   char *p = string;
295   char c;
296   immediate_quit = 1;
297   while (1)
298     {
299       c = readchar ();
300       if (c == *p)
301         {
302           p++;
303           if (*p == '\0')
304             {
305               immediate_quit = 0;
306               return;
307             }
308         }
309       else
310         {
311           p = string;
312           if (c == *p)
313             p++;
314         }
315     }
316 }
317
318 /* Keep discarding input until we see the hms prompt.
319
320    The convention for dealing with the prompt is that you
321    o give your command
322    o *then* wait for the prompt.
323
324    Thus the last thing that a procedure does with the serial line
325    will be an expect_prompt().  Exception:  hms_resume does not
326    wait for the prompt, because the terminal is being handed over
327    to the inferior.  However, the next thing which happens after that
328    is a hms_wait which does wait for the prompt.
329    Note that this includes abnormal exit, e.g. error().  This is
330    necessary to prevent getting into states from which we can't
331    recover.  */
332 static void
333 expect_prompt ()
334 {
335   expect ("HMS>");
336 }
337
338 /* Get a hex digit from the remote system & return its value.
339    If ignore_space is nonzero, ignore spaces (not newline, tab, etc).  */
340 static int
341 get_hex_digit (ignore_space)
342      int ignore_space;
343 {
344   int ch;
345
346   while (1)
347     {
348       ch = readchar ();
349       if (ch >= '0' && ch <= '9')
350         return ch - '0';
351       else if (ch >= 'A' && ch <= 'F')
352         return ch - 'A' + 10;
353       else if (ch >= 'a' && ch <= 'f')
354         return ch - 'a' + 10;
355       else if (ch == ' ' && ignore_space)
356         ;
357       else
358         {
359           expect_prompt ();
360           error ("Invalid hex digit from remote system.");
361         }
362     }
363 }
364
365 /* Get a byte from hms_desc and put it in *BYT.  Accept any number
366    leading spaces.  */
367 static void
368 get_hex_byte (byt)
369      char *byt;
370 {
371   int val;
372
373   val = get_hex_digit (1) << 4;
374   val |= get_hex_digit (0);
375   *byt = val;
376 }
377
378 /* Read a 32-bit hex word from the hms, preceded by a space  */
379 static long
380 get_hex_word ()
381 {
382   long val;
383   int j;
384
385   val = 0;
386   for (j = 0; j < 8; j++)
387     val = (val << 4) + get_hex_digit (j == 0);
388   return val;
389 }
390
391 /* Called when SIGALRM signal sent due to alarm() timeout.  */
392
393 /* Number of SIGTRAPs we need to simulate.  That is, the next
394    NEED_ARTIFICIAL_TRAP calls to hms_wait should just return
395    SIGTRAP without actually waiting for anything.  */
396
397 static int need_artificial_trap = 0;
398
399 void
400 hms_kill (arg, from_tty)
401      char *arg;
402      int from_tty;
403 {
404
405 }
406
407 /* This is called not only when we first attach, but also when the
408    user types "run" after having attached.  */
409 void
410 hms_create_inferior (execfile, args, env)
411      char *execfile;
412      char *args;
413      char **env;
414 {
415   int entry_pt;
416   char buffer[100];
417
418   if (args && *args)
419     error ("Can't pass arguments to remote hms process.");
420
421   if (execfile == 0 || exec_bfd == 0)
422     error ("No exec file specified");
423
424   entry_pt = (int) bfd_get_start_address (exec_bfd);
425   check_open ();
426
427   hms_kill (NULL, NULL);
428   hms_clear_breakpoints ();
429   init_wait_for_inferior ();
430   hms_write_cr ("");
431   expect_prompt ();
432
433   insert_breakpoints ();        /* Needed to get correct instruction in cache */
434   proceed (entry_pt, TARGET_SIGNAL_DEFAULT, 0);
435 }
436
437 /* Open a connection to a remote debugger.
438    NAME is the filename used for communication, then a space,
439    then the baud rate.
440  */
441
442 static char *
443 find_end_of_word (s)
444      char *s;
445 {
446   while (*s && !isspace (*s))
447     s++;
448   return s;
449 }
450
451 static char *
452 get_word (p)
453      char **p;
454 {
455   char *s = *p;
456   char *word;
457   char *copy;
458   size_t len;
459
460   while (isspace (*s))
461     s++;
462
463   word = s;
464
465   len = 0;
466
467   while (*s && !isspace (*s))
468     {
469       s++;
470       len++;
471
472     }
473   copy = xmalloc (len + 1);
474   memcpy (copy, word, len);
475   copy[len] = 0;
476   *p = s;
477   return copy;
478 }
479
480 static int baudrate = 9600;
481
482 static int
483 is_baudrate_right ()
484 {
485   int ok;
486
487   /* Put this port into NORMAL mode, send the 'normal' character */
488
489   hms_write ("\001", 1);        /* Control A */
490   hms_write ("\r\n", 2);        /* Cr */
491
492   while (1)
493     {
494       ok = SERIAL_READCHAR (desc, timeout);
495       if (ok < 0)
496         break;
497     }
498
499   hms_write ("r", 1);
500
501   if (readchar_nofail () == 'r')
502     return 1;
503
504   /* Not the right baudrate, or the board's not on */
505   return 0;
506 }
507 static void
508 set_rate ()
509 {
510   if (!SERIAL_SETBAUDRATE (desc, baudrate))
511     error ("Can't set baudrate");
512 }
513
514
515
516 /* Close out all files and local state before this target loses control. */
517
518 static void
519 hms_close (quitting)
520      int quitting;
521 {
522   /* Clear any break points */
523   remove_commands ();
524   hms_clear_breakpoints ();
525   sleep (1);                    /* Let any output make it all the way back */
526   if (is_open)
527     {
528       SERIAL_WRITE (desc, "R\r\n", 3);
529       SERIAL_CLOSE (desc);
530     }
531   is_open = 0;
532 }
533
534 /* Terminate the open connection to the remote debugger.  Use this
535    when you want to detach and do something else with your gdb.  */ void
536 hms_detach (args, from_tty)
537      char *args;
538      int from_tty;
539 {
540   if (is_open)
541     {
542       hms_clear_breakpoints ();
543     }
544
545   pop_target ();                /* calls hms_close to do the real work
546                                  */
547   if (from_tty)
548     printf_filtered ("Ending remote %s debugging\n",
549                      target_shortname);
550 }
551
552 /* Tell the remote machine to resume.  */
553
554 void
555 hms_resume (pid, step, sig)
556      int pid, step;
557      enum target_signal
558        sig;
559 {
560   if (step)
561     {
562       hms_write_cr ("s");
563       expect ("Step>");
564
565       /* Force the next hms_wait to return a trap.  Not doing anything
566          about I/O from the target means that the user has to type "continue"
567          to see any.  FIXME, this should be fixed.  */
568       need_artificial_trap = 1;
569     }
570   else
571     {
572       hms_write_cr ("g");
573       expect ("g");
574     }
575 }
576
577 /* Wait until the remote machine stops, then return, storing status in
578    STATUS just as `wait' would.  */
579
580 int
581 hms_wait (pid, status)
582      int pid;
583      struct target_waitstatus *status;
584 {
585   /* Strings to look for.  '?' means match any single character.  Note
586      that with the algorithm we use, the initial character of the string
587      cannot recur in the string, or we will not find some cases of the
588      string in the input.  */
589
590   static char bpt[] = "At breakpoint:";
591
592   /* It would be tempting to look for "\n[__exit + 0x8]\n" but that
593      requires loading symbols with "yc i" and even if we did do that we
594      don't know that the file has symbols.  */
595   static char exitmsg[] = "HMS>";
596   char *bp = bpt;
597   char *ep = exitmsg;
598
599   /* Large enough for either sizeof (bpt) or sizeof (exitmsg) chars.
600    */
601   char swallowed[50];
602
603   /* Current position in swallowed.  */
604   char *swallowed_p = swallowed;
605
606   int ch;
607   int ch_handled;
608   int old_timeout = timeout;
609   int
610     old_immediate_quit = immediate_quit;
611   int swallowed_cr = 0;
612
613   status->kind = TARGET_WAITKIND_EXITED;
614   status->value.integer = 0;
615
616   if (need_artificial_trap != 0)
617     {
618       status->kind =
619         TARGET_WAITKIND_STOPPED;
620       status->value.sig = TARGET_SIGNAL_TRAP;
621       need_artificial_trap--;
622       return 0;
623     }
624
625   timeout = 5;                  /* Don't time out for a while - user program is running.
626                                  */
627   immediate_quit = 1;           /* Helps ability to QUIT */
628   while (1)
629     {
630       QUIT;                     /* Let user quit and leave process running */
631       ch_handled = 0;
632       ch = readchar ();
633       if (ch == *bp)
634         {
635           bp++;
636           if (*bp == '\0')
637             break;
638           ch_handled = 1;
639
640           *swallowed_p++ = ch;
641         }
642       else
643         {
644           bp = bpt;
645         }
646       if
647         (ch == *ep || *ep == '?')
648         {
649           ep++;
650           if (*ep == '\0')
651             break;
652
653           if (!ch_handled)
654             *swallowed_p++ = ch;
655           ch_handled =
656             1;
657         }
658       else
659         {
660           ep = exitmsg;
661         }
662
663       if (!ch_handled)
664         {
665           char *p;
666
667           /* Print out any characters which have been swallowed.  */
668           for (p = swallowed; p < swallowed_p; ++p)
669             putchar_unfiltered (*p);
670           swallowed_p = swallowed;
671
672           if ((ch != '\r' && ch != '\n') || swallowed_cr > 10)
673             {
674               putchar_unfiltered (ch);
675               swallowed_cr = 10;
676             }
677           swallowed_cr++;
678
679         }
680     }
681   if (*bp == '\0')
682     {
683       status->kind = TARGET_WAITKIND_STOPPED;
684       status->value.sig = TARGET_SIGNAL_TRAP;
685       expect_prompt ();
686     }
687   else
688     {
689       status->kind = TARGET_WAITKIND_EXITED;
690       status->value.integer =
691         TARGET_SIGNAL_STOP;
692     }
693
694   timeout = old_timeout;
695   immediate_quit = old_immediate_quit;
696   return
697     0;
698 }
699
700 /* Return the name of register number REGNO in the form input and
701    output by hms.
702
703    Returns a pointer to a static buffer containing the answer.  */
704 static char *
705 get_reg_name (regno)
706      int regno;
707 {
708   static char *rn[] =
709   REGISTER_NAMES;
710
711   return rn[regno];
712 }
713
714 /* Read the remote registers.  */
715
716 static int
717 gethex (length, start, ok)
718      unsigned int length;
719      char *start;
720      int *ok;
721 {
722   int result = 0;
723
724   while (length--)
725     {
726       result <<= 4;
727       if (*start >= 'a' && *start <= 'f')
728         {
729           result += *start - 'a' + 10;
730         }
731       else if (*start >= 'A' &&
732                *start <= 'F')
733         {
734           result += *start - 'A' + 10;
735         }
736       else if
737         (*start >= '0' && *start <= '9')
738         {
739           result += *start - '0';
740         }
741       else
742         *ok = 0;
743       start++;
744
745     }
746   return result;
747 }
748 static int
749 timed_read (buf, n, timeout)
750      char
751       *buf;
752
753 {
754   int i;
755   char c;
756
757   i = 0;
758   while (i < n)
759     {
760       c = readchar ();
761
762       if (c == 0)
763         return i;
764       buf[i] = c;
765       i++;
766
767     }
768   return i;
769 }
770
771 hms_write (a, l)
772      char *a;
773 {
774   int i;
775
776   SERIAL_WRITE (desc, a, l);
777
778   if (!quiet || remote_debug)
779     {
780       printf_unfiltered ("<");
781       for (i = 0; i < l; i++)
782         {
783           printf_unfiltered ("%c", a[i]);
784         }
785       printf_unfiltered (">");
786     }
787 }
788
789 hms_write_cr (s)
790      char *s;
791 {
792   hms_write (s, strlen (s));
793   hms_write ("\r\n", 2);
794 }
795
796 #ifdef GDB_TARGET_IS_H8500
797
798 /* H8/500 monitor reg dump looks like:
799
800    HMS>r
801    PC:8000 SR:070C .7NZ.. CP:00 DP:00 EP:00 TP:00 BR:00
802    R0-R7: FF5A 0001 F4FE F500 0000 F528 F528 F4EE
803    HMS>
804
805
806  */
807
808 supply_val (n, size, ptr, segptr)
809      int n;
810      int size;
811      char *ptr;
812      char *segptr;
813 {
814   int ok;
815   char raw[4];
816   switch (size)
817     {
818     case 2:
819       raw[0] = gethex (2, ptr, &ok);
820       raw[1] = gethex (2, ptr + 2, &ok);
821       supply_register (n, raw);
822       break;
823     case 1:
824       raw[0] = gethex (2, ptr, &ok);
825       supply_register (n, raw);
826       break;
827     case 4:
828       {
829         int v = gethex (4, ptr, &ok);
830         v |= gethex (2, segptr, &ok) << 16;
831         raw[0] = 0;
832         raw[1] = (v >> 16) & 0xff;
833         raw[2] = (v >> 8) & 0xff;
834         raw[3] = (v >> 0) & 0xff;
835         supply_register (n, raw);
836       }
837     }
838
839 }
840 static void
841 hms_fetch_register (dummy)
842      int dummy;
843 {
844 #define REGREPLY_SIZE 108
845   char linebuf[REGREPLY_SIZE + 1];
846   int i;
847   int s;
848   int gottok;
849
850   LONGEST reg[NUM_REGS];
851   check_open ();
852
853   do
854     {
855
856       hms_write_cr ("r");
857       expect ("r");
858       s = timed_read (linebuf + 1, REGREPLY_SIZE, 1);
859
860       linebuf[REGREPLY_SIZE] = 0;
861       gottok = 0;
862       if (linebuf[3] == 'P' &&
863           linebuf[4] == 'C' &&
864           linebuf[5] == ':' &&
865           linebuf[105] == 'H' &&
866           linebuf[106] == 'M' &&
867           linebuf[107] == 'S')
868         {
869
870           /*
871              012
872              r**
873              -------1---------2---------3---------4---------5-----
874              345678901234567890123456789012345678901234567890123456
875              PC:8000 SR:070C .7NZ.. CP:00 DP:00 EP:00 TP:00 BR:00**
876              ---6---------7---------8---------9--------10----
877              789012345678901234567890123456789012345678901234
878              R0-R7: FF5A 0001 F4FE F500 0000 F528 F528 F4EE**
879
880              56789
881              HMS>
882            */
883           gottok = 1;
884
885
886           supply_val (PC_REGNUM, 4, linebuf + 6, linebuf + 29);
887
888           supply_val (CCR_REGNUM, 2, linebuf + 14);
889           supply_val (SEG_C_REGNUM, 1, linebuf + 29);
890           supply_val (SEG_D_REGNUM, 1, linebuf + 35);
891           supply_val (SEG_E_REGNUM, 1, linebuf + 41);
892           supply_val (SEG_T_REGNUM, 1, linebuf + 47);
893           for (i = 0; i < 8; i++)
894             {
895               static int sr[8] =
896               {35, 35, 35, 35,
897                41, 41, 47, 47};
898
899               char raw[4];
900               char *src = linebuf + 64 + 5 * i;
901               char *segsrc = linebuf + sr[i];
902               supply_val (R0_REGNUM + i, 2, src);
903               supply_val (PR0_REGNUM + i, 4, src, segsrc);
904             }
905         }
906       if (!gottok)
907         {
908           hms_write_cr ("");
909           expect ("HMS>");
910         }
911     }
912   while (!gottok);
913 }
914 #endif
915
916 #ifdef GDB_TARGET_IS_H8300
917 static void
918 hms_fetch_register (dummy)
919      int dummy;
920 {
921 #define REGREPLY_SIZE 79
922   char linebuf[REGREPLY_SIZE + 1];
923   int i;
924   int s;
925   int gottok;
926
927   unsigned LONGEST reg[NUM_REGS];
928
929   check_open ();
930
931   do
932     {
933       hms_write_cr ("r");
934
935       s = timed_read (linebuf, 1, 1);
936
937       while (linebuf[0] != 'r')
938         s = timed_read (linebuf, 1, 1);
939
940       s = timed_read (linebuf + 1, REGREPLY_SIZE - 1, 1);
941
942       linebuf[REGREPLY_SIZE] = 0;
943       gottok = 0;
944       if (linebuf[0] == 'r' &&
945           linebuf[3] == 'P' &&
946           linebuf[4] == 'C' &&
947           linebuf[5] == '=' &&
948           linebuf[75] == 'H' &&
949           linebuf[76] == 'M' &&
950           linebuf[77] == 'S')
951         {
952           /*
953              PC=XXXX CCR=XX:XXXXXXXX R0-R7= XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX
954              5436789012345678901234567890123456789012345678901234567890123456789012
955              0      1         2         3         4         5         6
956            */
957           gottok = 1;
958
959           reg[PC_REGNUM] = gethex (4, linebuf + 6, &gottok);
960           reg[CCR_REGNUM] = gethex (2, linebuf + 15, &gottok);
961           for (i = 0; i < 8; i++)
962             {
963               reg[i] = gethex (4, linebuf + 34 + 5 * i, &gottok);
964             }
965         }
966     }
967   while (!gottok);
968   for (i = 0; i < NUM_REGS; i++)
969     {
970       char swapped[2];
971
972       swapped[1] = reg[i];
973       swapped[0] = (reg[i]) >> 8;
974
975       supply_register (i, swapped);
976     }
977 }
978 #endif
979 /* Store register REGNO, or all if REGNO == -1.
980    Return errno value.  */
981 static void
982 hms_store_register (regno)
983      int regno;
984 {
985   if (regno == -1)
986     {
987       for (regno = 0; regno < NUM_REGS; regno++)
988         {
989           hms_store_register (regno);
990         }
991     }
992   else
993     {
994       char *name = get_reg_name (regno);
995       char buffer[100];
996       /* Some regs dont really exist */
997       if (!(name[0] == 'p' && name[1] == 'r')
998           && !(name[0] == 'c' && name[1] == 'y')
999           && !(name[0] == 't' && name[1] == 'i')
1000           && !(name[0] == 'i' && name[1] == 'n'))
1001         {
1002           sprintf (buffer, "r %s=%x", name, read_register (regno));
1003           hms_write_cr (buffer);
1004           expect_prompt ();
1005         }
1006     }
1007 }
1008
1009
1010 /* Get ready to modify the registers array.  On machines which store
1011    individual registers, this doesn't need to do anything.  On machines
1012    which store all the registers in one fell swoop, this makes sure
1013    that registers contains all the registers from the program being
1014    debugged.  */
1015
1016 void
1017 hms_prepare_to_store ()
1018 {
1019   /* Do nothing, since we can store individual regs */
1020 }
1021
1022 static CORE_ADDR
1023 translate_addr (addr)
1024      CORE_ADDR addr;
1025 {
1026
1027   return (addr);
1028
1029 }
1030
1031
1032 int
1033 hms_xfer_inferior_memory (memaddr, myaddr, len, write, target)
1034      CORE_ADDR memaddr;
1035      char *myaddr;
1036      int len;
1037      int write;
1038      struct target_ops *target; /* ignored */
1039 {
1040
1041   return len;
1042 }
1043
1044 int
1045 hms_write_inferior_memory (memaddr, myaddr, len)
1046      CORE_ADDR memaddr;
1047      unsigned char *myaddr;
1048      int len;
1049 {
1050   bfd_vma addr;
1051   int done;
1052   int todo;
1053   char buffer[100];
1054   done = 0;
1055   hms_write_cr (".");
1056   expect_prompt ();
1057   while (done < len)
1058     {
1059       char *ptr = buffer;
1060       int thisgo;
1061       int idx;
1062
1063       thisgo = len - done;
1064       if (thisgo > 20)
1065         thisgo = 20;
1066
1067       sprintf (ptr, "M.B %4x =", memaddr + done);
1068       ptr += 10;
1069       for (idx = 0; idx < thisgo; idx++)
1070         {
1071           sprintf (ptr, "%2x ", myaddr[idx + done]);
1072           ptr += 3;
1073         }
1074       hms_write_cr (buffer);
1075       expect_prompt ();
1076       done += thisgo;
1077     }
1078 }
1079
1080 void
1081 hms_files_info ()
1082 {
1083   char *file = "nothing";
1084
1085   if (exec_bfd)
1086     file = bfd_get_filename (exec_bfd);
1087
1088   if (exec_bfd)
1089 #ifdef __GO32__
1090     printf_filtered ("\tAttached to DOS asynctsr and running program %s\n", file);
1091 #else
1092     printf_filtered ("\tAttached to %s at %d baud and running program %s\n", dev_name, baudrate, file);
1093 #endif
1094   printf_filtered ("\ton an H8/300 processor.\n");
1095 }
1096
1097 /* Copy LEN bytes of data from debugger memory at MYADDR
1098    to inferior's memory at MEMADDR.  Returns errno value.
1099    * sb/sh instructions don't work on unaligned addresses, when TU=1.
1100  */
1101
1102 /* Read LEN bytes from inferior memory at MEMADDR.  Put the result
1103    at debugger address MYADDR.  Returns errno value.  */
1104 int
1105 hms_read_inferior_memory (memaddr, myaddr, len)
1106      CORE_ADDR memaddr;
1107      char *myaddr;
1108      int len;
1109 {
1110   /* Align to nearest low 16 bits */
1111   int i;
1112
1113   CORE_ADDR start = memaddr;
1114   CORE_ADDR end = memaddr + len - 1;
1115
1116   int ok = 1;
1117
1118   /*
1119      AAAA: XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX '................'
1120      012345678901234567890123456789012345678901234567890123456789012345
1121      0         1         2         3         4         5         6
1122    */
1123   char buffer[66];
1124
1125   if (memaddr & 0xf)
1126     abort ();
1127   if (len != 16)
1128     abort ();
1129
1130   sprintf (buffer, "m %4x %4x", start & 0xffff, end & 0xffff);
1131
1132   flush ();
1133   hms_write_cr (buffer);
1134   /* drop the echo and newline */
1135   for (i = 0; i < 13; i++)
1136     readchar ();
1137
1138   /* Grab the lines as they come out and fill the area */
1139   /* Skip over cr */
1140   while (1)
1141     {
1142       int p;
1143       int i;
1144       int addr;
1145       size_t idx;
1146
1147       char byte[16];
1148
1149       buffer[0] = readchar ();
1150       while (buffer[0] == '\r'
1151              || buffer[0] == '\n')
1152         buffer[0] = readchar ();
1153
1154       if (buffer[0] == 'M')
1155         break;
1156
1157       for (i = 1; i < 50; i++)
1158         {
1159           buffer[i] = readchar ();
1160         }
1161       /* sometimes we loose characters in the ascii representation of the 
1162          data.  I don't know where.  So just scan for the end of line */
1163       i = readchar ();
1164       while (i != '\n' && i != '\r')
1165         i = readchar ();
1166
1167       /* Now parse the line */
1168
1169       addr = gethex (4, buffer, &ok);
1170       idx = 6;
1171       for (p = 0; p < 16; p += 2)
1172         {
1173           byte[p] = gethex (2, buffer + idx, &ok);
1174           byte[p + 1] = gethex (2, buffer + idx + 2, &ok);
1175           idx += 5;
1176         }
1177
1178       for (p = 0; p < 16; p++)
1179         {
1180           if (addr + p >= memaddr &&
1181               addr + p < memaddr + len)
1182             {
1183               myaddr[(addr + p) - memaddr] = byte[p];
1184
1185             }
1186
1187         }
1188     }
1189 #ifdef GDB_TARGET_IS_H8500
1190   expect ("ore>");
1191 #endif
1192 #ifdef GDB_TARGET_IS_H8300
1193   expect ("emory>");
1194 #endif
1195   hms_write_cr (".");
1196
1197   expect_prompt ();
1198   return len;
1199 }
1200
1201
1202
1203 #define MAX_BREAKS      16
1204 static int num_brkpts = 0;
1205 static int
1206 hms_insert_breakpoint (addr, save)
1207      CORE_ADDR addr;
1208      char *save;                /* Throw away, let hms save instructions */
1209 {
1210   check_open ();
1211
1212   if (num_brkpts < MAX_BREAKS)
1213     {
1214       char buffer[100];
1215
1216       num_brkpts++;
1217       sprintf (buffer, "b %x", addr & 0xffff);
1218       hms_write_cr (buffer);
1219       expect_prompt ();
1220       return (0);
1221     }
1222   else
1223     {
1224       fprintf_filtered (gdb_stderr,
1225                       "Too many break points, break point not installed\n");
1226       return (1);
1227     }
1228
1229 }
1230 static int
1231 hms_remove_breakpoint (addr, save)
1232      CORE_ADDR addr;
1233      char *save;                /* Throw away, let hms save instructions */
1234 {
1235   if (num_brkpts > 0)
1236     {
1237       char buffer[100];
1238
1239       num_brkpts--;
1240       sprintf (buffer, "b - %x", addr & 0xffff);
1241       hms_write_cr (buffer);
1242       expect_prompt ();
1243
1244     }
1245   return (0);
1246 }
1247
1248 /* Clear the hmss notion of what the break points are */
1249 static int
1250 hms_clear_breakpoints ()
1251 {
1252
1253   if (is_open)
1254     {
1255       hms_write_cr ("b -");
1256       expect_prompt ();
1257     }
1258   num_brkpts = 0;
1259 }
1260 static void
1261 hms_mourn ()
1262 {
1263   hms_clear_breakpoints ();
1264   unpush_target (&hms_ops);
1265   generic_mourn_inferior ();
1266 }
1267
1268 /* Put a command string, in args, out to the hms.  The hms is assumed to
1269    be in raw mode, all writing/reading done through desc.
1270    Ouput from the hms is placed on the users terminal until the
1271    prompt from the hms is seen.
1272    FIXME: Can't handle commands that take input.  */
1273
1274 void
1275 hms_com (args, fromtty)
1276      char *args;
1277      int fromtty;
1278 {
1279   check_open ();
1280
1281   if (!args)
1282     return;
1283
1284   /* Clear all input so only command relative output is displayed */
1285
1286   hms_write_cr (args);
1287 /*  hms_write ("\030", 1); */
1288   expect_prompt ();
1289 }
1290
1291 static void
1292 hms_open (name, from_tty)
1293      char *name;
1294      int from_tty;
1295 {
1296   unsigned int prl;
1297   char *p;
1298
1299   if (name == 0)
1300     {
1301       name = "";
1302     }
1303   if (is_open)
1304     hms_close (0);
1305   dev_name = strdup (name);
1306
1307   if (!(desc = SERIAL_OPEN (dev_name)))
1308     perror_with_name ((char *) dev_name);
1309
1310   SERIAL_RAW (desc);
1311   is_open = 1;
1312   push_target (&hms_ops);
1313   dcache_ptr = dcache_init (hms_read_inferior_memory,
1314                             hms_write_inferior_memory);
1315   remote_dcache = 1;
1316   /* Hello?  Are you there?  */
1317   SERIAL_WRITE (desc, "\r\n", 2);
1318   expect_prompt ();
1319
1320   /* Clear any break points */
1321   hms_clear_breakpoints ();
1322
1323   printf_filtered ("Connected to remote board running HMS monitor.\n");
1324   add_commands ();
1325 /*  hms_drain (); */
1326 }
1327
1328 /* Define the target subroutine names */
1329
1330 struct target_ops hms_ops =
1331 {
1332   "hms", "Remote HMS monitor",
1333   "Use the H8 evaluation board running the HMS monitor connected\n\
1334 by a serial line.",
1335
1336   hms_open, hms_close,
1337   0, hms_detach, hms_resume, hms_wait,  /* attach */
1338   hms_fetch_register, hms_store_register,
1339   hms_prepare_to_store,
1340   hms_xfer_inferior_memory,
1341   hms_files_info,
1342   hms_insert_breakpoint, hms_remove_breakpoint,         /* Breakpoints */
1343   0, 0, 0, 0, 0,                /* Terminal handling */
1344   hms_kill,                     /* FIXME, kill */
1345   gr_load_image,
1346   0,                            /* lookup_symbol */
1347   hms_create_inferior,          /* create_inferior */
1348   hms_mourn,                    /* mourn_inferior FIXME */
1349   0,                            /* can_run */
1350   0,                            /* notice_signals */
1351   0,                            /* to_stop */
1352   process_stratum, 0,           /* next */
1353   1, 1, 1, 1, 1,                /* all mem, mem, stack, regs, exec */
1354   0, 0,                         /* Section pointers */
1355   OPS_MAGIC,                    /* Always the last thing */
1356 };
1357
1358 hms_quiet ()                    /* FIXME - this routine can be removed after Dec '94 */
1359 {
1360   quiet = !quiet;
1361   if (quiet)
1362     printf_filtered ("Snoop disabled\n");
1363   else
1364     printf_filtered ("Snoop enabled\n");
1365
1366   printf_filtered ("`snoop' is obsolete, please use `set remotedebug'.\n");
1367 }
1368
1369 hms_device (s)
1370      char *s;
1371 {
1372   if (s)
1373     {
1374       dev_name = get_word (&s);
1375     }
1376 }
1377
1378 static
1379 hms_speed (s)
1380      char *s;
1381 {
1382   check_open ();
1383
1384   if (s)
1385     {
1386       char buffer[100];
1387       int newrate = atoi (s);
1388       int which = 0;
1389
1390       if (SERIAL_SETBAUDRATE (desc, newrate))
1391         error ("Can't use %d baud\n", newrate);
1392
1393       printf_filtered ("Checking target is in sync\n");
1394
1395       printf_filtered ("Sending commands to set target to %d\n",
1396                        baudrate);
1397
1398       sprintf (buffer, "tm %d. N 8 1", baudrate);
1399       hms_write_cr (buffer);
1400     }
1401 }
1402
1403 /***********************************************************************/
1404
1405 static void
1406 hms_drain (args, fromtty)
1407      char *args;
1408      int fromtty;
1409 {
1410   int c;
1411   while (1)
1412     {
1413       c = SERIAL_READCHAR (desc, 1);
1414       if (c == SERIAL_TIMEOUT)
1415         break;
1416       if (c == SERIAL_ERROR)
1417         break;
1418       if (c > ' ' && c < 127)
1419         printf ("%c", c & 0xff);
1420       else
1421         printf ("<%x>", c & 0xff);
1422     }
1423 }
1424
1425 static void
1426 add_commands ()
1427 {
1428
1429   add_com ("hms_drain", class_obscure, hms_drain,
1430            "Drain pending hms text buffers.");
1431 }
1432
1433 static void
1434 remove_commands ()
1435 {
1436   extern struct cmd_list_element *cmdlist;
1437   delete_cmd ("hms-drain", &cmdlist);
1438 }
1439
1440
1441 void
1442 _initialize_remote_hms ()
1443 {
1444   add_target (&hms_ops);
1445
1446   add_com ("hms <command>", class_obscure, hms_com,
1447            "Send a command to the HMS monitor.");
1448
1449   /* FIXME - hms_quiet and `snoop' can be removed after Dec '94 */
1450   add_com ("snoop", class_obscure, hms_quiet,
1451            "Show what commands are going to the monitor (OBSOLETE - see 'set remotedebug')");
1452
1453   add_com ("device", class_obscure, hms_device,
1454            "Set the terminal line for HMS communications");
1455
1456   add_com ("speed", class_obscure, hms_speed,
1457            "Set the terminal line speed for HMS communications");
1458
1459   dev_name = NULL;
1460 }
1461 #endif
1462