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