Make debugging remote gdb friendlier
[external/binutils.git] / gdb / monitor.c
1 /* Remote debugging interface for boot monitors, for GDB.
2    Copyright 1990, 1991, 1992, 1993, 1995
3    Free Software Foundation, Inc.
4    Contributed by Cygnus Support.  Written by Rob Savoye for Cygnus.
5    Resurrected from the ashes by Stu Grossman.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
22
23 /* This file was derived from various remote-* modules. It is a collection
24    of generic support functions so GDB can talk directly to a ROM based
25    monitor. This saves use from having to hack an exception based handler
26    into existance, and makes for quick porting.
27
28    This module talks to a debug monitor called 'MONITOR', which
29    We communicate with MONITOR via either a direct serial line, or a TCP
30    (or possibly TELNET) stream to a terminal multiplexor,
31    which in turn talks to the target board.  */
32
33 #include "defs.h"
34 #include "gdbcore.h"
35 #include "target.h"
36 #include "wait.h"
37 #ifdef ANSI_PROTOTYPES
38 #include <stdarg.h>
39 #else
40 #include <varargs.h>
41 #endif
42 #include <signal.h>
43 #include <ctype.h>
44 #include "gdb_string.h"
45 #include <sys/types.h>
46 #include "command.h"
47 #include "serial.h"
48 #include "monitor.h"
49 #include "gdbcmd.h"
50 #include "inferior.h"
51 #include "gnu-regex.h"
52 #include "dcache.h"
53 #include "srec.h"
54
55 static int readchar PARAMS ((int timeout));
56
57 static void monitor_command PARAMS ((char *args, int fromtty));
58
59 static void monitor_fetch_register PARAMS ((int regno));
60 static void monitor_store_register PARAMS ((int regno));
61
62 static void monitor_close PARAMS ((int quitting));
63 static void monitor_detach PARAMS ((char *args, int from_tty));
64 static void monitor_resume PARAMS ((int pid, int step, enum target_signal sig));
65 static void monitor_interrupt PARAMS ((int signo));
66 static void monitor_interrupt_twice PARAMS ((int signo));
67 static void monitor_interrupt_query PARAMS ((void));
68 static void monitor_wait_cleanup PARAMS ((int old_timeout));
69
70 static int monitor_wait PARAMS ((int pid, struct target_waitstatus *status));
71 static void monitor_fetch_registers PARAMS ((int regno));
72 static void monitor_store_registers PARAMS ((int regno));
73 static void monitor_prepare_to_store PARAMS ((void));
74 static int monitor_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr, int len, int write, struct target_ops *target));
75 static void monitor_files_info PARAMS ((struct target_ops *ops));
76 static int monitor_insert_breakpoint PARAMS ((CORE_ADDR addr, char *shadow));
77 static int monitor_remove_breakpoint PARAMS ((CORE_ADDR addr, char *shadow));
78 static void monitor_kill PARAMS ((void));
79 static void monitor_load PARAMS ((char *file, int from_tty));
80 static void monitor_mourn_inferior PARAMS ((void));
81 static void monitor_stop PARAMS ((void));
82 static void monitor_debug PARAMS ((char *string));
83
84 static int monitor_read_memory PARAMS ((CORE_ADDR addr, char *myaddr,int len));
85 static int monitor_write_memory PARAMS ((CORE_ADDR addr, char *myaddr,int len));
86
87 static int from_hex PARAMS ((int a));
88 static unsigned long get_hex_word PARAMS ((void));
89
90 static struct monitor_ops *current_monitor;
91
92 static int hashmark;            /* flag set by "set hash" */
93
94 static int timeout = 30;
95
96 static int in_monitor_wait = 0; /* Non-zero means we are in monitor_wait() */
97
98 static void (*ofunc)();         /* Old SIGINT signal handler */
99
100 /* Descriptor for I/O to remote machine.  Initialize it to NULL so
101    that monitor_open knows that we don't have a file open when the
102    program starts.  */
103
104 static serial_t monitor_desc = NULL;
105
106 /* Pointer to regexp pattern matching data */
107
108 static struct re_pattern_buffer register_pattern;
109 static char register_fastmap[256];
110
111 static struct re_pattern_buffer getmem_resp_delim_pattern;
112 static char getmem_resp_delim_fastmap[256];
113
114 static int dump_reg_flag;       /* Non-zero means do a dump_registers cmd when
115                                    monitor_wait wakes up.  */
116
117 static DCACHE *remote_dcache;
118
119 /* monitor_debug is like fputs_unfiltered, except it prints special
120    characters in printable fashion.  */
121
122 static void
123 monitor_debug (string)
124      char *string;
125 {
126   int ch;
127
128   while ((ch = *string++) != '\0')
129     {
130       switch (ch) {
131       default:
132         if (isprint (ch))
133           fputc_unfiltered (ch, gdb_stderr);
134
135         else
136           fprintf_unfiltered (gdb_stderr, "\\%03o", ch);
137
138         break;
139
140       case '\\': fputs_unfiltered ("\\\\",  gdb_stderr);        break;  
141       case '\b': fputs_unfiltered ("\\b",   gdb_stderr);        break;  
142       case '\f': fputs_unfiltered ("\\f",   gdb_stderr);        break;  
143       case '\n': fputs_unfiltered ("\\n\n", gdb_stderr);        break;  
144       case '\r': fputs_unfiltered ("\\r\n", gdb_stderr);        break;  
145       case '\t': fputs_unfiltered ("\\t",   gdb_stderr);        break;  
146       case '\v': fputs_unfiltered ("\\v",   gdb_stderr);        break;  
147       }
148     }
149 }
150
151
152 /* monitor_printf_noecho -- Send data to monitor, but don't expect an echo.
153    Works just like printf.  */
154
155 void
156 #ifdef ANSI_PROTOTYPES
157 monitor_printf_noecho (char *pattern, ...)
158 #else
159 monitor_printf_noecho (va_alist)
160      va_dcl
161 #endif
162 {
163   va_list args;
164   char sndbuf[2000];
165   int len;
166
167 #if ANSI_PROTOTYPES
168   va_start (args, pattern);
169 #else
170   char *pattern;
171   va_start (args);
172   pattern = va_arg (args, char *);
173 #endif
174
175   vsprintf (sndbuf, pattern, args);
176
177   if (remote_debug > 0)
178     monitor_debug (sndbuf);
179
180   len = strlen (sndbuf);
181
182   if (len + 1 > sizeof sndbuf)
183     abort ();
184
185   if (SERIAL_WRITE(monitor_desc, sndbuf, len))
186     fprintf_unfiltered (stderr, "SERIAL_WRITE failed: %s\n", safe_strerror (errno));
187 }
188
189 /* monitor_printf -- Send data to monitor and check the echo.  Works just like
190    printf.  */
191
192 void
193 #ifdef ANSI_PROTOTYPES
194 monitor_printf (char *pattern, ...)
195 #else
196 monitor_printf (va_alist)
197      va_dcl
198 #endif
199 {
200   va_list args;
201   char sndbuf[2000];
202   int len;
203   int i, c;
204
205 #ifdef ANSI_PROTOTYPES
206   va_start (args, pattern);
207 #else
208   char *pattern;
209   va_start (args);
210   pattern = va_arg (args, char *);
211 #endif
212
213   vsprintf (sndbuf, pattern, args);
214
215   if (remote_debug > 0)
216     monitor_debug (sndbuf);
217
218   len = strlen (sndbuf);
219
220   if (len + 1 > sizeof sndbuf)
221     abort ();
222
223   if (SERIAL_WRITE(monitor_desc, sndbuf, len))
224     fprintf_unfiltered (stderr, "SERIAL_WRITE failed: %s\n", safe_strerror (errno));
225
226   for (i = 0; i < len; i++)
227     {
228     trycr:
229       c = readchar (timeout);
230
231       if (c != sndbuf[i])
232         {
233           /* Don't fail if we sent a ^C, they're never echoed */
234           if (sndbuf[i] == '\003')
235             continue;
236 #if 0
237           if (sndbuf[i] == '\r'
238               && c == '\n')
239             goto trycr;
240 #endif
241           warning ("monitor_printf:  Bad echo.  Sent: \"%s\", Got: \"%.*s%c\".",
242                  sndbuf, i, sndbuf, c);
243         }
244     }
245 }
246
247 /* Read a character from the remote system, doing all the fancy
248    timeout stuff.  */
249
250 static int
251 readchar (timeout)
252      int timeout;
253 {
254   int c;
255
256   c = SERIAL_READCHAR (monitor_desc, timeout);
257
258   if (remote_debug > 0)
259     fputc_unfiltered (c, gdb_stderr);
260
261   if (c >= 0)
262     return c & 0x7f;
263
264   if (c == SERIAL_TIMEOUT)
265 #ifdef MAINTENANCE_CMDS
266     if (in_monitor_wait)        /* Watchdog went off */
267       {
268         target_mourn_inferior ();
269         error ("Watchdog has expired.  Target detached.\n");
270       }
271     else
272 #endif
273       error ("Timeout reading from remote system.");
274
275   perror_with_name ("remote-monitor");
276 }
277
278 /* Scan input from the remote system, until STRING is found.  If BUF is non-
279    zero, then collect input until we have collected either STRING or BUFLEN-1
280    chars.  In either case we terminate BUF with a 0.  If input overflows BUF
281    because STRING can't be found, return -1, else return number of chars in BUF
282    (minus the terminating NUL).  Note that in the non-overflow case, STRING
283    will be at the end of BUF.  */
284
285 int
286 monitor_expect (string, buf, buflen)
287      char *string;
288      char *buf;
289      int buflen;
290 {
291   char *p = string;
292   int obuflen = buflen;
293   int c;
294
295   immediate_quit = 1;
296   while (1)
297     {
298       if (buf)
299         {
300           if (buflen < 2)
301             {
302               *buf = '\000';
303               immediate_quit = 0;
304               return -1;
305             }
306
307           c = readchar (timeout);
308           if (c == '\000')
309             continue;
310           *buf++ = c;
311           buflen--;
312         }
313       else
314         c = readchar (timeout);
315
316       if (c == *p++)
317         {
318           if (*p == '\0')
319             {
320               immediate_quit = 0;
321
322               if (buf)
323                 {
324                   *buf++ = '\000';
325                   return obuflen - buflen;
326                 }
327               else
328                 return 0;
329             }
330         }
331       else
332         {
333           p = string;
334           if (c == *p)
335             p++;
336         }
337     }
338 }
339
340 /* Search for a regexp.  */
341
342 int
343 monitor_expect_regexp (pat, buf, buflen)
344      struct re_pattern_buffer *pat;
345      char *buf;
346      int buflen;
347 {
348   char *mybuf;
349   char *p;
350
351   if (buf)
352     mybuf = buf;
353   else
354     {
355       mybuf = alloca (1024);
356       buflen = 1024;
357     }
358
359   p = mybuf;
360   while (1)
361     {
362       int retval;
363
364       if (p - mybuf >= buflen)
365         {                       /* Buffer about to overflow */
366
367 /* On overflow, we copy the upper half of the buffer to the lower half.  Not
368    great, but it usually works... */
369
370           memcpy (mybuf, mybuf + buflen / 2, buflen / 2);
371           p = mybuf + buflen / 2;
372         }
373
374       *p++ = readchar (timeout);
375
376       retval = re_search (pat, mybuf, p - mybuf, 0, p - mybuf, NULL);
377       if (retval >= 0)
378         return 1;
379     }
380 }
381
382 /* Keep discarding input until we see the MONITOR prompt.
383
384    The convention for dealing with the prompt is that you
385    o give your command
386    o *then* wait for the prompt.
387
388    Thus the last thing that a procedure does with the serial line
389    will be an monitor_expect_prompt().  Exception:  monitor_resume does not
390    wait for the prompt, because the terminal is being handed over
391    to the inferior.  However, the next thing which happens after that
392    is a monitor_wait which does wait for the prompt.
393    Note that this includes abnormal exit, e.g. error().  This is
394    necessary to prevent getting into states from which we can't
395    recover.  */
396
397 int
398 monitor_expect_prompt (buf, buflen)
399      char *buf;
400      int buflen;
401 {
402   return monitor_expect (PROMPT, buf, buflen);
403 }
404
405 /* Get N 32-bit words from remote, each preceded by a space, and put
406    them in registers starting at REGNO.  */
407
408 static unsigned long
409 get_hex_word ()
410 {
411   unsigned long val;
412   int i;
413   int ch;
414
415   do
416     ch = readchar (timeout);
417   while (isspace(ch));
418
419   val = from_hex (ch);
420
421   for (i = 7; i >= 1; i--)
422     {
423       ch = readchar (timeout);
424       if (!isxdigit (ch))
425         break;
426       val = (val << 4) | from_hex (ch);
427     }
428
429   return val;
430 }
431
432 static void
433 compile_pattern (pattern, compiled_pattern, fastmap)
434      char *pattern;
435      struct re_pattern_buffer *compiled_pattern;
436      char *fastmap;
437 {
438   int tmp;
439   char *val;
440
441   compiled_pattern->fastmap = fastmap;
442
443   tmp = re_set_syntax (RE_SYNTAX_EMACS);
444   val = re_compile_pattern (pattern,
445                             strlen (pattern),
446                             compiled_pattern);
447   re_set_syntax (tmp);
448
449   if (val)
450     error ("compile_pattern: Can't compile pattern string `%s': %s!", pattern, val);
451
452   if (fastmap)
453     re_compile_fastmap (compiled_pattern);
454 }
455
456 /* Open a connection to a remote debugger. NAME is the filename used
457    for communication.  */
458
459 static char *dev_name;
460 static struct target_ops *targ_ops;
461
462 void
463 monitor_open (args, mon_ops, from_tty)
464      char *args;
465      struct monitor_ops *mon_ops;
466      int from_tty;
467 {
468   char *name;
469   int i;
470   char **p;
471
472   if (mon_ops->magic != MONITOR_OPS_MAGIC)
473     error ("Magic number of monitor_ops struct wrong.");
474
475   targ_ops = mon_ops->target;
476   name = targ_ops->to_shortname;
477
478   if (!args)
479     error ("Use `target %s DEVICE-NAME' to use a serial port, or \n\
480 `target %s HOST-NAME:PORT-NUMBER' to use a network connection.", name, name);
481
482   target_preopen (from_tty);
483
484   /* Setup pattern for register dump */
485
486   if (mon_ops->register_pattern)
487     compile_pattern (mon_ops->register_pattern, &register_pattern,
488                      register_fastmap);
489
490   if (mon_ops->getmem.resp_delim)
491     compile_pattern (mon_ops->getmem.resp_delim, &getmem_resp_delim_pattern,
492                      getmem_resp_delim_fastmap);
493
494   unpush_target (targ_ops);
495
496   if (dev_name)
497     free (dev_name);
498   dev_name = strsave (args);
499
500   monitor_desc = SERIAL_OPEN (dev_name);
501
502   if (!monitor_desc)
503     perror_with_name (dev_name);
504
505   if (baud_rate != -1)
506     {
507       if (SERIAL_SETBAUDRATE (monitor_desc, baud_rate))
508         {
509           SERIAL_CLOSE (monitor_desc);
510           perror_with_name (dev_name);
511         }
512     }
513   
514   SERIAL_RAW (monitor_desc);
515
516   SERIAL_FLUSH_INPUT (monitor_desc);
517
518   /* some systems only work with 2 stop bits */
519
520   SERIAL_SETSTOPBITS (monitor_desc, mon_ops->stopbits);
521
522   current_monitor = mon_ops;
523
524   /* See if we can wake up the monitor.  First, try sending a stop sequence,
525      then send the init strings.  Last, remove all breakpoints.  */
526
527   if (current_monitor->stop)
528     {
529       monitor_stop ();
530       monitor_expect_prompt (NULL, 0);
531     }
532
533   /* wake up the monitor and see if it's alive */
534   for (p = mon_ops->init; *p != NULL; p++)
535     {
536       monitor_printf (*p);
537       monitor_expect_prompt (NULL, 0);
538     }
539
540   SERIAL_FLUSH_INPUT (monitor_desc);
541
542   /* Remove all breakpoints */
543
544   if (mon_ops->clr_all_break)
545     {
546       monitor_printf (mon_ops->clr_all_break);
547       monitor_expect_prompt (NULL, 0);
548     }
549
550   if (from_tty)
551     printf_unfiltered ("Remote target %s connected to %s\n", name, dev_name);
552
553   push_target (targ_ops);
554
555   inferior_pid = 42000;         /* Make run command think we are busy... */
556
557   /* Give monitor_wait something to read */
558
559   monitor_printf (current_monitor->line_term);
560
561   remote_dcache = dcache_init (monitor_read_memory, monitor_write_memory);
562
563   start_remote ();
564 }
565
566 /* Close out all files and local state before this target loses
567    control.  */
568
569 static void
570 monitor_close (quitting)
571      int quitting;
572 {
573   if (monitor_desc)
574     SERIAL_CLOSE (monitor_desc);
575   monitor_desc = NULL;
576 }
577
578 /* Terminate the open connection to the remote debugger.  Use this
579    when you want to detach and do something else with your gdb.  */
580
581 static void
582 monitor_detach (args, from_tty)
583      char *args;
584      int from_tty;
585 {
586   pop_target ();                /* calls monitor_close to do the real work */
587   if (from_tty)
588     printf_unfiltered ("Ending remote %s debugging\n", target_shortname);
589 }
590
591 /* Convert VALSTR into the target byte-ordered value of REGNO and store it.  */
592
593 char *
594 monitor_supply_register (regno, valstr)
595      int regno;
596      char *valstr;
597 {
598   unsigned LONGEST val;
599   unsigned char regbuf[MAX_REGISTER_RAW_SIZE];
600   char *p;
601
602   val = strtoul (valstr, &p, 16);
603
604   if (val == 0 && valstr == p)
605     error ("monitor_supply_register (%d):  bad value from monitor: %s.",
606            regno, valstr);
607
608   /* supply register stores in target byte order, so swap here */
609
610   store_unsigned_integer (regbuf, REGISTER_RAW_SIZE (regno), val);
611
612   supply_register (regno, regbuf);
613
614   return p;
615 }
616
617 /* Tell the remote machine to resume.  */
618
619 static void
620 monitor_resume (pid, step, sig)
621      int pid, step;
622      enum target_signal sig;
623 {
624   dcache_flush (remote_dcache);
625   if (step)
626     monitor_printf (STEP_CMD);
627   else
628     {
629       monitor_printf (CONT_CMD);
630       if (current_monitor->flags & MO_NEED_REGDUMP_AFTER_CONT)
631         dump_reg_flag = 1;
632     }
633 }
634
635 /* Parse the output of a register dump command.  A monitor specific regexp is
636    used to extract individual register descriptions of the form REG=VAL.  Each
637    description is split up into a name and a value string which are passed down
638    to monitor specific code.  */
639
640 static char *
641 parse_register_dump (buf, len)
642      char *buf;
643      int len;
644 {
645   while (1)
646     {
647       int regnamelen, vallen;
648       char *regname, *val;
649 /* Element 0 points to start of register name, and element 1 points to the
650    start of the register value.  */
651       struct re_registers register_strings;
652
653       if (re_search (&register_pattern, buf, len, 0, len,
654                      &register_strings) == -1)
655         break;
656
657       regnamelen = register_strings.end[1] - register_strings.start[1];
658       regname = buf + register_strings.start[1];
659       vallen = register_strings.end[2] - register_strings.start[2];
660       val = buf + register_strings.start[2];
661
662       current_monitor->supply_register (regname, regnamelen, val, vallen);
663
664       buf += register_strings.end[0];
665       len -= register_strings.end[0];
666     }
667 }
668
669 /* Send ^C to target to halt it.  Target will respond, and send us a
670    packet.  */
671
672 static void
673 monitor_interrupt (signo)
674      int signo;
675 {
676   /* If this doesn't work, try more severe steps.  */
677   signal (signo, monitor_interrupt_twice);
678   
679   if (remote_debug)
680     printf_unfiltered ("monitor_interrupt called\n");
681
682   target_stop ();
683 }
684
685 /* The user typed ^C twice.  */
686
687 static void
688 monitor_interrupt_twice (signo)
689      int signo;
690 {
691   signal (signo, ofunc);
692   
693   monitor_interrupt_query ();
694
695   signal (signo, monitor_interrupt);
696 }
697
698 /* Ask the user what to do when an interrupt is received.  */
699
700 static void
701 monitor_interrupt_query ()
702 {
703   target_terminal_ours ();
704
705   if (query ("Interrupted while waiting for the program.\n\
706 Give up (and stop debugging it)? "))
707     {
708       target_mourn_inferior ();
709       return_to_top_level (RETURN_QUIT);
710     }
711
712   target_terminal_inferior ();
713 }
714
715 static void
716 monitor_wait_cleanup (old_timeout)
717      int old_timeout;
718 {
719   timeout = old_timeout;
720   signal (SIGINT, ofunc);
721   in_monitor_wait = 0;
722 }
723
724 /* Wait until the remote machine stops, then return, storing status in
725    status just as `wait' would.  */
726
727 static int
728 monitor_wait (pid, status)
729      int pid;
730      struct target_waitstatus *status;
731 {
732   int old_timeout = timeout;
733   char buf[1024];
734   int resp_len;
735   struct cleanup *old_chain;
736
737   status->kind = TARGET_WAITKIND_EXITED;
738   status->value.integer = 0;
739
740   old_chain = make_cleanup (monitor_wait_cleanup, old_timeout);
741
742 #ifdef MAINTENANCE_CMDS
743   in_monitor_wait = 1;
744   timeout = watchdog > 0 ? watchdog : -1;
745 #else
746   timeout = -1;         /* Don't time out -- user program is running. */
747 #endif
748
749   ofunc = (void (*)()) signal (SIGINT, monitor_interrupt);
750
751   do
752     {
753       resp_len = monitor_expect_prompt (buf, sizeof (buf));
754
755       if (resp_len <= 0)
756         fprintf_unfiltered (gdb_stderr, "monitor_wait:  excessive response from monitor: %s.", buf);
757     }
758   while (resp_len < 0);
759
760   signal (SIGINT, ofunc);
761
762   timeout = old_timeout;
763
764   if (dump_reg_flag && current_monitor->dump_registers)
765     {
766       dump_reg_flag = 0;
767
768       monitor_printf (current_monitor->dump_registers);
769       resp_len = monitor_expect_prompt (buf, sizeof (buf));
770     }
771
772   if (current_monitor->register_pattern)
773     parse_register_dump (buf, resp_len);
774
775   status->kind = TARGET_WAITKIND_STOPPED;
776   status->value.sig = TARGET_SIGNAL_TRAP;
777
778   discard_cleanups (old_chain);
779
780   in_monitor_wait = 0;
781
782   return inferior_pid;
783 }
784
785 /* Fetch register REGNO, or all registers if REGNO is -1. Returns
786    errno value.  */
787
788 static void
789 monitor_fetch_register (regno)
790      int regno;
791 {
792   char *name;
793   static char zerobuf[MAX_REGISTER_RAW_SIZE] = {0};
794   char regbuf[MAX_REGISTER_RAW_SIZE * 2 + 1];
795   int i;
796
797   name = REGNAMES (regno);
798
799   if (!name)
800     {
801       supply_register (regno, zerobuf);
802       return;
803     }
804
805   /* send the register examine command */
806
807   monitor_printf (current_monitor->getreg.cmd, name);
808
809   /* If RESP_DELIM is specified, we search for that as a leading delimiter for
810      the register value.  Otherwise, we just start searching from the start of
811      the buf.  */
812
813   if (current_monitor->getreg.resp_delim)
814     monitor_expect (current_monitor->getreg.resp_delim, NULL, 0);
815
816   /* Read upto the maximum number of hex digits for this register, skipping
817      spaces, but stop reading if something else is seen.  Some monitors
818      like to drop leading zeros.  */
819
820   for (i = 0; i < REGISTER_RAW_SIZE (regno) * 2; i++)
821     {
822       int c;
823       c = readchar (timeout);
824       while (c == ' ')
825         c = readchar (timeout);
826
827       if (!isxdigit (c))
828         break;
829
830       regbuf[i] = c;
831     }
832
833   regbuf[i] = '\000';           /* terminate the number */
834
835   /* If TERM is present, we wait for that to show up.  Also, (if TERM is
836      present), we will send TERM_CMD if that is present.  In any case, we collect
837      all of the output into buf, and then wait for the normal prompt.  */
838
839   if (current_monitor->getreg.term)
840     {
841       monitor_expect (current_monitor->getreg.term, NULL, 0); /* get response */
842
843       if (current_monitor->getreg.term_cmd)
844         {
845           monitor_printf (current_monitor->getreg.term_cmd);
846           monitor_expect_prompt (NULL, 0);
847         }
848     }
849   else
850     monitor_expect_prompt (NULL, 0); /* get response */
851
852   monitor_supply_register (regno, regbuf);
853 }
854
855 /* Read the remote registers into the block regs.  */
856
857 static void monitor_dump_regs ()
858 {
859   if (current_monitor->dump_registers)
860     {
861       char buf[200];
862       int resp_len;
863       monitor_printf (current_monitor->dump_registers);
864       resp_len = monitor_expect_prompt (buf, sizeof (buf));
865       parse_register_dump (buf, resp_len);
866     }
867   else
868     abort(); /* Need some way to read registers */
869 }
870
871 static void
872 monitor_fetch_registers (regno)
873      int regno;
874 {
875   if (current_monitor->getreg.cmd) 
876     {
877       if (regno >= 0)
878         {
879           monitor_fetch_register (regno);
880           return;
881         }
882
883       for (regno = 0; regno < NUM_REGS; regno++)
884         monitor_fetch_register (regno);
885     }
886   else {
887     monitor_dump_regs ();
888   }
889 }
890
891 /* Store register REGNO, or all if REGNO == 0.  Return errno value.  */
892
893 static void
894 monitor_store_register (regno)
895      int regno;
896 {
897   char *name;
898   unsigned LONGEST val;
899
900   name = REGNAMES (regno);
901   if (!name)
902     return;
903
904   val = read_register (regno);
905
906  /* send the register deposit command */
907
908   monitor_printf (current_monitor->setreg.cmd, name, val);
909
910 /* It's possible that there are actually some monitors out there that will
911    prompt you when you set a register.  In that case, you may need to add some
912    code here to deal with TERM and TERM_CMD (see monitor_fetch_register to get
913    an idea of what's needed...) */
914
915   monitor_expect_prompt (NULL, 0);
916 }
917
918 /* Store the remote registers.  */
919
920 static void
921 monitor_store_registers (regno)
922      int regno;
923 {
924   if (regno >= 0)
925     {
926       monitor_store_register (regno);
927       return;
928     }
929
930   for (regno = 0; regno < NUM_REGS; regno++)
931     monitor_store_register (regno);
932 }
933
934 /* Get ready to modify the registers array.  On machines which store
935    individual registers, this doesn't need to do anything.  On machines
936    which store all the registers in one fell swoop, this makes sure
937    that registers contains all the registers from the program being
938    debugged.  */
939
940 static void
941 monitor_prepare_to_store ()
942 {
943   /* Do nothing, since we can store individual regs */
944 }
945
946 static void
947 monitor_files_info (ops)
948      struct target_ops *ops;
949 {
950   printf_unfiltered ("\tAttached to %s at %d baud.\n", dev_name, baud_rate);
951 }
952
953 static int
954 monitor_write_memory (memaddr, myaddr, len)
955      CORE_ADDR memaddr;
956      char *myaddr;
957      int len;
958 {
959   unsigned LONGEST val;
960   char *cmd;
961   int i;
962
963   /* Use memory fill command for leading 0 bytes.  */
964
965   if (current_monitor->fill)
966     {
967       for (i = 0; i < len; i++)
968         if (myaddr[i] != 0)
969           break;
970
971       if (i > 4)                /* More than 4 zeros is worth doing */
972         {
973           if (current_monitor->flags & MO_FILL_USES_ADDR)
974             monitor_printf (current_monitor->fill, memaddr, memaddr + i, 0);
975           else
976             monitor_printf (current_monitor->fill, memaddr, i, 0);
977
978           monitor_expect_prompt (NULL, 0);
979
980           return i;
981         }
982     }
983
984   if ((memaddr & 0x7) == 0 && len >= 8 && current_monitor->setmem.cmdll)
985     {
986       len = 8;
987       cmd = current_monitor->setmem.cmdll;
988     }
989   else if ((memaddr & 0x3) == 0 && len >= 4 && current_monitor->setmem.cmdl)
990     {
991       len = 4;
992       cmd = current_monitor->setmem.cmdl;
993     }
994   else if ((memaddr & 0x1) == 0 && len >= 2 && current_monitor->setmem.cmdw)
995     {
996       len = 2;
997       cmd = current_monitor->setmem.cmdw;
998     }
999   else
1000     {
1001       len = 1;
1002       cmd = current_monitor->setmem.cmdb;
1003     }
1004
1005   val = extract_unsigned_integer (myaddr, len);
1006
1007   monitor_printf (cmd, memaddr, val);
1008
1009   monitor_expect_prompt (NULL, 0);
1010
1011   return len;
1012 }
1013
1014 /* This is an alternate form of monitor_read_memory which is used for monitors
1015    which can only read a single byte/word/etc. at a time.  */
1016
1017 static int
1018 monitor_read_memory_single (memaddr, myaddr, len)
1019      CORE_ADDR memaddr;
1020      char *myaddr;
1021      int len;
1022 {
1023   unsigned LONGEST val;
1024   char membuf[sizeof(LONGEST) * 2 + 1];
1025   char *p;
1026   char *cmd;
1027   int i;
1028
1029   if ((memaddr & 0x7) == 0 && len >= 8 && current_monitor->getmem.cmdll)
1030     {
1031       len = 8;
1032       cmd = current_monitor->getmem.cmdll;
1033     }
1034   else if ((memaddr & 0x3) == 0 && len >= 4 && current_monitor->getmem.cmdl)
1035     {
1036       len = 4;
1037       cmd = current_monitor->getmem.cmdl;
1038     }
1039   else if ((memaddr & 0x1) == 0 && len >= 2 && current_monitor->getmem.cmdw)
1040     {
1041       len = 2;
1042       cmd = current_monitor->getmem.cmdw;
1043     }
1044   else
1045     {
1046       len = 1;
1047       cmd = current_monitor->getmem.cmdb;
1048     }
1049
1050 /* Send the examine command.  */
1051
1052   monitor_printf (cmd, memaddr);
1053
1054 /* If RESP_DELIM is specified, we search for that as a leading delimiter for
1055    the register value.  Otherwise, we just start searching from the start of
1056    the buf.  */
1057
1058   if (current_monitor->getmem.resp_delim)
1059     monitor_expect_regexp (getmem_resp_delim_pattern, NULL, 0);
1060
1061 /* Now, read the appropriate number of hex digits for this loc, skipping
1062    spaces.  */
1063
1064   for (i = 0; i < len * 2; i++)
1065     {
1066       int c;
1067
1068       while (1)
1069         {
1070           c = readchar (timeout);
1071           if (isxdigit (c))
1072             break;
1073           if (c == ' ')
1074             continue;
1075
1076           error ("monitor_read_memory_single (0x%x):  bad response from monitor: %.*s%c.",
1077                  memaddr, i, membuf, c);
1078         }
1079
1080       membuf[i] = c;
1081     }
1082
1083   membuf[i] = '\000';           /* terminate the number */
1084
1085 /* If TERM is present, we wait for that to show up.  Also, (if TERM is
1086    present), we will send TERM_CMD if that is present.  In any case, we collect
1087    all of the output into buf, and then wait for the normal prompt.  */
1088
1089   if (current_monitor->getmem.term)
1090     {
1091       monitor_expect (current_monitor->getmem.term, NULL, 0); /* get response */
1092
1093       if (current_monitor->getmem.term_cmd)
1094         {
1095           monitor_printf (current_monitor->getmem.term_cmd);
1096           monitor_expect_prompt (NULL, 0);
1097         }
1098     }
1099   else
1100     monitor_expect_prompt (NULL, 0); /* get response */
1101
1102   p = membuf;
1103   val = strtoul (membuf, &p, 16);
1104
1105   if (val == 0 && membuf == p)
1106     error ("monitor_read_memory_single (0x%x):  bad value from monitor: %s.",
1107            memaddr, membuf);
1108
1109   /* supply register stores in target byte order, so swap here */
1110
1111   store_unsigned_integer (myaddr, len, val);
1112
1113   return len;
1114 }
1115
1116 /* Copy LEN bytes of data from debugger memory at MYADDR to inferior's memory
1117    at MEMADDR.  Returns length moved.  Currently, we only do one byte at a
1118    time.  */
1119
1120 static int
1121 monitor_read_memory (memaddr, myaddr, len)
1122      CORE_ADDR memaddr;
1123      char *myaddr;
1124      int len;
1125 {
1126   unsigned LONGEST val;
1127   unsigned char regbuf[MAX_REGISTER_RAW_SIZE];
1128   char buf[512];
1129   char *p, *p1;
1130   char *name;
1131   int resp_len;
1132   int i;
1133
1134   if (current_monitor->flags & MO_GETMEM_READ_SINGLE)
1135     return monitor_read_memory_single (memaddr, myaddr, len);
1136
1137   len = min (len, 16);
1138
1139 /* See if xfer would cross a 16 byte boundary.  If so, clip it.  */
1140   if (((memaddr ^ (memaddr + len - 1)) & ~0xf) != 0)
1141     len = ((memaddr + len) & ~0xf) - memaddr;
1142
1143  /* send the memory examine command */
1144
1145   if (current_monitor->flags & MO_GETMEM_NEEDS_RANGE)
1146     monitor_printf (current_monitor->getmem.cmdb, memaddr, memaddr + len - 1);
1147   else
1148     monitor_printf (current_monitor->getmem.cmdb, memaddr, len);
1149
1150 /* If TERM is present, we wait for that to show up.  Also, (if TERM is
1151    present), we will send TERM_CMD if that is present.  In any case, we collect
1152    all of the output into buf, and then wait for the normal prompt.  */
1153
1154   if (current_monitor->getmem.term)
1155     {
1156       resp_len = monitor_expect (current_monitor->getmem.term, buf, sizeof buf); /* get response */
1157
1158       if (resp_len <= 0)
1159         error ("monitor_read_memory (0x%x):  excessive response from monitor: %.*s.",
1160                memaddr, resp_len, buf);
1161
1162       if (current_monitor->getmem.term_cmd)
1163         {
1164           SERIAL_WRITE (monitor_desc, current_monitor->getmem.term_cmd,
1165                         strlen (current_monitor->getmem.term_cmd));
1166           monitor_expect_prompt (NULL, 0);
1167         }
1168     }
1169   else
1170     resp_len = monitor_expect_prompt (buf, sizeof buf); /* get response */
1171
1172   p = buf;
1173
1174   /* If RESP_DELIM is specified, we search for that as a leading delimiter for
1175      the values.  Otherwise, we just start searching from the start of the buf.
1176    */
1177
1178   if (current_monitor->getmem.resp_delim)
1179     {
1180       int retval, tmp;
1181       struct re_registers resp_strings;
1182
1183       tmp = strlen (p);
1184       retval = re_search (&getmem_resp_delim_pattern, p, tmp, 0, tmp,
1185                           &resp_strings);
1186
1187       if (retval < 0)
1188         error ("monitor_read_memory (0x%x):  bad response from monitor: %.*s.",
1189                memaddr, resp_len, buf);
1190
1191       p += resp_strings.end[0];
1192 #if 0
1193       p = strstr (p, current_monitor->getmem.resp_delim);
1194       if (!p)
1195         error ("monitor_read_memory (0x%x):  bad response from monitor: %.*s.",
1196                memaddr, resp_len, buf);
1197       p += strlen (current_monitor->getmem.resp_delim);
1198 #endif
1199     }
1200
1201   for (i = len; i > 0; i--)
1202     {
1203       /* Skip non-hex chars, but bomb on end of string and newlines */
1204
1205       while (1)
1206         {
1207           if (isxdigit (*p))
1208             break;
1209           if (*p == '\000' || *p == '\n' || *p == '\r')
1210             error ("monitor_read_memory (0x%x):  badly terminated response from monitor: %.*s", memaddr, resp_len, buf);
1211           p++;
1212         }
1213
1214       val = strtoul (p, &p1, 16);
1215
1216       if (val == 0 && p == p1)
1217         error ("monitor_read_memory (0x%x):  bad value from monitor: %.*s.", memaddr,
1218                resp_len, buf);
1219
1220       *myaddr++ = val;
1221
1222       if (i == 1)
1223         break;
1224
1225       p = p1;
1226     }
1227
1228   return len;
1229 }
1230
1231 static int
1232 monitor_xfer_memory (memaddr, myaddr, len, write, target)
1233      CORE_ADDR memaddr;
1234      char *myaddr;
1235      int len;
1236      int write;
1237      struct target_ops *target;         /* ignored */
1238 {
1239   return dcache_xfer_memory (remote_dcache, memaddr, myaddr, len, write);
1240 }
1241
1242 static void
1243 monitor_kill ()
1244 {
1245   return;               /* ignore attempts to kill target system */
1246 }
1247
1248 /* All we actually do is set the PC to the start address of exec_bfd, and start
1249    the program at that point.  */
1250
1251 static void
1252 monitor_create_inferior (exec_file, args, env)
1253      char *exec_file;
1254      char *args;
1255      char **env;
1256 {
1257   if (args && (*args != '\000'))
1258     error ("Args are not supported by the monitor.");
1259
1260   clear_proceed_status ();
1261   proceed (bfd_get_start_address (exec_bfd), TARGET_SIGNAL_0, 0);
1262 }
1263
1264 /* Clean up when a program exits.
1265    The program actually lives on in the remote processor's RAM, and may be
1266    run again without a download.  Don't leave it full of breakpoint
1267    instructions.  */
1268
1269 static void
1270 monitor_mourn_inferior ()
1271 {
1272   unpush_target (targ_ops);
1273   generic_mourn_inferior ();    /* Do all the proper things now */
1274 }
1275
1276 #define NUM_MONITOR_BREAKPOINTS 8
1277
1278 static CORE_ADDR breakaddr[NUM_MONITOR_BREAKPOINTS] = {0};
1279
1280 /* Tell the monitor to add a breakpoint.  */
1281
1282 static int
1283 monitor_insert_breakpoint (addr, shadow)
1284      CORE_ADDR addr;
1285      char *shadow;
1286 {
1287   int i;
1288   static unsigned char break_insn[] = BREAKPOINT;
1289
1290   for (i = 0; i < NUM_MONITOR_BREAKPOINTS; i++)
1291     {
1292       if (breakaddr[i] == 0)
1293         {
1294           breakaddr[i] = addr;
1295           monitor_read_memory (addr, shadow, sizeof (break_insn));
1296           monitor_printf (SET_BREAK_CMD, addr);
1297           monitor_expect_prompt (NULL, 0);
1298           return 0;
1299         }
1300     }
1301
1302   error ("Too many breakpoints (> %d) for monitor.", NUM_MONITOR_BREAKPOINTS);
1303 }
1304
1305 /* Tell the monitor to remove a breakpoint.  */
1306
1307 static int
1308 monitor_remove_breakpoint (addr, shadow)
1309      CORE_ADDR addr;
1310      char *shadow;
1311 {
1312   int i;
1313
1314   for (i = 0; i < NUM_MONITOR_BREAKPOINTS; i++)
1315     {
1316       if (breakaddr[i] == addr)
1317         {
1318           breakaddr[i] = 0;
1319           /* some monitors remove breakpoints based on the address */
1320           if (current_monitor->flags & MO_CLR_BREAK_USES_ADDR)   
1321             monitor_printf (CLR_BREAK_CMD, addr);
1322           else
1323             monitor_printf (CLR_BREAK_CMD, i);
1324           monitor_expect_prompt (NULL, 0);
1325           return 0;
1326         }
1327     }
1328   fprintf_unfiltered (stderr, "Can't find breakpoint associated with 0x%x\n", addr);
1329   return 1;
1330 }
1331
1332 /* monitor_load -- download a file. */
1333
1334 static void
1335 monitor_load (file, from_tty)
1336     char *file;
1337     int  from_tty;
1338 {
1339   dcache_flush (remote_dcache);
1340
1341   if (current_monitor->load_routine)
1342     current_monitor->load_routine (monitor_desc, file, hashmark);
1343   else
1344     {                           /* The default is ascii S-records */
1345       monitor_printf (LOAD_CMD);        /* tell the monitor to load */
1346       if (current_monitor->loadresp)
1347         monitor_expect (current_monitor->loadresp, NULL, 0);
1348
1349       load_srec (monitor_desc, file, 32, SREC_ALL, hashmark);
1350
1351       monitor_expect_prompt (NULL, 0);
1352     }
1353
1354 /* Finally, make the PC point at the start address */
1355
1356   if (exec_bfd)
1357     write_pc (bfd_get_start_address (exec_bfd));
1358
1359   inferior_pid = 0;             /* No process now */
1360
1361 /* This is necessary because many things were based on the PC at the time that
1362    we attached to the monitor, which is no longer valid now that we have loaded
1363    new code (and just changed the PC).  Another way to do this might be to call
1364    normal_stop, except that the stack may not be valid, and things would get
1365    horribly confused... */
1366
1367   clear_symtab_users ();
1368 }
1369
1370 static void
1371 monitor_stop ()
1372 {
1373   if (current_monitor->stop)
1374     monitor_printf_noecho (current_monitor->stop);
1375 }
1376
1377 /* Put a command string, in args, out to MONITOR.  Output from MONITOR
1378    is placed on the users terminal until the prompt is seen. FIXME: We
1379    read the characters ourseleves here cause of a nasty echo.  */
1380
1381 static void
1382 monitor_command (args, from_tty)
1383      char *args;
1384      int from_tty;
1385 {
1386   char *p;
1387   int resp_len;
1388   char buf[1000];
1389
1390   if (monitor_desc == NULL)
1391     error ("monitor target not open.");
1392
1393   p = PROMPT;
1394
1395   /* Send the command.  Note that if no args were supplied, then we're
1396      just sending the monitor a newline, which is sometimes useful.  */
1397
1398   monitor_printf ("%s\r", (args ? args : ""));
1399
1400   resp_len = monitor_expect_prompt (buf, sizeof buf);
1401
1402   fputs_unfiltered (buf, gdb_stdout); /* Output the response */
1403 }
1404
1405 /* Convert hex digit A to a number.  */
1406
1407 static int
1408 from_hex (a)
1409      int a;
1410 {  
1411   if (a >= '0' && a <= '9')
1412     return a - '0';
1413   if (a >= 'a' && a <= 'f')
1414     return a - 'a' + 10;
1415   if (a >= 'A' && a <= 'F')
1416     return a - 'A' + 10;
1417
1418   error ("Reply contains invalid hex digit 0x%x", a);
1419 }
1420
1421 static struct target_ops monitor_ops =
1422 {
1423   NULL,                         /* to_shortname */
1424   NULL,                         /* to_longname */
1425   NULL,                         /* to_doc */
1426   NULL,                         /* to_open */
1427   monitor_close,                /* to_close */
1428   NULL,                         /* to_attach */
1429   monitor_detach,               /* to_detach */
1430   monitor_resume,               /* to_resume */
1431   monitor_wait,                 /* to_wait */
1432   monitor_fetch_registers,      /* to_fetch_registers */
1433   monitor_store_registers,      /* to_store_registers */
1434   monitor_prepare_to_store,     /* to_prepare_to_store */
1435   monitor_xfer_memory,          /* to_xfer_memory */
1436   monitor_files_info,           /* to_files_info */
1437   monitor_insert_breakpoint,    /* to_insert_breakpoint */
1438   monitor_remove_breakpoint,    /* to_remove_breakpoint */
1439   0,                            /* to_terminal_init */
1440   0,                            /* to_terminal_inferior */
1441   0,                            /* to_terminal_ours_for_output */
1442   0,                            /* to_terminal_ours */
1443   0,                            /* to_terminal_info */
1444   monitor_kill,                 /* to_kill */
1445   monitor_load,                 /* to_load */
1446   0,                            /* to_lookup_symbol */
1447   monitor_create_inferior,      /* to_create_inferior */
1448   monitor_mourn_inferior,       /* to_mourn_inferior */
1449   0,                            /* to_can_run */
1450   0,                            /* to_notice_signals */
1451   0,                            /* to_thread_alive */
1452   monitor_stop,                 /* to_stop */
1453   process_stratum,              /* to_stratum */
1454   0,                            /* to_next */
1455   1,                            /* to_has_all_memory */
1456   1,                            /* to_has_memory */
1457   1,                            /* to_has_stack */
1458   1,                            /* to_has_registers */
1459   1,                            /* to_has_execution */
1460   0,                            /* sections */
1461   0,                            /* sections_end */
1462   OPS_MAGIC                     /* to_magic */
1463 };
1464
1465 /* Init the target_ops structure pointed at by OPS */
1466
1467 void
1468 init_monitor_ops (ops)
1469      struct target_ops *ops;
1470 {
1471   memcpy (ops, &monitor_ops, sizeof monitor_ops);
1472 }
1473
1474 /* Define additional commands that are usually only used by monitors.  */
1475
1476 void
1477 _initialize_remote_monitors ()
1478 {
1479   add_show_from_set (add_set_cmd ("hash", no_class, var_boolean,
1480                                   (char *)&hashmark,
1481                                   "Set display of activity while downloading a file.\n\
1482 When enabled, a hashmark \'#\' is displayed.",
1483                                   &setlist),
1484                      &showlist);
1485
1486   add_com ("monitor", class_obscure, monitor_command,
1487            "Send a command to the debug monitor."); 
1488 }