* remote-bug.c: rename quiet to bug88k_snoop.
[platform/upstream/binutils.git] / gdb / remote-bug.c
1 /* Remote debugging interface for Motorola's MVME187BUG monitor, an embedded
2    monitor for the m88k.
3
4    Copyright 1992, 1993 Free Software Foundation, Inc.
5    Contributed by Cygnus Support.  Written by K. Richard Pixley.
6
7 This file is part of GDB.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
22
23 #include "defs.h"
24 #include "inferior.h"
25 #include "wait.h"
26 #include "value.h"
27
28 #include <string.h>
29 #include <ctype.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <setjmp.h>
33 #include <errno.h>
34
35 #include "terminal.h"
36 #include "target.h"
37 #include "gdbcore.h"
38 #include "serial.h"
39 #include "gdbcmd.h"
40
41 extern int sleep();
42 extern int remque();
43 extern int insque();
44
45 /* External data declarations */
46 extern int stop_soon_quietly;   /* for wait_for_inferior */
47
48 /* Forward data declarations */
49 extern struct target_ops bug_ops;       /* Forward declaration */
50
51 /* Forward function declarations */
52 static void bug_close ();
53 static int bug_clear_breakpoints ();
54 static void bug_write_cr();
55
56 #if __STDC__ == 1
57
58 static int bug_read_inferior_memory (CORE_ADDR memaddr, char *myaddr, int len);
59 static int bug_write_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len);
60
61 #else
62
63 static int bug_read_inferior_memory ();
64 static int bug_write_inferior_memory ();
65
66 #endif /* not __STDC__ */
67
68 /* To be silent, or to loudly echo all input and output to and from
69    the target.  */
70
71 static int bug88k_snoop = 0;
72
73 /* This is the serial descriptor to our target.  */
74
75 static serial_t desc = NULL;
76
77 /* This variable is somewhat arbitrary.  It's here so that it can be
78    set from within a running gdb.  */
79
80 static int srec_max_retries = 3;
81
82 /* Each S-record download to the target consists of an S0 header
83    record, some number of S3 data records, and one S7 termination
84    record.  I call this download a "frame".  Srec_frame says how many
85    bytes will be represented in each frame.  */
86
87 static int srec_frame = 160;
88
89 /* This variable determines how many bytes will be represented in each
90    S3 s-record.  */
91
92 static int srec_bytes = 40;
93
94 /* At one point it appeared to me as though the bug monitor could not
95    really be expected to receive two sequential characters at 9600
96    baud reliably.  Echo-pacing is an attempt to force data across the
97    line even in this condition.  Specifically, in echo-pace mode, each
98    character is sent one at a time and we look for the echo before
99    sending the next.  This is excruciatingly slow.  */
100
101 static int srec_echo_pace = 0;
102
103 /* How long to wait after an srec for a possible error message.
104    Similar to the above, I tried sleeping after sending each S3 record
105    in hopes that I might actually see error messages from the bug
106    monitor.  This might actually work if we were to use sleep
107    intervals smaller than 1 second.  */
108
109 static int srec_sleep = 0;
110
111 /* Every srec_noise records, flub the checksum.  This is a debugging
112    feature.  Set the variable to something other than 1 in order to
113    inject *deliberate* checksum errors.  One might do this if one
114    wanted to test error handling and recovery.  */
115
116 static int srec_noise = 0;
117
118 /***********************************************************************/
119 /* Caching stuff stolen from remote-nindy.c  */
120
121 /* The data cache records all the data read from the remote machine
122    since the last time it stopped.
123
124    Each cache block holds LINE_SIZE bytes of data
125    starting at a multiple-of-LINE_SIZE address.  */
126
127 #define LINE_SIZE_POWER 4
128 #define LINE_SIZE (1<<LINE_SIZE_POWER)  /* eg 1<<3 == 8 */
129 #define LINE_SIZE_MASK ((LINE_SIZE-1))  /* eg 7*2+1= 111*/
130 #define DCACHE_SIZE 64          /* Number of cache blocks */
131 #define XFORM(x)  ((x&LINE_SIZE_MASK)>>2)
132 struct dcache_block
133   {
134     struct dcache_block *next, *last;
135     unsigned int addr;          /* Address for which data is recorded.  */
136     int data[LINE_SIZE / sizeof (int)];
137   };
138
139 struct dcache_block dcache_free, dcache_valid;
140
141 /* Free all the data cache blocks, thus discarding all cached data.  */
142 static
143 void
144 dcache_flush ()
145 {
146   register struct dcache_block *db;
147
148   while ((db = dcache_valid.next) != &dcache_valid)
149     {
150       remque (db);
151       insque (db, &dcache_free);
152     }
153 }
154
155 /*
156  * If addr is present in the dcache, return the address of the block
157  * containing it.
158  */
159 static
160 struct dcache_block *
161 dcache_hit (addr)
162      unsigned int addr;
163 {
164   register struct dcache_block *db;
165
166   if (addr & 3)
167     abort ();
168
169   /* Search all cache blocks for one that is at this address.  */
170   db = dcache_valid.next;
171   while (db != &dcache_valid)
172     {
173       if ((addr & ~LINE_SIZE_MASK) == db->addr)
174         return db;
175       db = db->next;
176     }
177   return NULL;
178 }
179
180 /*  Return the int data at address ADDR in dcache block DC.  */
181 static
182 int
183 dcache_value (db, addr)
184      struct dcache_block *db;
185      unsigned int addr;
186 {
187   if (addr & 3)
188     abort ();
189   return (db->data[XFORM (addr)]);
190 }
191
192 /* Get a free cache block, put or keep it on the valid list,
193    and return its address.  The caller should store into the block
194    the address and data that it describes, then remque it from the
195    free list and insert it into the valid list.  This procedure
196    prevents errors from creeping in if a ninMemGet is interrupted
197    (which used to put garbage blocks in the valid list...).  */
198 static
199 struct dcache_block *
200 dcache_alloc ()
201 {
202   register struct dcache_block *db;
203
204   if ((db = dcache_free.next) == &dcache_free)
205     {
206       /* If we can't get one from the free list, take last valid and put
207          it on the free list.  */
208       db = dcache_valid.last;
209       remque (db);
210       insque (db, &dcache_free);
211     }
212
213   remque (db);
214   insque (db, &dcache_valid);
215   return (db);
216 }
217
218 /* Return the contents of the word at address ADDR in the remote machine,
219    using the data cache.  */
220 static
221 int
222 dcache_fetch (addr)
223      CORE_ADDR addr;
224 {
225   register struct dcache_block *db;
226
227   db = dcache_hit (addr);
228   if (db == 0)
229     {
230       db = dcache_alloc ();
231       immediate_quit++;
232       bug_read_inferior_memory (addr & ~LINE_SIZE_MASK, (unsigned char *) db->data, LINE_SIZE);
233       immediate_quit--;
234       db->addr = addr & ~LINE_SIZE_MASK;
235       remque (db);              /* Off the free list */
236       insque (db, &dcache_valid);       /* On the valid list */
237     }
238   return (dcache_value (db, addr));
239 }
240
241 /* Write the word at ADDR both in the data cache and in the remote machine.  */
242 static void
243 dcache_poke (addr, data)
244      CORE_ADDR addr;
245      int data;
246 {
247   register struct dcache_block *db;
248
249   /* First make sure the word is IN the cache.  DB is its cache block.  */
250   db = dcache_hit (addr);
251   if (db == 0)
252     {
253       db = dcache_alloc ();
254       immediate_quit++;
255       bug_write_inferior_memory (addr & ~LINE_SIZE_MASK, (unsigned char *) db->data, LINE_SIZE);
256       immediate_quit--;
257       db->addr = addr & ~LINE_SIZE_MASK;
258       remque (db);              /* Off the free list */
259       insque (db, &dcache_valid);       /* On the valid list */
260     }
261
262   /* Modify the word in the cache.  */
263   db->data[XFORM (addr)] = data;
264
265   /* Send the changed word.  */
266   immediate_quit++;
267   bug_write_inferior_memory (addr, (unsigned char *) &data, 4);
268   immediate_quit--;
269 }
270
271 /* The cache itself. */
272 struct dcache_block the_cache[DCACHE_SIZE];
273
274 /* Initialize the data cache.  */
275 static void
276 dcache_init ()
277 {
278   register i;
279   register struct dcache_block *db;
280
281   db = the_cache;
282   dcache_free.next = dcache_free.last = &dcache_free;
283   dcache_valid.next = dcache_valid.last = &dcache_valid;
284   for (i = 0; i < DCACHE_SIZE; i++, db++)
285     insque (db, &dcache_free);
286 }
287
288 /***********************************************************************
289  * I/O stuff stolen from remote-eb.c
290  ***********************************************************************/
291
292 /* with a timeout of 2, we time out waiting for the prompt after an
293    s-record dump. */
294 static int timeout = 4;
295
296 static const char *dev_name;
297
298 /* Descriptor for I/O to remote machine.  Initialize it to -1 so that
299    bug_open knows that we don't have a file open when the program
300    starts.  */
301
302 static int is_open = 0;
303 static int
304 check_open ()
305 {
306   if (!is_open)
307     {
308       error ("remote device not open");
309     }
310
311   return(1);
312 }
313
314 #define ON      1
315 #define OFF     0
316
317 /* Read a character from the remote system, doing all the fancy
318    timeout stuff.  */
319 static int
320 readchar ()
321 {
322   int buf;
323
324   buf = SERIAL_READCHAR (desc, timeout);
325
326   if (buf == SERIAL_TIMEOUT)
327     error ("Timeout reading from remote system.");
328
329   if (bug88k_snoop)
330     printf ("%c", buf);
331
332   return buf & 0x7f;
333 }
334
335 static int
336 readchar_nofail ()
337 {
338   int buf;
339
340   buf = SERIAL_READCHAR (desc, timeout);
341   if (buf == SERIAL_TIMEOUT)
342     buf = 0;
343   if (bug88k_snoop)
344     if (buf)
345       printf ("%c", buf);
346     else
347       printf ("<timeout>");
348
349   return buf & 0x7f;
350
351 }
352
353 static int
354 pollchar()
355 {
356   int buf;
357
358   buf = SERIAL_READCHAR (desc, 0);
359   if (buf == SERIAL_TIMEOUT)
360     buf = 0;
361   if (bug88k_snoop)
362     if (buf)
363       printf ("%c", buf);
364     else
365       printf ("<empty poll>");
366
367   return buf & 0x7f;
368 }
369
370 /* Keep discarding input from the remote system, until STRING is found.
371    Let the user break out immediately.  */
372 static void
373 expect (string)
374      char *string;
375 {
376   char *p = string;
377
378   immediate_quit = 1;
379   for (;;)
380     {
381       if (readchar () == *p)
382         {
383           p++;
384           if (*p == '\0')
385             {
386               immediate_quit = 0;
387               return;
388             }
389         }
390       else
391         p = string;
392     }
393 }
394
395 /* Keep discarding input until we see the bug prompt.
396
397    The convention for dealing with the prompt is that you
398    o give your command
399    o *then* wait for the prompt.
400
401    Thus the last thing that a procedure does with the serial line
402    will be an expect_prompt().  Exception:  bug_resume does not
403    wait for the prompt, because the terminal is being handed over
404    to the inferior.  However, the next thing which happens after that
405    is a bug_wait which does wait for the prompt.
406    Note that this includes abnormal exit, e.g. error().  This is
407    necessary to prevent getting into states from which we can't
408    recover.  */
409 static void
410 expect_prompt ()
411 {
412   expect ("Bug>");
413 }
414
415 /* Get a hex digit from the remote system & return its value.
416    If ignore_space is nonzero, ignore spaces (not newline, tab, etc).  */
417 static int
418 get_hex_digit (ignore_space)
419      int ignore_space;
420 {
421   int ch;
422
423   for (;;)
424     {
425       ch = readchar ();
426       if (ch >= '0' && ch <= '9')
427         return ch - '0';
428       else if (ch >= 'A' && ch <= 'F')
429         return ch - 'A' + 10;
430       else if (ch >= 'a' && ch <= 'f')
431         return ch - 'a' + 10;
432       else if (ch != ' ' || !ignore_space)
433         {
434           expect_prompt ();
435           error ("Invalid hex digit from remote system.");
436         }
437     }
438 }
439
440 /* Get a byte from bug_desc and put it in *BYT.  Accept any number
441    leading spaces.  */
442 static void
443 get_hex_byte (byt)
444      char *byt;
445 {
446   int val;
447
448   val = get_hex_digit (1) << 4;
449   val |= get_hex_digit (0);
450   *byt = val;
451 }
452
453 /* Read a 32-bit hex word from the bug, preceded by a space  */
454 static long
455 get_hex_word ()
456 {
457   long val;
458   int j;
459
460   val = 0;
461   for (j = 0; j < 8; j++)
462     val = (val << 4) + get_hex_digit (j == 0);
463   return val;
464 }
465
466 /* Called when SIGALRM signal sent due to alarm() timeout.  */
467
468 /* Number of SIGTRAPs we need to simulate.  That is, the next
469    NEED_ARTIFICIAL_TRAP calls to bug_wait should just return
470    SIGTRAP without actually waiting for anything.  */
471
472 static int need_artificial_trap = 0;
473
474 void
475 bug_kill (arg, from_tty)
476      char *arg;
477      int from_tty;
478 {
479
480 }
481
482 /*
483  * Download a file specified in 'args', to the bug.
484  */
485
486 static void
487 bug_load (args, fromtty)
488      char *args;
489      int fromtty;
490 {
491   bfd *abfd;
492   asection *s;
493   char buffer[1024];
494
495   check_open ();
496
497   dcache_flush ();
498   inferior_pid = 0;
499   abfd = bfd_openr (args, 0);
500   if (!abfd)
501     {
502       printf_filtered ("Unable to open file %s\n", args);
503       return;
504     }
505
506   if (bfd_check_format (abfd, bfd_object) == 0)
507     {
508       printf_filtered ("File is not an object file\n");
509       return;
510     }
511
512   s = abfd->sections;
513   while (s != (asection *) NULL)
514     {
515       if (s->flags & SEC_LOAD)
516         {
517           int i;
518
519           char *buffer = xmalloc (srec_frame);
520
521           printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name, s->vma, s->vma + s->_raw_size);
522           fflush (stdout);
523           for (i = 0; i < s->_raw_size; i += srec_frame)
524             {
525               if (srec_frame > s->_raw_size - i)
526                 srec_frame = s->_raw_size - i;
527
528               bfd_get_section_contents (abfd, s, buffer, i, srec_frame);
529               bug_write_inferior_memory (s->vma + i, buffer, srec_frame);
530               printf_filtered ("*");
531               fflush (stdout);
532             }
533           printf_filtered ("\n");
534           free (buffer);
535         }
536       s = s->next;
537     }
538   sprintf (buffer, "rs ip %lx", (unsigned long) abfd->start_address);
539   bug_write_cr (buffer);
540   expect_prompt ();
541 }
542
543 /* This is called not only when we first attach, but also when the
544    user types "run" after having attached.  */
545 void
546 bug_create_inferior (execfile, args, env)
547      char *execfile;
548      char *args;
549      char **env;
550 {
551   int entry_pt;
552
553   if (args && *args)
554     error ("Can't pass arguments to remote bug process.");
555
556   if (execfile == 0 || exec_bfd == 0)
557     error ("No exec file specified");
558
559   entry_pt = (int) bfd_get_start_address (exec_bfd);
560   check_open ();
561
562   bug_kill (NULL, NULL);
563   bug_clear_breakpoints ();
564   init_wait_for_inferior ();
565   bug_write_cr ("");
566   expect_prompt ();
567
568   insert_breakpoints ();        /* Needed to get correct instruction in cache */
569   proceed (entry_pt, -1, 0);
570 }
571
572 static char *
573 get_word (p)
574      char **p;
575 {
576   char *s = *p;
577   char *word;
578   char *copy;
579   size_t len;
580
581   while (isspace (*s))
582     s++;
583
584   word = s;
585
586   len = 0;
587
588   while (*s && !isspace (*s))
589     {
590       s++;
591       len++;
592
593     }
594   copy = xmalloc (len + 1);
595   memcpy (copy, word, len);
596   copy[len] = 0;
597   *p = s;
598   return copy;
599 }
600
601 static int baudrate = 9600;
602
603 static void
604 bug_open (name, from_tty)
605      char *name;
606      int from_tty;
607 {
608   push_target (&bug_ops);
609
610   if (name == 0)
611     {
612       name = "";
613     }
614   if (is_open)
615     bug_close (0);
616   dev_name = strdup (name);
617
618   if (!(desc = SERIAL_OPEN (dev_name)))
619     perror_with_name ((char *) dev_name);
620
621   SERIAL_RAW (desc);
622   is_open = 1;
623
624   dcache_init ();
625
626   /* Hello?  Are you there?  */
627   SERIAL_WRITE (desc, "\r", 1);
628   expect_prompt ();
629
630   /* Clear any break points */
631   bug_clear_breakpoints ();
632
633   printf_filtered ("Connected to remote 187bug system.\n");
634 }
635
636 /* Close out all files and local state before this target loses control. */
637
638 static void
639 bug_close (quitting)
640      int quitting;
641 {
642   /* Clear any break points */
643   bug_clear_breakpoints ();
644
645   if (is_open)
646     SERIAL_CLOSE (desc);
647
648   is_open = 0;
649 }
650
651 /* Terminate the open connection to the remote debugger.
652    Use this when you want to detach and do something else
653    with your gdb.  */
654 void
655 bug_detach (args, from_tty)
656      char *args;
657      int from_tty;
658 {
659   if (is_open)
660     bug_clear_breakpoints ();
661
662   pop_target ();                /* calls bug_close to do the real work */
663
664   if (from_tty)
665     printf_filtered ("Ending remote %s debugging\n", target_shortname);
666 }
667
668 /* Tell the remote machine to resume.  */
669
670 void
671 bug_resume (pid, step, sig)
672      int pid, step, sig;
673 {
674   dcache_flush ();
675
676   if (step)
677     {
678       bug_write_cr("t");
679
680       /* Force the next bug_wait to return a trap.  Not doing anything
681        about I/O from the target means that the user has to type
682        "continue" to see any.  FIXME, this should be fixed.  */
683       need_artificial_trap = 1;
684     }
685   else
686       bug_write_cr ("g");
687
688   return;
689 }
690
691 /* Given a null terminated list of strings LIST, read the input until we find one of
692    them.  Return the index of the string found or -1 on error.  '?' means match
693    any single character. Note that with the algorithm we use, the initial
694    character of the string cannot recur in the string, or we will not find some
695    cases of the string in the input.  If PASSTHROUGH is non-zero, then
696    pass non-matching data on.  */
697
698 static int
699 multi_scan (list, passthrough)
700      char *list[];
701      int passthrough;
702 {
703   char *swallowed = NULL; /* holding area */
704   char *swallowed_p = swallowed; /* Current position in swallowed.  */
705   int ch;
706   int ch_handled;
707   int i;
708   int string_count;
709   int max_length;
710   char **plist;
711
712   /* Look through the strings.  Count them.  Find the largest one so we can
713      allocate a holding area.  */
714
715   for (max_length = string_count = i = 0;
716        list[i] != NULL;
717        ++i, ++string_count)
718     {
719       int length = strlen(list[i]);
720
721       if (length > max_length)
722         max_length = length;
723     }
724
725   /* if we have no strings, then something is wrong. */
726   if (string_count == 0)
727     return(-1);
728
729   /* otherwise, we will need a holding area big enough to hold almost two
730      copies of our largest string.  */
731   swallowed_p = swallowed = alloca(max_length << 1);
732
733   /* and a list of pointers to current scan points. */
734   plist = alloca(string_count * sizeof(*plist));
735
736   /* and initialize */
737   for (i = 0; i < string_count; ++i)
738     plist[i] = list[i];
739
740   for (ch = readchar(); /* loop forever */ ; ch = readchar())
741     {
742       QUIT; /* Let user quit and leave process running */
743       ch_handled = 0;
744
745       for (i = 0; i < string_count; ++i)
746         {
747           if (ch == *plist[i] || *plist[i] == '?')
748             {
749               ++plist[i];
750               if (*plist[i] == '\0')
751                 return(i);
752
753               if (!ch_handled)
754                 *swallowed_p++ = ch;
755
756               ch_handled = 1;
757             }
758           else
759             plist[i] = list[i];
760         }
761
762       if (!ch_handled)
763         {
764           char *p;
765
766           /* Print out any characters which have been swallowed.  */
767           if (passthrough)
768             {
769               for (p = swallowed; p < swallowed_p; ++p)
770                 putc (*p, stdout);
771
772               putc (ch, stdout);
773             }
774
775           swallowed_p = swallowed;
776         }
777     }
778
779   return(-1);
780 }
781
782 /* Wait until the remote machine stops, then return,
783    storing status in STATUS just as `wait' would.  */
784
785 static char *wait_strings[] = {
786   "At Breakpoint",
787   "Exception: Data Access Fault (Local Bus Timeout)",
788   "\r8???-Bug>",
789   NULL,
790 };
791
792 int
793 bug_wait (status)
794      WAITTYPE *status;
795 {
796   int old_timeout = timeout;
797   int old_immediate_quit = immediate_quit;
798
799   WSETEXIT ((*status), 0);
800
801   /* read off leftovers from resume so that the rest can be passed
802      back out as stdout.  */
803   if (need_artificial_trap == 0)
804     {
805       expect("Effective address: ");
806       (void) get_hex_word();
807       expect ("\r\n");
808     }
809
810   timeout = -1; /* Don't time out -- user program is running. */
811   immediate_quit = 1; /* Helps ability to QUIT */
812
813   switch (multi_scan(wait_strings, need_artificial_trap == 0))
814     {
815     case 0: /* breakpoint case */
816       WSETSTOP ((*status), SIGTRAP);
817       /* user output from the target can be discarded here. (?) */
818       expect_prompt();
819       break;
820
821     case 1: /* bus error */
822       WSETSTOP ((*status), SIGBUS);
823       /* user output from the target can be discarded here. (?) */
824       expect_prompt();
825       break;
826
827     case 2: /* normal case */
828       if (need_artificial_trap != 0)
829         {
830           /* stepping */
831           WSETSTOP ((*status), SIGTRAP);
832           need_artificial_trap--;
833           break;
834         }
835       else
836         {
837           /* exit case */
838           WSETEXIT ((*status), 0);
839           break;
840         }
841
842     case -1: /* trouble */
843     default:
844       fprintf_filtered (stderr,
845                         "Trouble reading target during wait\n");
846       break;
847     }
848
849   timeout = old_timeout;
850   immediate_quit = old_immediate_quit;
851   return 0;
852 }
853
854 /* Return the name of register number REGNO
855    in the form input and output by bug.
856
857    Returns a pointer to a static buffer containing the answer.  */
858 static char *
859 get_reg_name (regno)
860      int regno;
861 {
862   static char *rn[] = {
863     "r00", "r01", "r02", "r03", "r04", "r05", "r06", "r07",
864     "r08", "r09", "r10", "r11", "r12", "r13", "r14", "r15",
865     "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
866     "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
867
868     /* these get confusing because we omit a few and switch some ordering around. */
869
870     "cr01",  /* 32 = psr */
871     "fcr62", /* 33 = fpsr*/
872     "fcr63", /* 34 = fpcr */
873     "ip",                       /* this is something of a cheat. */
874   /* 35 = sxip */
875     "cr05", /* 36 = snip */
876     "cr06", /* 37 = sfip */
877   };
878
879   return rn[regno];
880 }
881
882 static int
883 bug_write (a, l)
884      char *a;
885      int l;
886 {
887   int i;
888
889   SERIAL_WRITE (desc, a, l);
890
891   if (bug88k_snoop)
892     for (i = 0; i < l; i++)
893       {
894         printf ("%c", a[i]);
895       }
896
897   return(0);
898 }
899
900 static void
901 bug_write_cr (s)
902      char *s;
903 {
904   bug_write (s, strlen (s));
905   bug_write ("\r", 1);
906   return;
907 }
908
909 #if 0 /* not currently used */
910 /* Read from remote while the input matches STRING.  Return zero on
911    success, -1 on failure.  */
912
913 static int
914 bug_scan (s)
915      char *s;
916 {
917   int c;
918
919   while (*s)
920     {
921       c = readchar();
922       if (c != *s++)
923         {
924           fflush(stdout);
925           printf("\nNext character is '%c' - %d and s is \"%s\".\n", c, c, --s);
926           return(-1);
927         }
928     }
929
930   return(0);
931 }
932 #endif /* never */
933
934 static int
935 bug_srec_write_cr (s)
936      char *s;
937 {
938   char *p = s;
939
940   if (srec_echo_pace)
941     for (p = s; *p; ++p)
942       {
943         if (bug88k_snoop)
944           printf ("%c", *p);
945
946         do
947           SERIAL_WRITE(desc, p, 1);
948         while (readchar_nofail() != *p);
949       }
950   else
951     {  
952       bug_write_cr (s);
953 /*       return(bug_scan (s) || bug_scan ("\n")); */
954     }
955
956   return(0);
957 }
958
959 /* Store register REGNO, or all if REGNO == -1. */
960
961 static void
962 bug_fetch_register(regno)
963      int regno;
964 {
965   REGISTER_TYPE regval;
966   check_open();
967
968   if (regno == -1)
969     {
970       int i;
971
972       for (i = 0; i < NUM_REGS; ++i)
973         bug_fetch_register(i);
974     }
975   else
976     {
977       bug_write("rs ", 3);
978       bug_write_cr(get_reg_name(regno));
979       expect("=");
980       regval = get_hex_word();
981       expect_prompt();
982
983       /* the following registers contain flag bits in the lower to bit slots.
984          Mask them off */
985       if (regno == PC_REGNUM    /* aka sxip */
986           || regno == NPC_REGNUM /* aka snip */
987           || regno == SFIP_REGNUM)      /* aka sfip */
988         regval &= ~0x3;
989
990       supply_register(regno, (char *) &regval);
991     }
992
993   return;
994 }
995
996 /* Store register REGNO, or all if REGNO == -1. */
997
998 static void
999 bug_store_register (regno)
1000      int regno;
1001 {
1002   char buffer[1024];
1003   check_open();
1004
1005   if (regno == -1)
1006     {
1007       int i;
1008
1009       for (i = 0; i < NUM_REGS; ++i)
1010         bug_store_register(i);
1011     }
1012   else
1013     {
1014       char *regname;
1015
1016       regname = (get_reg_name(regno));
1017
1018       sprintf(buffer, "rs %s %08x",
1019               regname,
1020               read_register(regno));
1021
1022       bug_write_cr(buffer);
1023       expect_prompt();
1024     }
1025
1026   return;
1027 }
1028
1029 /* Get ready to modify the registers array.  On machines which store
1030    individual registers, this doesn't need to do anything.  On machines
1031    which store all the registers in one fell swoop, this makes sure
1032    that registers contains all the registers from the program being
1033    debugged.  */
1034
1035 void
1036 bug_prepare_to_store ()
1037 {
1038   /* Do nothing, since we can store individual regs */
1039 }
1040
1041 /* Read a word from remote address ADDR and return it.
1042  * This goes through the data cache.
1043  */
1044 int
1045 bug_fetch_word (addr)
1046      CORE_ADDR addr;
1047 {
1048   return dcache_fetch (addr);
1049 }
1050
1051 /* Write a word WORD into remote address ADDR.
1052    This goes through the data cache.  */
1053
1054 void
1055 bug_store_word (addr, word)
1056      CORE_ADDR addr;
1057      int word;
1058 {
1059   dcache_poke (addr, word);
1060 }
1061
1062 int
1063 bug_xfer_inferior_memory (memaddr, myaddr, len, write, target)
1064      CORE_ADDR memaddr;
1065      char *myaddr;
1066      int len;
1067      int write;
1068      struct target_ops *target; /* ignored */
1069 {
1070   register int i;
1071
1072   /* Round starting address down to longword boundary.  */
1073   register CORE_ADDR addr;
1074
1075   /* Round ending address up; get number of longwords that makes.  */
1076   register int count;
1077
1078   /* Allocate buffer of that many longwords.  */
1079   register int *buffer;
1080
1081   addr = memaddr & -sizeof (int);
1082   count = (((memaddr + len) - addr) + sizeof (int) - 1) / sizeof (int);
1083
1084   buffer = (int *) alloca (count * sizeof (int));
1085
1086   if (write)
1087     {
1088       /* Fill start and end extra bytes of buffer with existing memory data.  */
1089
1090       if (addr != memaddr || len < (int) sizeof (int))
1091         {
1092           /* Need part of initial word -- fetch it.  */
1093           buffer[0] = bug_fetch_word (addr);
1094         }
1095
1096       if (count > 1)            /* FIXME, avoid if even boundary */
1097         {
1098           buffer[count - 1]
1099             = bug_fetch_word (addr + (count - 1) * sizeof (int));
1100         }
1101
1102       /* Copy data to be written over corresponding part of buffer */
1103
1104       bcopy (myaddr, (char *) buffer + (memaddr & (sizeof (int) - 1)), len);
1105
1106       /* Write the entire buffer.  */
1107
1108       for (i = 0; i < count; i++, addr += sizeof (int))
1109         {
1110           errno = 0;
1111           bug_store_word (addr, buffer[i]);
1112           if (errno)
1113             {
1114
1115               return 0;
1116             }
1117
1118         }
1119     }
1120   else
1121     {
1122       /* Read all the longwords */
1123       for (i = 0; i < count; i++, addr += sizeof (int))
1124         {
1125           errno = 0;
1126           buffer[i] = bug_fetch_word (addr);
1127           if (errno)
1128             {
1129               return 0;
1130             }
1131           QUIT;
1132         }
1133
1134       /* Copy appropriate bytes out of the buffer.  */
1135       bcopy ((char *) buffer + (memaddr & (sizeof (int) - 1)), myaddr, len);
1136     }
1137
1138   return len;
1139 }
1140
1141 static void
1142 start_load()
1143 {
1144   char *command;
1145
1146   command = (srec_echo_pace ? "lo 0 ;x" : "lo 0");
1147
1148   bug_write_cr (command);
1149   expect (command);
1150   expect ("\r\n");
1151   bug_srec_write_cr ("S0030000FC");
1152   return;
1153 }
1154
1155 /* This is an extremely vulnerable and fragile function.  I've made
1156    considerable attempts to make this deterministic, but I've
1157    certainly forgotten something.  The trouble is that S-records are
1158    only a partial file format, not a protocol.  Worse, apparently the
1159    m88k bug monitor does not run in real time while receiving
1160    S-records.  Hence, we must pay excruciating attention to when and
1161    where error messages are returned, and what has actually been sent.
1162
1163    Each call represents a chunk of memory to be sent to the target.
1164    We break that chunk into an S0 header record, some number of S3
1165    data records each containing srec_bytes, and an S7 termination
1166    record.  */
1167
1168 static char *srecord_strings[] = {
1169   "S-RECORD",
1170   "8???-Bug>",
1171   NULL,
1172 };
1173
1174 static int
1175 bug_write_inferior_memory (memaddr, myaddr, len)
1176      CORE_ADDR memaddr;
1177      unsigned char *myaddr;
1178      int len;
1179 {
1180   int done;
1181   int checksum;
1182   int x;
1183   int retries;
1184   char buffer[(srec_bytes + 8) << 1];
1185
1186   retries = 0;
1187
1188   do
1189     {
1190       done = 0;
1191
1192       if (retries > srec_max_retries)
1193         return(-1);
1194
1195       if (retries > 0)
1196         {
1197           if (bug88k_snoop)
1198             printf("\n<retrying...>\n");
1199
1200           /* This expect_prompt call is extremely important.  Without
1201              it, we will tend to resend our packet so fast that it
1202              will arrive before the bug monitor is ready to receive
1203              it.  This would lead to a very ugly resend loop.  */
1204
1205           expect_prompt();
1206         }
1207
1208       start_load();
1209
1210       while (done < len)
1211         {
1212           int thisgo;
1213           int idx;
1214           char *buf = buffer;
1215           CORE_ADDR address;
1216
1217           checksum = 0;
1218           thisgo = len - done;
1219           if (thisgo > srec_bytes)
1220             thisgo = srec_bytes;
1221
1222           address = memaddr + done;
1223           sprintf (buf, "S3%02X%08X", thisgo + 4 + 1, address);
1224           buf += 12;
1225
1226           checksum += (thisgo + 4 + 1
1227                        + (address & 0xff)
1228                        + ((address >>  8) & 0xff)
1229                        + ((address >> 16) & 0xff)
1230                        + ((address >> 24) & 0xff));
1231
1232           for (idx = 0; idx < thisgo; idx++)
1233             {
1234               sprintf (buf, "%02X", myaddr[idx + done]);
1235               checksum += myaddr[idx + done];
1236               buf += 2;
1237             }
1238
1239           if (srec_noise > 0)
1240             {
1241               /* FIXME-NOW: insert a deliberate error every now and then.
1242                  This is intended for testing/debugging the error handling
1243                  stuff.  */
1244               static int counter = 0;
1245               if (++counter > srec_noise)
1246                 {
1247                   counter = 0;
1248                   ++checksum;
1249                 }
1250             }
1251
1252           sprintf(buf, "%02X", ~checksum & 0xff);
1253           bug_srec_write_cr (buffer);
1254
1255           if (srec_sleep != 0)
1256             sleep(srec_sleep);
1257
1258           /* This pollchar is probably redundant to the multi_scan
1259              below.  Trouble is, we can't be sure when or where an
1260              error message will appear.  Apparently, when running at
1261              full speed from a typical sun4, error messages tend to
1262              appear to arrive only *after* the s7 record.   */
1263
1264           if ((x = pollchar()) != 0)
1265             {
1266               if (bug88k_snoop)
1267                 printf("\n<retrying...>\n");
1268
1269               ++retries;
1270
1271               /* flush any remaining input and verify that we are back
1272                  at the prompt level. */
1273               expect_prompt();
1274               /* start all over again. */
1275               start_load();
1276               done = 0;
1277               continue;
1278             }
1279
1280           done += thisgo;
1281         }
1282
1283       bug_srec_write_cr("S7060000000000F9");
1284       ++retries;
1285
1286       /* Having finished the load, we need to figure out whether we
1287          had any errors.  */
1288     } while (multi_scan(srecord_strings, 0) == 0);;
1289
1290   return(0);
1291 }
1292
1293 void
1294 bug_files_info ()
1295 {
1296   char *file = "nothing";
1297
1298   if (exec_bfd)
1299     file = bfd_get_filename (exec_bfd);
1300
1301   if (exec_bfd)
1302 #ifdef __GO32__
1303     printf_filtered ("\tAttached to DOS asynctsr and running program %s\n", file);
1304 #else
1305     printf_filtered ("\tAttached to %s at %d baud and running program %s\n", dev_name, baudrate, file);
1306 #endif
1307   printf_filtered ("\ton an m88k processor.\n");
1308 }
1309
1310 /* Copy LEN bytes of data from debugger memory at MYADDR
1311    to inferior's memory at MEMADDR.  Returns errno value.
1312  * sb/sh instructions don't work on unaligned addresses, when TU=1.
1313  */
1314
1315 /* Read LEN bytes from inferior memory at MEMADDR.  Put the result
1316    at debugger address MYADDR.  Returns errno value.  */
1317 static int
1318 bug_read_inferior_memory (memaddr, myaddr, len)
1319      CORE_ADDR memaddr;
1320      char *myaddr;
1321      int len;
1322 {
1323   char request[100];
1324   char *buffer;
1325   char *p;
1326   char type;
1327   char size;
1328   unsigned char c;
1329   unsigned int inaddr;
1330   unsigned int checksum;
1331
1332   sprintf(request, "du 0 %x:&%d", memaddr, len);
1333   bug_write_cr(request);
1334
1335   p = buffer = alloca(len);
1336
1337   /* scan up through the header */
1338   expect("S0030000FC");
1339
1340   while (p < buffer + len)
1341     {
1342       /* scan off any white space. */
1343       while (readchar() != 'S') ;;
1344
1345       /* what kind of s-rec? */
1346       type = readchar();
1347
1348       /* scan record size */
1349       get_hex_byte(&size);
1350       checksum = size;
1351       --size;
1352       inaddr = 0;
1353
1354       switch (type)
1355         {
1356         case '7':
1357         case '8':
1358         case '9':
1359           goto done;
1360
1361         case '3':
1362           get_hex_byte(&c);
1363           inaddr = (inaddr << 8) + c;
1364           checksum += c;
1365           --size;
1366           /* intentional fall through */
1367         case '2':
1368           get_hex_byte(&c);
1369           inaddr = (inaddr << 8) + c;
1370           checksum += c;
1371           --size;
1372           /* intentional fall through */
1373         case '1':
1374           get_hex_byte(&c);
1375           inaddr = (inaddr << 8) + c;
1376           checksum += c;
1377           --size;
1378           get_hex_byte(&c);
1379           inaddr = (inaddr << 8) + c;
1380           checksum += c;
1381           --size;
1382           break;
1383
1384         default:
1385           /* bonk */
1386           error("reading s-records.");
1387         }
1388
1389       if (inaddr < memaddr
1390           || (memaddr + len) < (inaddr + size))
1391         error("srec out of memory range.");
1392
1393       if (p != buffer + inaddr - memaddr)
1394         error("srec out of sequence.");
1395
1396       for (; size; --size, ++p)
1397         {
1398           get_hex_byte(p);
1399           checksum += *p;
1400         }
1401
1402       get_hex_byte(&c);
1403       if (c != (~checksum & 0xff))
1404         error("bad s-rec checksum");
1405     }
1406
1407  done:
1408   expect_prompt();
1409   if (p != buffer + len)
1410     return(1);
1411
1412   memcpy(myaddr, buffer, len);
1413   return(0);
1414 }
1415
1416 #define MAX_BREAKS      16
1417 static int num_brkpts = 0;
1418 static int
1419 bug_insert_breakpoint (addr, save)
1420      CORE_ADDR addr;
1421      char *save;                /* Throw away, let bug save instructions */
1422 {
1423   check_open ();
1424
1425   if (num_brkpts < MAX_BREAKS)
1426     {
1427       char buffer[100];
1428
1429       num_brkpts++;
1430       sprintf (buffer, "br %x", addr);
1431       bug_write_cr (buffer);
1432       expect_prompt ();
1433       return(0);
1434     }
1435   else
1436     {
1437       fprintf_filtered (stderr,
1438                       "Too many break points, break point not installed\n");
1439       return(1);
1440     }
1441
1442 }
1443 static int
1444 bug_remove_breakpoint (addr, save)
1445      CORE_ADDR addr;
1446      char *save;                /* Throw away, let bug save instructions */
1447 {
1448   if (num_brkpts > 0)
1449     {
1450       char buffer[100];
1451
1452       num_brkpts--;
1453       sprintf (buffer, "nobr %x", addr);
1454       bug_write_cr (buffer);
1455       expect_prompt ();
1456
1457     }
1458   return (0);
1459 }
1460
1461 /* Clear the bugs notion of what the break points are */
1462 static int
1463 bug_clear_breakpoints ()
1464 {
1465
1466   if (is_open)
1467     {
1468       bug_write_cr ("nobr");
1469       expect("nobr");
1470       expect_prompt ();
1471     }
1472   num_brkpts = 0;
1473   return(0);
1474 }
1475
1476 static void
1477 bug_mourn ()
1478 {
1479   bug_clear_breakpoints ();
1480   generic_mourn_inferior ();
1481 }
1482
1483 /* Put a command string, in args, out to the bug.  The bug is assumed to
1484    be in raw mode, all writing/reading done through desc.
1485    Ouput from the bug is placed on the users terminal until the
1486    prompt from the bug is seen.
1487    FIXME: Can't handle commands that take input.  */
1488
1489 void
1490 bug_com (args, fromtty)
1491      char *args;
1492      int fromtty;
1493 {
1494   check_open ();
1495
1496   if (!args)
1497     return;
1498
1499   /* Clear all input so only command relative output is displayed */
1500
1501   bug_write_cr (args);
1502   bug_write ("\030", 1);
1503   expect_prompt ();
1504 }
1505
1506 static void
1507 bug_device (args, fromtty)
1508      char *args;
1509      int fromtty;
1510 {
1511   if (args)
1512     dev_name = get_word (&args);
1513
1514   return;
1515 }
1516
1517 #if 0
1518 static
1519 bug_speed (s)
1520      char *s;
1521 {
1522   check_open ();
1523
1524   if (s)
1525     {
1526       char buffer[100];
1527       int newrate = atoi (s);
1528       int which = 0;
1529
1530       if (SERIAL_SETBAUDRATE (desc, newrate))
1531         error ("Can't use %d baud\n", newrate);
1532
1533       printf_filtered ("Checking target is in sync\n");
1534
1535       printf_filtered ("Sending commands to set target to %d\n",
1536                        baudrate);
1537
1538       sprintf (buffer, "tm %d. N 8 1", baudrate);
1539       bug_write_cr (buffer);
1540     }
1541 }
1542 #endif /* 0 */
1543
1544 struct target_ops bug_ops =
1545 {
1546   "bug", "Remote BUG monitor",
1547   "Use the mvme187 board running the BUG monitor connected\n\
1548 by a serial line.",
1549
1550   bug_open, bug_close,
1551   0, bug_detach, bug_resume, bug_wait,  /* attach */
1552   bug_fetch_register, bug_store_register,
1553   bug_prepare_to_store,
1554   bug_xfer_inferior_memory,
1555   bug_files_info,
1556   bug_insert_breakpoint, bug_remove_breakpoint, /* Breakpoints */
1557   0, 0, 0, 0, 0,                /* Terminal handling */
1558   bug_kill,                     /* FIXME, kill */
1559   bug_load,
1560   0,                            /* lookup_symbol */
1561   bug_create_inferior,          /* create_inferior */
1562   bug_mourn,                    /* mourn_inferior FIXME */
1563   0,                            /* can_run */
1564   0,                            /* notice_signals */
1565   process_stratum, 0,           /* next */
1566   1, 1, 1, 1, 1,                /* all mem, mem, stack, regs, exec */
1567   0, 0,                         /* Section pointers */
1568   OPS_MAGIC,                    /* Always the last thing */
1569 };
1570
1571 void
1572 _initialize_remote_bug ()
1573 {
1574   add_target (&bug_ops);
1575
1576   add_com ("bug <command>", class_obscure, bug_com,
1577            "Send a command to the BUG monitor.");
1578
1579   add_com ("device", class_obscure, bug_device,
1580            "Set the terminal line for BUG communications");
1581
1582 #if 0
1583   add_com ("speed", class_obscure, bug_speed,
1584            "Set the terminal line speed for BUG communications");
1585 #endif /* 0 */
1586
1587   add_show_from_set
1588     (add_set_cmd ("srec-bytes", class_support, var_uinteger,
1589                   (char *) &srec_bytes,
1590                   "\
1591 Set the number of bytes represented in each S-record.\n\
1592 This affects the communication protocol with the remote target.",
1593                   &setlist),
1594      &showlist);
1595
1596   add_show_from_set
1597     (add_set_cmd ("srec-max-retries", class_support, var_uinteger,
1598                   (char *) &srec_max_retries,
1599                   "\
1600 Set the number of retries for shipping S-records.\n\
1601 This affects the communication protocol with the remote target.",
1602                   &setlist),
1603      &showlist);
1604
1605   add_show_from_set
1606     (add_set_cmd ("srec-frame", class_support, var_uinteger,
1607                   (char *) &srec_frame,
1608                   "\
1609 Set the number of bytes in an S-record frame.\n\
1610 This affects the communication protocol with the remote target.",
1611                   &setlist),
1612      &showlist);
1613
1614   add_show_from_set
1615     (add_set_cmd ("srec-noise", class_support, var_zinteger,
1616                   (char *) &srec_noise,
1617                   "\
1618 Set number of S-record to send before deliberately flubbing a checksum.\n\
1619 Zero means flub none at all.  This affects the communication protocol\n\
1620 with the remote target.",
1621                   &setlist),
1622      &showlist);
1623
1624   add_show_from_set
1625     (add_set_cmd ("srec-sleep", class_support, var_zinteger,
1626                   (char *) &srec_sleep,
1627                   "\
1628 Set number of seconds to sleep after an S-record for a possible error message to arrive.\n\
1629 This affects the communication protocol with the remote target.",
1630                   &setlist),
1631      &showlist);
1632
1633   add_show_from_set
1634     (add_set_cmd ("srec-echo-pace", class_support, var_boolean,
1635                   (char *) &srec_echo_pace,
1636                   "\
1637 Set echo-verification.\n\
1638 When on, use verification by echo when downloading S-records.  This is\n\
1639 much slower, but generally more reliable.", 
1640                   &setlist),
1641      &showlist);
1642
1643   add_show_from_set
1644     (add_set_cmd ("bug88k-snoop", class_support, var_boolean,
1645                   (char *) &bug88k_snoop,
1646                   "\
1647 Set echoing of what's going to and from the monitor.\n\
1648 When on, echo data going out on and coming back from the serial line.", 
1649                   &setlist),
1650      &showlist);
1651
1652   dev_name = NULL;
1653 }