* monitor.c (set_loadtype_command): Fixed so it doesn't core dump.
[external/binutils.git] / gdb / monitor.c
1 /* Remote debugging interface for boot monitors, for GDB.
2    Copyright 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
3    Contributed by Cygnus Support. Written by Rob Savoye for Cygnus.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 /* This file was derived from various remote-* modules. It is a collection
22    of generic support functions so GDB can talk directly to a ROM based
23    monitor. This saves use from having to hack an exception based handler
24    into existance, and makes for quick porting.
25
26    This module talks to a debug monitor called 'MONITOR', which
27    We communicate with MONITOR via either a direct serial line, or a TCP
28    (or possibly TELNET) stream to a terminal multiplexor,
29    which in turn talks to the target board.
30 */
31
32 #include "defs.h"
33 #include "gdbcore.h"
34 #include "target.h"
35 #include "wait.h"
36 #include <varargs.h>
37 #include <signal.h>
38 #include <string.h>
39 #include <sys/types.h>
40 #include "command.h"
41 #include "serial.h"
42 #include "monitor.h"
43 #include "remote-utils.h"
44
45 #ifdef HAVE_TERMIO
46 #  define TERMINAL struct termios
47 #else
48 #  define TERMINAL struct sgttyb
49 #endif
50
51 struct monitor_ops *current_monitor;
52 extern struct cmd_list_element *setlist;
53 extern struct cmd_list_element *unsetlist;
54 struct cmd_list_element *showlist;
55 extern char *version;
56 extern char *host_name;
57 extern char *target_name;
58
59 static int hashmark;                            /* flag set by "set hash" */
60
61 /* FIXME: Replace with sr_get_debug ().  */
62 #define LOG_FILE "monitor.log"
63 #if defined (LOG_FILE)
64 FILE *log_file;
65 #endif
66
67 static int timeout = 24;
68
69 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
70    monitor_open knows that we don't have a file open when the program starts.
71    */
72 static serial_t monitor_desc = NULL;
73
74 /* sets the download protocol, choices are srec, generic, boot */
75 char *loadtype;
76 static char *loadtype_str;
77 static void set_loadtype_command();
78 static void monitor_load_srec();
79 static int monitor_write_srec();
80
81 /*
82  * set_loadtype_command -- set the type for downloading. Check to make
83  *      sure you have a support protocol for this target.
84  */
85 static void
86 set_loadtype_command (ignore, from_tty, c)
87      char *ignore;
88      int from_tty;
89      struct cmd_list_element *c;
90 {
91   char *tmp;
92   char *type;
93   if (STREQ (LOADTYPES, "")) {
94     error ("No loadtype set");
95     return;
96   }
97   
98   tmp = savestring (LOADTYPES, strlen(LOADTYPES));
99   type = strtok(tmp, ",");
100   if (STREQ (type, (*(char **) c->var))) {
101       loadtype_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
102       return;
103     }
104   
105   while ((type = strtok (NULL, ",")) != (char *)NULL) {
106     if (STREQ (type, (*(char **) c->var)))
107       loadtype_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
108     return;
109   }
110   free (tmp);
111   error ("Loadtype \"%s\" does not exist.", (*(char **) c->var));
112 }
113
114 /*
115  * printf_monitor -- send data to monitor.  Works just like printf.
116  */
117 static void
118 printf_monitor(va_alist)
119      va_dcl
120 {
121   va_list args;
122   char *pattern;
123   char buf[200];
124   int i;
125
126   va_start(args);
127
128   pattern = va_arg(args, char *);
129
130   vsprintf(buf, pattern, args);
131
132   debuglogs (1, "printf_monitor(), Sending: \"%s\".", buf);
133
134   if (SERIAL_WRITE(monitor_desc, buf, strlen(buf)))
135     fprintf(stderr, "SERIAL_WRITE failed: %s\n", safe_strerror(errno));
136 }
137
138 /*
139  * debuglogs -- deal with debugging info to multiple sources. This takes
140  *      two real args, the first one is the level to be compared against 
141  *      the sr_get_debug() value, the second arg is a printf buffer and args
142  *      to be formatted and printed. A CR is added after each string is printed.
143  */
144 static void
145 debuglogs(va_alist)
146      va_dcl
147 {
148   va_list args;
149   char *pattern, *p;
150   char buf[200];
151   char newbuf[300];
152   int level, i;
153
154   va_start(args);
155
156   level = va_arg(args, int);                    /* get the debug level */
157   if ((level <0) || (level > 100)) {
158     error ("Bad argument passed to debuglogs()");
159     return;
160   }
161       
162   pattern = va_arg(args, char *);               /* get the printf style pattern */
163
164   vsprintf(buf, pattern, args);                 /* format the string */
165   
166   /* convert some characters so it'll look right in the log */
167   p = newbuf;
168   for (i=0 ; buf[i] != '\0'; i++) {
169     switch (buf[i]) {
170     case '\n':                                  /* newlines */
171       *p++ = '\\';
172       *p++ = 'n';
173       continue;
174     case '\r':                                  /* carriage returns */
175       *p++ = '\\';
176       *p++ = 'r';
177       continue;
178     case '\033':                                /* escape */
179       *p++ = '\\';
180       *p++ = 'e';
181       continue;
182     case '\t':                                  /* tab */
183       *p++ = '\\';
184       *p++ = 't';
185       continue;
186     case '\b':                                  /* backspace */
187       *p++ = '\\';
188       *p++ = 'b';
189       continue;
190     default:                                    /* no change */
191       *p++ = buf[i];
192     }
193
194     if (buf[i] < 26) {                          /* modify control characters */
195       *p++ = '^';
196       *p++ = buf[i] + 'A';
197       continue;
198     }
199   }
200   *p = '\0';                                    /* terminate the string */
201
202   if (sr_get_debug() > level)
203     puts (newbuf);
204
205 #ifdef LOG_FILE                                 /* write to the monitor log */
206   if (log_file != 0x0) {
207     fputs (newbuf, log_file);
208     fputc ('\n', log_file);
209     fflush (log_file);
210   }
211 #endif
212 }
213
214 /* readchar -- read a character from the remote system, doing all the fancy
215  *      timeout stuff.
216  */
217 static int
218 readchar(timeout)
219      int timeout;
220 {
221   int c;
222
223   c = SERIAL_READCHAR(monitor_desc, timeout);
224
225   if (sr_get_debug() > 4)
226     putchar(c & 0x7f);
227
228 #ifdef LOG_FILE
229   if (isascii (c))
230     putc(c & 0x7f, log_file);
231 #endif
232
233   if (c >= 0)
234     return c & 0x7f;
235
236   if (c == SERIAL_TIMEOUT) {
237     if (timeout == 0)
238       return c;         /* Polls shouldn't generate timeout errors */
239     error("Timeout reading from remote system.");
240 #ifdef LOG_FILE
241       fputc ("ERROR: Timeout reading from remote system", log_file);
242 #endif
243   }
244   perror_with_name("remote-monitor");
245 }
246
247 /* 
248  * expect --  scan input from the remote system, until STRING is found.
249  *      If DISCARD is non-zero, then discard non-matching input, else print
250  *      it out. Let the user break out immediately.
251  */
252 static void
253 expect (string, discard)
254      char *string;
255      int discard;
256 {
257   char *p = string;
258   int c;
259
260
261   debuglogs (1, "Expecting \"%s\".", string);
262
263   immediate_quit = 1;
264   while (1) {
265     c = readchar(timeout);
266     if (!isascii (c))
267       continue;
268     if (c == *p++) {
269       if (*p == '\0') {
270         immediate_quit = 0;
271         debuglogs (4, "Matched");
272         return;
273       }
274     } else {
275       if (!discard) {
276         fwrite(string, 1, (p - 1) - string, stdout);
277         putchar((char)c);
278         fflush(stdout);
279       }
280       p = string;
281     }
282   }
283 }
284
285 /* Keep discarding input until we see the MONITOR prompt.
286
287    The convention for dealing with the prompt is that you
288    o give your command
289    o *then* wait for the prompt.
290
291    Thus the last thing that a procedure does with the serial line
292    will be an expect_prompt().  Exception:  monitor_resume does not
293    wait for the prompt, because the terminal is being handed over
294    to the inferior.  However, the next thing which happens after that
295    is a monitor_wait which does wait for the prompt.
296    Note that this includes abnormal exit, e.g. error().  This is
297    necessary to prevent getting into states from which we can't
298    recover.  */
299 static void
300 expect_prompt(discard)
301      int discard;
302 {
303 #if defined (LOG_FILE)
304   /* This is a convenient place to do this.  The idea is to do it often
305      enough that we never lose much data if we terminate abnormally.  */
306   fflush(log_file);
307 #endif
308   expect (PROMPT, discard);
309 }
310
311 /*
312  * junk -- ignore junk characters. Returns a 1 if junk, 0 otherwise
313  */
314 static int
315 junk(ch)
316      char ch;
317 {
318   switch (ch) {
319   case ' ':
320   case '-':
321   case '\t':
322   case '\r':
323   case '\n':
324     if (sr_get_debug() > 5)
325       debuglogs (5, "Ignoring \'%c\'.", ch);
326     return 1;
327   default:
328     if (sr_get_debug() > 5)
329       debuglogs (5, "Accepting \'%c\'.", ch);
330     return 0;
331   }
332 }
333
334 /* 
335  *  get_hex_digit -- Get a hex digit from the remote system & return its value.
336  *              If ignore is nonzero, ignore spaces, newline & tabs.
337  */
338 static int
339 get_hex_digit(ignore)
340      int ignore;
341 {
342   static int ch;
343   while (1) {
344     ch = readchar(timeout);
345     if (junk(ch))
346       continue;
347     if (sr_get_debug() > 4)
348       debuglogs (4, "get_hex_digit() got a 0x%x(%c)", ch, ch);
349
350     if (ch >= '0' && ch <= '9')
351       return ch - '0';
352     else if (ch >= 'A' && ch <= 'F')
353       return ch - 'A' + 10;
354     else if (ch >= 'a' && ch <= 'f')
355       return ch - 'a' + 10;
356     else if (ch == ' ' && ignore)
357       ;
358     else {
359       expect_prompt(1);
360       error("Invalid hex digit from remote system.");
361     }
362   }
363 }
364
365 /* get_hex_byte -- Get a byte from monitor and put it in *BYT. 
366  *      Accept any number leading spaces.
367  */
368 static void
369 get_hex_byte (byt)
370      char *byt;
371 {
372   int val;
373
374   val = get_hex_digit (1) << 4;
375   debuglogs (4, "get_hex_digit() -- Read first nibble 0x%x", val);
376  
377   val |= get_hex_digit (0);
378   debuglogs (4, "get_hex_digit() -- Read second nibble 0x%x", val);
379   *byt = val;
380   
381   debuglogs (4, "get_hex_digit() -- Read a 0x%x", val);
382 }
383
384 /* 
385  * get_hex_word --  Get N 32-bit words from remote, each preceded by a space,
386  *      and put them in registers starting at REGNO.
387  */
388 static int
389 get_hex_word ()
390 {
391   long val;
392   int i;
393
394   val = 0;
395   for (i = 0; i < 8; i++)
396     val = (val << 4) + get_hex_digit (i == 0);
397   
398   debuglogs (4, "get_hex_word() got a 0x%x.", val);
399
400   return val;
401 }
402
403 /* This is called not only when we first attach, but also when the
404    user types "run" after having attached.  */
405 void
406 monitor_create_inferior (execfile, args, env)
407      char *execfile;
408      char *args;
409      char **env;
410 {
411   int entry_pt;
412
413   if (args && *args)
414     error("Can't pass arguments to remote MONITOR process");
415
416   if (execfile == 0 || exec_bfd == 0)
417     error("No exec file specified");
418
419   entry_pt = (int) bfd_get_start_address (exec_bfd);
420
421   debuglogs (1, "create_inferior(exexfile=%s, args=%s, env=%s)", execfile, args, env);
422
423 /* The "process" (board) is already stopped awaiting our commands, and
424    the program is already downloaded.  We just set its PC and go.  */
425
426   clear_proceed_status ();
427
428   /* Tell wait_for_inferior that we've started a new process.  */
429   init_wait_for_inferior ();
430
431   /* Set up the "saved terminal modes" of the inferior
432      based on what modes we are starting it with.  */
433   target_terminal_init ();
434
435   /* Install inferior's terminal modes.  */
436   target_terminal_inferior ();
437
438   /* insert_step_breakpoint ();  FIXME, do we need this?  */
439
440   /* Let 'er rip... */
441   proceed ((CORE_ADDR)entry_pt, TARGET_SIGNAL_DEFAULT, 0);
442 }
443
444 /*
445  * monitor_open -- open a connection to a remote debugger.
446  *      NAME is the filename used for communication.
447  */
448 static int baudrate = 9600;
449 static char dev_name[100];
450
451 void
452 monitor_open(args, name, from_tty)
453      char *args;
454      char *name;
455      int from_tty;
456 {
457
458   if (args == NULL)
459     error ("Use `target %s DEVICE-NAME' to use a serial port, or \n\
460 `target %s HOST-NAME:PORT-NUMBER' to use a network connection.", name, name);
461
462 /*  if (is_open) */
463     monitor_close(0);
464
465   strcpy(dev_name, args);
466   monitor_desc = SERIAL_OPEN(dev_name);
467
468   if (monitor_desc == NULL)
469     perror_with_name(dev_name);
470
471   if (baud_rate != -1) {
472     if (SERIAL_SETBAUDRATE (monitor_desc, baud_rate)) {
473       SERIAL_CLOSE (monitor_desc);
474       perror_with_name (name);
475     }
476   }
477   
478   SERIAL_RAW(monitor_desc);
479
480 #if defined (LOG_FILE)
481   log_file = fopen (LOG_FILE, "w");
482   if (log_file == NULL)
483     perror_with_name (LOG_FILE);
484   fprintf_filtered (log_file, "GDB %s (%s", version, host_name);
485   fprintf_filtered (log_file, " --target %s)\n", target_name);
486   fprintf_filtered (log_file, "Remote target %s connected to %s\n\n", TARGET_NAME, dev_name);
487 #endif
488
489   /* wake up the monitor and see if it's alive */
490   printf_monitor(INIT_CMD);
491   expect_prompt(1);             /* See if we get a prompt */
492
493   /* try again to be sure */
494   printf_monitor(INIT_CMD);
495   expect_prompt(1);             /* See if we get a prompt */
496
497   if (from_tty)
498     printf("Remote target %s connected to %s\n", TARGET_NAME, dev_name);
499 }
500
501 /*
502  * monitor_close -- Close out all files and local state before this
503  *      target loses control.
504  */
505
506 void
507 monitor_close (quitting)
508      int quitting;
509 {
510   SERIAL_CLOSE(monitor_desc);
511   monitor_desc = NULL;
512
513   debuglogs (1, "monitor_close (quitting=%d)", quitting);
514
515 #if defined (LOG_FILE)
516   if (log_file) {
517     if (ferror(log_file))
518       fprintf(stderr, "Error writing log file.\n");
519     if (fclose(log_file) != 0)
520       fprintf(stderr, "Error closing log file.\n");
521   }
522 #endif
523 }
524
525 /* 
526  * monitor_detach -- terminate the open connection to the remote
527  *      debugger. Use this when you want to detach and do something
528  *      else with your gdb.
529  */
530 void
531 monitor_detach (from_tty)
532      int from_tty;
533 {
534
535   debuglogs (1, "monitor_detach ()");
536
537   pop_target();         /* calls monitor_close to do the real work */
538   if (from_tty)
539     printf ("Ending remote %s debugging\n", target_shortname);
540 }
541
542 /*
543  * monitor_attach -- attach GDB to the target.
544  */
545 void
546 monitor_attach (args, from_tty)
547      char *args;
548      int from_tty;
549 {
550   if (from_tty)
551     printf ("Starting remote %s debugging\n", target_shortname);
552  
553   debuglogs (1, "monitor_attach (args=%s)", args);
554   
555   printf_monitor (GO_CMD);
556   /* swallow the echo.  */
557   expect (GO_CMD, 1);
558 }
559   
560 /*
561  * monitor_resume -- Tell the remote machine to resume.
562  */
563 void
564 monitor_resume (pid, step, sig)
565      int pid, step;
566      enum target_signal sig;
567 {
568   debuglogs (1, "monitor_resume (step=%d, sig=%d)", step, sig);
569
570   if (step) {
571     printf_monitor (STEP_CMD);
572   } else {
573     printf_monitor (CONT_CMD);
574   }
575 }
576
577 /*
578  * monitor_wait -- Wait until the remote machine stops, then return,
579  *          storing status in status just as `wait' would.
580  */
581 int
582 monitor_wait (pid, status)
583      int pid;
584      struct target_waitstatus *status;
585 {
586   int old_timeout = timeout;
587
588   debuglogs(1, "monitor_wait (), printing extraneous text.");
589   
590   status->kind = TARGET_WAITKIND_EXITED;
591   status->value.integer = 0;
592
593   timeout = 0;          /* Don't time out -- user program is running. */
594
595   expect_prompt(0);    /* Wait for prompt, outputting extraneous text */
596   debuglogs (4, "monitor_wait(), got the prompt.");
597
598   status->kind = TARGET_WAITKIND_STOPPED;
599   status->value.sig = TARGET_SIGNAL_TRAP;
600
601   timeout = old_timeout;
602
603   return 0;
604 }
605
606 /* Return the name of register number regno in the form input and output by
607    monitor.  Currently, register_names just happens to contain exactly what
608    monitor wants.  Lets take advantage of that just as long as possible! */
609
610 static char *
611 get_reg_name (regno)
612      int regno;
613 {
614   static char buf[50];
615   const char *p;
616   char *b;
617
618   b = buf;
619
620   if (regno < 0)
621     return ("");
622
623   for (p = REGNAMES(regno); *p; p++)
624     *b++ = tolower(*p);
625
626   *b = '\000';
627
628   debuglogs (5, "Got name \"%s\" from regno #%d.", buf, regno);
629
630   return buf;
631 }
632
633 /*
634  * monitor_fetch_registers -- read the remote registers into the
635  *      block regs.
636  */
637 void
638 monitor_fetch_registers ()
639 {
640   int regno;
641
642   /* yeah yeah, i know this is horribly inefficient.  but it isn't done
643      very often...  i'll clean it up later.  */
644
645   for (regno = 0; regno <= PC_REGNUM; regno++)
646     monitor_fetch_register(regno);
647 }
648
649 /* 
650  * monitor_fetch_register -- fetch register REGNO, or all registers if REGNO
651  *      is -1. Returns errno value.
652  */
653 void
654 monitor_fetch_register (regno)
655      int regno;
656 {
657   int val, j;
658
659   debuglogs (1, "monitor_fetch_register (reg=%s)", get_reg_name (regno));
660
661   if (regno < 0) {
662     monitor_fetch_registers ();
663   } else {
664     char *name = get_reg_name (regno);
665     if (STREQ(name, ""))
666       return;
667     printf_monitor (ROMCMD(GET_REG), name);     /* send the command */
668     expect (name, 1);                           /* then strip the leading garbage */
669     if (*ROMDELIM(GET_REG) != 0) {              /* if there's a delimiter */
670       expect (ROMDELIM(GET_REG), 1);
671     }
672     
673     val =  get_hex_word();                      /* get the value, ignore junk */
674     supply_register (regno, (char *) &val);
675     
676     if (*ROMDELIM(GET_REG) != 0) {
677 /***  expect (ROMRES(GET_REG)); ***/
678       printf_monitor (CMD_END);
679     }
680     expect_prompt (1);
681   }
682   return;
683 }
684
685 /* Store the remote registers from the contents of the block REGS.  */
686
687 void
688 monitor_store_registers ()
689 {
690   int regno;
691
692   debuglogs (1, "monitor_store_registers()");
693
694   for (regno = 0; regno <= PC_REGNUM; regno++)
695     monitor_store_register(regno);
696
697   registers_changed ();
698 }
699
700 /* 
701  * monitor_store_register -- store register REGNO, or all if REGNO == 0.
702  *      return errno value.
703  */
704 void
705 monitor_store_register (regno)
706      int regno;
707 {
708   char *name;
709   int i;
710
711   i = read_register(regno);
712
713   debuglogs (1, "monitor_store_register (regno=%d)", regno);
714
715   if (regno < 0)
716     monitor_store_registers ();
717   else {
718       debuglogs (3, "Setting register %s to 0x%x", get_reg_name (regno), read_register (regno));
719     
720     name = get_reg_name (regno);
721     if (STREQ(name, ""))
722       return;
723     printf_monitor (ROMCMD(SET_REG), name, read_register(regno));
724     expect (name, 1);                           /* strip the leading garbage */
725     if (*ROMDELIM(SET_REG) != 0) {              /* if there's a delimiter */
726       expect (ROMDELIM(SET_REG), 1);
727       get_hex_word(1);
728       printf_monitor ("%d%s\n", i, CMD_END);
729     }
730     expect_prompt (1);
731   }
732   return;
733   
734 #if 0
735       printf_monitor (SET_REG, get_reg_name (regno),
736                       read_register (regno));
737       expect_prompt (1);
738     }
739 #endif
740 }
741
742 /* Get ready to modify the registers array.  On machines which store
743    individual registers, this doesn't need to do anything.  On machines
744    which store all the registers in one fell swoop, this makes sure
745    that registers contains all the registers from the program being
746    debugged.  */
747
748 void
749 monitor_prepare_to_store ()
750 {
751   /* Do nothing, since we can store individual regs */
752 }
753
754 void
755 monitor_files_info ()
756 {
757   printf ("\tAttached to %s at %d baud.\n",
758           dev_name, baudrate);
759 }
760
761 /*
762  * monitor_write_inferior_memory -- Copy LEN bytes of data from debugger
763  *      memory at MYADDR to inferior's memory at MEMADDR.  Returns length moved.
764  */
765 int
766 monitor_write_inferior_memory (memaddr, myaddr, len)
767      CORE_ADDR memaddr;
768      unsigned char *myaddr;
769      int len;
770 {
771   int i;
772   char buf[10];
773
774   debuglogs (1, "monitor_write_inferior_memory (memaddr=0x%x, myaddr=0x%x, len=%d)", memaddr, myaddr, len);
775
776   for (i = 0; i < len; i++) {
777     printf_monitor (ROMCMD(SET_MEM), memaddr + i, myaddr[i] );
778     if (*ROMDELIM(SET_MEM) != 0) {              /* if there's a delimiter */
779       expect (ROMDELIM(SET_MEM), 1);
780       expect (CMD_DELIM);
781       printf_monitor ("%x", myaddr[i]);
782     }
783 /***    printf_monitor ("%x", myaddr[i]); ***/
784     if (sr_get_debug() > 1)
785       printf ("\nSet 0x%x to 0x%x\n", memaddr + i, myaddr[i]);
786     if (*ROMDELIM(SET_MEM) != 0) {
787       expect (CMD_DELIM);
788       printf_monitor (CMD_END);
789     }
790     expect_prompt (1);
791   }
792   return len;
793 }
794
795 /*
796  * monitor_read_inferior_memory -- read LEN bytes from inferior memory
797  *      at MEMADDR.  Put the result at debugger address MYADDR.  Returns
798  *      length moved.
799  */
800 int
801 monitor_read_inferior_memory(memaddr, myaddr, len)
802      CORE_ADDR memaddr;
803      char *myaddr;
804      int len;
805 {
806   int i, j;
807   char buf[20];
808
809   /* Number of bytes read so far.  */
810   int count;
811
812   /* Starting address of this pass.  */
813   unsigned long startaddr;
814
815   /* Number of bytes to read in this pass.  */
816   int len_this_pass;
817
818   debuglogs (1, "monitor_read_inferior_memory (memaddr=0x%x, myaddr=0x%x, len=%d)", memaddr, myaddr, len);
819
820   /* Note that this code works correctly if startaddr is just less
821      than UINT_MAX (well, really CORE_ADDR_MAX if there was such a
822      thing).  That is, something like
823      monitor_read_bytes (CORE_ADDR_MAX - 4, foo, 4)
824      works--it never adds len To memaddr and gets 0.  */
825   /* However, something like
826      monitor_read_bytes (CORE_ADDR_MAX - 3, foo, 4)
827      doesn't need to work.  Detect it and give up if there's an attempt
828      to do that.  */
829   if (((memaddr - 1) + len) < memaddr) {
830     errno = EIO;
831     return 0;
832   }
833   
834   startaddr = memaddr;
835   count = 0;
836   while (count < len) {
837     len_this_pass = 16;
838     if ((startaddr % 16) != 0)
839       len_this_pass -= startaddr % 16;
840     if (len_this_pass > (len - count))
841       len_this_pass = (len - count);
842
843     debuglogs (3, "Display %d bytes at %x", len_this_pass, startaddr);
844     
845     for (i = 0; i < len_this_pass; i++) {
846       printf_monitor (ROMCMD(GET_MEM), startaddr, startaddr);
847       sprintf (buf, ROMCMD(GET_MEM), startaddr, startaddr);
848       if (*ROMDELIM(GET_MEM) != 0) {            /* if there's a delimiter */
849         expect (ROMDELIM(GET_MEM), 1);
850       } else {
851         sprintf (buf, ROMCMD(GET_MEM), startaddr, startaddr);
852         expect (buf,1);                         /* get the command echo */
853         get_hex_word(1);                        /* strip away the address */
854       }
855       get_hex_byte (&myaddr[count++]);          /* get the value at this address */
856
857       if (*ROMDELIM(GET_MEM) != 0) {
858         printf_monitor (CMD_END);
859       }
860       expect_prompt (1);
861       startaddr += 1;
862     }
863   }
864   return len;
865 }
866
867 /* FIXME-someday!  merge these two.  */
868 int
869 monitor_xfer_inferior_memory (memaddr, myaddr, len, write, target)
870      CORE_ADDR memaddr;
871      char *myaddr;
872      int len;
873      int write;
874      struct target_ops *target;         /* ignored */
875 {
876   if (write)
877     return monitor_write_inferior_memory (memaddr, myaddr, len);
878   else
879     return monitor_read_inferior_memory (memaddr, myaddr, len);
880 }
881
882 void
883 monitor_kill (args, from_tty)
884      char *args;
885      int from_tty;
886 {
887   return;               /* ignore attempts to kill target system */
888 }
889
890 /* Clean up when a program exits.
891    The program actually lives on in the remote processor's RAM, and may be
892    run again without a download.  Don't leave it full of breakpoint
893    instructions.  */
894
895 void
896 monitor_mourn_inferior ()
897 {
898   remove_breakpoints ();
899   generic_mourn_inferior ();    /* Do all the proper things now */
900 }
901
902 #define MAX_MONITOR_BREAKPOINTS 16
903
904 extern int memory_breakpoint_size;
905 static CORE_ADDR breakaddr[MAX_MONITOR_BREAKPOINTS] = {0};
906
907 /*
908  * monitor_insert_breakpoint -- add a breakpoint
909  */
910 int
911 monitor_insert_breakpoint (addr, shadow)
912      CORE_ADDR addr;
913      char *shadow;
914 {
915   int i;
916
917   debuglogs (1, "monitor_insert_breakpoint() addr = 0x%x", addr);
918
919   for (i = 0; i <= MAX_MONITOR_BREAKPOINTS; i++) {
920     if (breakaddr[i] == 0) {
921       breakaddr[i] = addr;
922       if (sr_get_debug() > 4)
923         printf ("Breakpoint at %x\n", addr);
924       monitor_read_inferior_memory(addr, shadow, memory_breakpoint_size);
925       printf_monitor(SET_BREAK_CMD, addr);
926       expect_prompt(1);
927       return 0;
928     }
929   }
930
931   fprintf(stderr, "Too many breakpoints (> 16) for monitor\n");
932   return 1;
933 }
934
935 /*
936  * _remove_breakpoint -- Tell the monitor to remove a breakpoint
937  */
938 int
939 monitor_remove_breakpoint (addr, shadow)
940      CORE_ADDR addr;
941      char *shadow;
942 {
943   int i;
944
945   debuglogs (1, "monitor_remove_breakpoint() addr = 0x%x", addr);
946
947   for (i = 0; i < MAX_MONITOR_BREAKPOINTS; i++) {
948     if (breakaddr[i] == addr) {
949       breakaddr[i] = 0;
950       /* some monitors remove breakpoints based on the address */
951       if (CLR_BREAK_ADDR)   
952         printf_monitor(CLR_BREAK_CMD, addr);
953       else
954         printf_monitor(CLR_BREAK_CMD, i);
955       expect_prompt(1);
956       return 0;
957     }
958   }
959   fprintf(stderr, "Can't find breakpoint associated with 0x%x\n", addr);
960   return 1;
961 }
962
963 /* monitor_load -- load a file. This file determines which of the
964  *      supported formats to use. The current types are:
965  *      FIXME: not all types supported yet.
966  *      default - reads any file using bfd and writes it to memory.
967  *      srec    - reads binary file using bfd and writes it as an
968  *              ascii srecord.
969  *      xmodem-bin - reads a binary file using bfd, and  downloads it
970  *               using xmodem protocol.
971  *      xmodem-srec - reads a binary file using bfd, and after converting
972  *               it downloads it as an srecord using xmodem protocol.
973  *      ascii-srec - reads a ascii srecord file and downloads it
974  *              without a change.
975  *      ascii-xmodem - reads a ascii file and downloads using xmodem
976  *              protocol.
977  */
978 void
979 monitor_load (file, fromtty)
980     char *file;
981     int  fromtty;
982 {
983   FILE *download;
984   int i, bytes_read;
985
986   debuglogs (1, "Loading %s to monitor", file);
987
988   if (STREQ (loadtype_str, "default")) {        /* default, load a binary */
989     gr_load_image (file, fromtty);              /* by writing it into memory */
990   }
991
992   if (STREQ (loadtype_str, "srec")) {           /* load an srecord by converting */
993     monitor_load_srec(file, fromtty);           /* if from a binary */
994   }
995
996   if (STREQ (loadtype_str, "ascii-srec")) {     /* load an srecord file */
997     monitor_load_ascii_srec(file, fromtty);             /* if from a binary */
998   }
999
1000   if (STREQ (loadtype_str, "xmodem-srec")) {    /* load an srecord using the */
1001    error ("This protocol is not implemented yet.");     /* xmodem protocol */
1002   }
1003 }
1004
1005 /*
1006  * monitor_load_ascii_srec -- download an ASCII srecord file.
1007  */
1008 #define DOWNLOAD_LINE_SIZE 100
1009 int
1010 monitor_load_ascii_srec (file, fromtty)
1011     char *file;
1012     int fromtty;
1013 {
1014   FILE *download;
1015   char buf[DOWNLOAD_LINE_SIZE];
1016   int i, bytes_read;
1017
1018   debuglogs (1, "Loading an ASCII srecord file, %s.", file);
1019
1020   download = fopen (file, "r");
1021   if (download == NULL) {
1022     error ("%s Does not exist", file);
1023     return;
1024   }
1025
1026   printf_monitor (LOAD_CMD);
1027
1028   while (!feof (download)) {
1029     bytes_read = fread (buf, sizeof (char), DOWNLOAD_LINE_SIZE, download);
1030     if (hashmark) {
1031       putchar ('.');
1032       fflush (stdout);
1033     }
1034     if (SERIAL_WRITE(monitor_desc, buf, bytes_read)) {
1035       fprintf(stderr, "SERIAL_WRITE failed: (while downloading) %s\n", safe_strerror(errno));
1036       break;
1037     }
1038     i = 0;
1039     while (i++ <=200) {} ;                      /* Ugly HACK, probably needs flow control */
1040     if (bytes_read < DOWNLOAD_LINE_SIZE) {
1041       if (!feof (download))
1042         error ("Only read %d bytes\n", bytes_read);
1043       break;
1044     }
1045   }
1046   
1047   if (hashmark) {
1048     putchar ('\n');
1049   }
1050   if (!feof (download))
1051     error ("Never got EOF while downloading");
1052   expect_prompt(1);
1053   fclose (download);
1054 }
1055
1056 /* 
1057  * monitor_command -- put a command string, in args, out to MONITOR.
1058  *      Output from MONITOR is placed on the users terminal until the
1059  *      prompt is seen. FIXME: We read the charcters ourseleves here
1060  *      cause of a nasty echo.
1061  */
1062 void
1063 monitor_command (args, fromtty)
1064      char       *args;
1065      int        fromtty;
1066 {
1067
1068   char *p;
1069   char c, cp;
1070   p = PROMPT;
1071
1072   debuglogs (1, "monitor_command (args=%s)", args);
1073
1074   if (monitor_desc == NULL)
1075     error("monitor target not open.");
1076
1077   if (!args)
1078     error("Missing command.");
1079         
1080   printf_monitor ("%s\n", args);
1081
1082   expect_prompt(0);
1083 }
1084
1085 /*
1086  * monitor_load_srec -- download a binary file by converting it to srecords.
1087  */
1088 static void
1089 monitor_load_srec (args, fromtty)
1090      char *args;
1091      int fromtty;
1092 {
1093   bfd *abfd;
1094   asection *s;
1095   char buffer[1024];
1096   int srec_frame = SREC_SIZE;
1097
1098   abfd = bfd_openr (args, 0);
1099   if (!abfd) {
1100     printf_filtered ("Unable to open file %s\n", args);
1101     return;
1102   }
1103
1104   if (bfd_check_format (abfd, bfd_object) == 0) {
1105     printf_filtered ("File is not an object file\n");
1106     return;
1107   }
1108   
1109   s = abfd->sections;
1110   while (s != (asection *) NULL) {
1111     srec_frame = SREC_SIZE;
1112     if (s->flags & SEC_LOAD) {
1113       int i;
1114       char *buffer = xmalloc (srec_frame);
1115       printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name, s->vma, s->vma + s
1116                        ->_raw_size);
1117       fflush (stdout);
1118       for (i = 0; i < s->_raw_size; i += srec_frame) {
1119         if (srec_frame > s->_raw_size - i)
1120           srec_frame = s->_raw_size - i;
1121         
1122         bfd_get_section_contents (abfd, s, buffer, i, srec_frame);
1123         monitor_write_srec (s->vma + i, buffer, srec_frame);
1124         printf_filtered ("*");
1125         fflush (stdout);
1126       }
1127       printf_filtered ("\n");
1128       free (buffer);
1129     }
1130     s = s->next;
1131   }
1132   sprintf (buffer, "rs ip %lx", (unsigned long) abfd->start_address);
1133   printf_monitor (buffer);
1134   expect_prompt ();
1135 }
1136
1137
1138 static int
1139 monitor_write_srec (memaddr, myaddr, len)
1140      CORE_ADDR memaddr;
1141      unsigned char *myaddr;
1142      int len;
1143 {
1144   int done;
1145   int checksum;
1146   int x;
1147   int retries;
1148   int srec_bytes = 40;
1149   int srec_max_retries = 3;
1150   int srec_echo_pace = 0;
1151   int srec_sleep = 0;
1152   int srec_noise = 0;
1153   char *buffer = alloca ((srec_bytes + 8) << 1);
1154
1155   retries = 0;
1156
1157   while (1) {                                   /* FIXME !!! */
1158     done = 0;
1159     
1160     if (retries > srec_max_retries)
1161       return(-1);
1162     
1163       if (retries > 0) {
1164         if (sr_get_debug() > 0)
1165           printf("\n<retrying...>\n");
1166         
1167           /* This gr_expect_prompt call is extremely important.  Without
1168              it, we will tend to resend our packet so fast that it
1169              will arrive before the bug monitor is ready to receive
1170              it.  This would lead to a very ugly resend loop.  */
1171         
1172         gr_expect_prompt();
1173       }
1174     
1175     /* FIXME: this is just start_load pasted in... */
1176     { char *command;
1177     command = (srec_echo_pace ? "lo 0 ;x" : "lo 0");
1178     sr_write_cr (command);
1179     sr_expect (command);
1180     sr_expect ("\r\n");
1181 #if 0
1182     bug_srec_write_cr ("S0030000FC");
1183 #endif
1184     }
1185     /* end of hack */
1186
1187       while (done < len) {
1188         int thisgo;
1189         int idx;
1190         char *buf = buffer;
1191         CORE_ADDR address;
1192         
1193         checksum = 0;
1194         thisgo = len - done;
1195         if (thisgo > srec_bytes)
1196           thisgo = srec_bytes;
1197         
1198         address = memaddr + done;
1199         sprintf (buf, "S3%02X%08X", thisgo + 4 + 1, address);
1200         buf += 12;
1201         
1202         checksum += (thisgo + 4 + 1
1203                      + (address & 0xff)
1204                      + ((address >>  8) & 0xff)
1205                      + ((address >> 16) & 0xff)
1206                      + ((address >> 24) & 0xff));
1207         
1208         for (idx = 0; idx < thisgo; idx++) {
1209           sprintf (buf, "%02X", myaddr[idx + done]);
1210           checksum += myaddr[idx + done];
1211           buf += 2;
1212         }
1213         
1214         if (srec_noise > 0) {
1215           /* FIXME-NOW: insert a deliberate error every now and then.
1216              This is intended for testing/debugging the error handling
1217              stuff.  */
1218           static int counter = 0;
1219           if (++counter > srec_noise) {
1220             counter = 0;
1221             ++checksum;
1222           }
1223         }
1224         
1225         sprintf(buf, "%02X", ~checksum & 0xff);
1226 #if 0
1227         bug_srec_write_cr (buffer);
1228 #endif
1229         
1230         if (srec_sleep != 0)
1231           sleep(srec_sleep);
1232         
1233         /* This pollchar is probably redundant to the gr_multi_scan
1234            below.  Trouble is, we can't be sure when or where an
1235            error message will appear.  Apparently, when running at
1236            full speed from a typical sun4, error messages tend to
1237            appear to arrive only *after* the s7 record.   */
1238         
1239         if ((x = sr_pollchar()) != 0) {
1240           if (sr_get_debug() > 0)
1241             printf("\n<retrying...>\n");
1242
1243           ++retries;
1244           
1245           /* flush any remaining input and verify that we are back
1246              at the prompt level. */
1247           gr_expect_prompt();
1248           /* start all over again. */
1249     /* FIXME: this is just start_load pasted in... */
1250     { char *command;
1251     command = (srec_echo_pace ? "lo 0 ;x" : "lo 0");
1252     sr_write_cr (command);
1253     sr_expect (command);
1254     sr_expect ("\r\n");
1255 #if 0
1256     bug_srec_write_cr ("S0030000FC");
1257 #endif
1258     }
1259     /* end of hack */
1260
1261           done = 0;
1262           continue;
1263         }
1264         
1265         done += thisgo;
1266       }
1267 #if 0    
1268     bug_srec_write_cr("S7060000000000F9");
1269 #endif
1270     ++retries;
1271     
1272     /* Having finished the load, we need to figure out whether we
1273        had any errors.  */
1274   }
1275   
1276   return(0);
1277 }
1278
1279 /*
1280  * _initialize_remote_monitors -- setup a few addtitional commands that
1281  *              are usually only used by monitors.
1282  */
1283 void
1284 _initialize_remote_monitors ()
1285 {
1286   struct cmd_list_element *c;
1287
1288   /* this sets the type of download protocol */
1289   c = add_set_cmd ("loadtype", no_class, var_string, (char *)&loadtype_str,
1290        "Set the type of the remote load protocol.\n", &setlist);
1291   c->function.sfunc =  set_loadtype_command;
1292   add_show_from_set (c, &showlist);
1293   loadtype_str = savestring ("default", 8);
1294
1295   add_show_from_set (add_set_cmd ("hash", no_class, var_boolean,
1296                                   (char *)&hashmark,
1297                                   "Set display of activity while downloading a file.\n\
1298 When enabled, a period \'.\' is displayed.",
1299                                   &setlist),
1300                      &showlist);
1301
1302   /* generic monitor command */
1303   add_com ("monitor", class_obscure, monitor_command,
1304            "Send a command to the debug monitor."); 
1305 }