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