Wed Apr 29 10:20:40 1998 John Metzler <jmetzler@cygnus.com>
[external/binutils.git] / gdb / monitor.c
1 /* Remote debugging interface for boot monitors, for GDB.
2    Copyright 1990, 1991, 1992, 1993, 1995, 1996, 1997
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 char *dev_name;
63 static struct target_ops *targ_ops;
64
65 static void monitor_vsprintf PARAMS ((char *sndbuf, char *pattern, va_list args));
66
67 static int readchar PARAMS ((int timeout));
68
69 static void monitor_command PARAMS ((char *args, int fromtty));
70
71 static void monitor_fetch_register PARAMS ((int regno));
72 static void monitor_store_register PARAMS ((int regno));
73
74 static void monitor_detach PARAMS ((char *args, int from_tty));
75 static void monitor_resume PARAMS ((int pid, int step, enum target_signal sig));
76 static void monitor_interrupt PARAMS ((int signo));
77 static void monitor_interrupt_twice PARAMS ((int signo));
78 static void monitor_interrupt_query PARAMS ((void));
79 static void monitor_wait_cleanup PARAMS ((int old_timeout));
80
81 static int monitor_wait PARAMS ((int pid, struct target_waitstatus *status));
82 static void monitor_fetch_registers PARAMS ((int regno));
83 static void monitor_store_registers PARAMS ((int regno));
84 static void monitor_prepare_to_store PARAMS ((void));
85 static int monitor_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr, int len, int write, struct target_ops *target));
86 static void monitor_files_info PARAMS ((struct target_ops *ops));
87 static int monitor_insert_breakpoint PARAMS ((CORE_ADDR addr, char *shadow));
88 static int monitor_remove_breakpoint PARAMS ((CORE_ADDR addr, char *shadow));
89 static void monitor_kill PARAMS ((void));
90 static void monitor_load PARAMS ((char *file, int from_tty));
91 static void monitor_mourn_inferior PARAMS ((void));
92 static void monitor_stop PARAMS ((void));
93
94 static int monitor_read_memory PARAMS ((CORE_ADDR addr, char *myaddr,int len));
95 static int monitor_write_memory PARAMS ((CORE_ADDR addr, char *myaddr,int len));
96 static int monitor_write_memory_bytes PARAMS ((CORE_ADDR addr,
97                                                char *myaddr,int len));
98 static int monitor_write_memory_block PARAMS((
99                                               CORE_ADDR memaddr ,
100                                               char * myaddr ,
101                                               int len)) ;
102 static int monitor_expect_regexp PARAMS ((struct re_pattern_buffer *pat,
103                                           char *buf, int buflen));
104 static void monitor_dump_regs PARAMS((void)) ;
105 #if 0
106 static int from_hex PARAMS ((int a));
107 static unsigned long get_hex_word PARAMS ((void));
108 #endif
109 static void parse_register_dump PARAMS ((char *, int));
110
111 static struct monitor_ops *current_monitor;
112
113 static int hashmark;            /* flag set by "set hash" */
114
115 static int timeout = 30;
116
117 static int in_monitor_wait = 0; /* Non-zero means we are in monitor_wait() */
118
119 static void (*ofunc)();         /* Old SIGINT signal handler */
120
121 /* Extra remote debugging for developing a new rom monitor variation */
122 #if ! defined(EXTRA_RDEBUG)
123 #define EXTRA_RDEBUG 1
124 #endif
125 #if EXTRA_RDEBUG
126 #define RDEBUG(stuff) { if (remote_debug) printf stuff ; }
127 #else
128 #define RDEBUG(stuff) {}
129 #endif
130
131 /* Descriptor for I/O to remote machine.  Initialize it to NULL so
132    that monitor_open knows that we don't have a file open when the
133    program starts.  */
134
135 static serial_t monitor_desc = NULL;
136
137 /* Pointer to regexp pattern matching data */
138
139 static struct re_pattern_buffer register_pattern;
140 static char register_fastmap[256];
141
142 static struct re_pattern_buffer getmem_resp_delim_pattern;
143 static char getmem_resp_delim_fastmap[256];
144
145 static int dump_reg_flag;       /* Non-zero means do a dump_registers cmd when
146                                    monitor_wait wakes up.  */
147
148 static DCACHE *remote_dcache;
149 static int first_time=0;        /* is this the first time we're executing after 
150                                         gaving created the child proccess? */
151
152 /* Convert hex digit A to a number.  */
153
154 static int
155 fromhex (a)
156      int a;
157 {
158   if (a >= '0' && a <= '9')
159     return a - '0';
160   else if (a >= 'a' && a <= 'f')
161     return a - 'a' + 10;
162   else
163     if (a >= 'A' && a <= 'F')
164       return a - 'A' + 10 ;
165   else error ("Invalid hex digit %d", a);
166 }
167
168 /* monitor_vsprintf - similar to vsprintf but handles 64-bit addresses
169
170    This function exists to get around the problem that many host platforms
171    don't have a printf that can print 64-bit addresses.  The %A format
172    specification is recognized as a special case, and causes the argument
173    to be printed as a 64-bit hexadecimal address.
174
175    Only format specifiers of the form "[0-9]*[a-z]" are recognized.
176    If it is a '%s' format, the argument is a string; otherwise the
177    argument is assumed to be a long integer.
178 */
179   
180 static void
181 monitor_vsprintf (sndbuf, pattern, args)
182      char *sndbuf;
183      char *pattern;
184      va_list args;
185 {
186   char format[10];
187   char fmt;
188   char *p;
189   int i;
190   long arg_int;
191   CORE_ADDR arg_addr;
192   char *arg_string;
193
194   for (p = pattern; *p; p++)
195     {
196       if (*p == '%')
197         {
198           /* Copy the format specifier to a separate buffer.  */
199           format[0] = *p++;
200           for (i = 1; *p >= '0' && *p <= '9' && i < (int) sizeof (format) - 2;
201                i++, p++)
202             format[i] = *p;
203           format[i] = fmt = *p;
204           format[i+1] = '\0';
205
206           /* Fetch the next argument and print it.  */
207           switch (fmt)
208             {
209             case 'A':
210               arg_addr = va_arg (args, CORE_ADDR);
211               strcpy (sndbuf, paddr_nz (arg_addr));
212               break;
213             case 's':
214               arg_string = va_arg (args, char *);
215               sprintf (sndbuf, format, arg_string);
216               break;
217             default:
218               arg_int = va_arg (args, long);
219               sprintf (sndbuf, format, arg_int);
220               break;
221             }
222           sndbuf += strlen (sndbuf);
223         }
224       else
225         *sndbuf++ = *p;
226     }
227   *sndbuf = '\0';
228 }
229
230
231 /* monitor_printf_noecho -- Send data to monitor, but don't expect an echo.
232    Works just like printf.  */
233
234 void
235 #ifdef ANSI_PROTOTYPES
236 monitor_printf_noecho (char *pattern, ...)
237 #else
238 monitor_printf_noecho (va_alist)
239      va_dcl
240 #endif
241 {
242   va_list args;
243   char sndbuf[2000];
244   int len;
245
246 #if ANSI_PROTOTYPES
247   va_start (args, pattern);
248 #else
249   char *pattern;
250   va_start (args);
251   pattern = va_arg (args, char *);
252 #endif
253
254   monitor_vsprintf (sndbuf, pattern, args);
255
256 #if 0
257   if (remote_debug > 0)
258     puts_debug ("sent -->", sndbuf, "<--");
259 #endif
260   RDEBUG(("sent[%s]\n",sndbuf)) ;
261   
262   len = strlen (sndbuf);
263
264   if (len + 1 > sizeof sndbuf)
265     abort ();
266
267   monitor_write (sndbuf, len);
268 }
269
270 /* monitor_printf -- Send data to monitor and check the echo.  Works just like
271    printf.  */
272
273 void
274 #ifdef ANSI_PROTOTYPES
275 monitor_printf (char *pattern, ...)
276 #else
277 monitor_printf (va_alist)
278      va_dcl
279 #endif
280 {
281   va_list args;
282   char sndbuf[2000];
283   int len;
284
285 #ifdef ANSI_PROTOTYPES
286   va_start (args, pattern);
287 #else
288   char *pattern;
289   va_start (args);
290   pattern = va_arg (args, char *);
291 #endif
292
293   monitor_vsprintf (sndbuf, pattern, args);
294
295 #if 0
296   if (remote_debug > 0)
297     puts_debug ("sent -->", sndbuf, "<--");
298 #endif
299   RDEBUG(("sent[%s]\n",sndbuf)) 
300   len = strlen (sndbuf);
301   if (len + 1 > sizeof sndbuf)
302     abort ();
303
304   monitor_write (sndbuf, len);
305
306   /* We used to expect that the next immediate output was the characters we
307      just output, but sometimes some extra junk appeared before the characters
308      we expected, like an extra prompt, or a portmaster sending telnet negotiations.
309      So, just start searching for what we sent, and skip anything unknown.  */
310   RDEBUG(("ExpectEcho\n"))
311   monitor_expect (sndbuf, (char *)0, 0);
312 }
313
314
315 /* Write characters to the remote system.  */
316
317 void
318 monitor_write (buf, buflen)
319      char *buf;
320      int buflen;
321 {
322   if (SERIAL_WRITE(monitor_desc, buf, buflen))
323     fprintf_unfiltered (stderr, "SERIAL_WRITE failed: %s\n", safe_strerror (errno));
324 }
325
326
327 /* Read a binary character from the remote system, doing all the fancy
328    timeout stuff, but without interpreting the character in any way,
329    and without printing remote debug information.  */
330
331 int
332 monitor_readchar ()
333 {
334   int c;
335   int looping;
336
337   do
338     {
339       looping = 0;
340       c = SERIAL_READCHAR (monitor_desc, timeout);
341
342       if (c >= 0)
343         c &= 0xff;                      /* don't lose bit 7 */
344     }
345   while (looping);
346
347   if (c >= 0)
348     return c;
349
350   if (c == SERIAL_TIMEOUT)
351       error ("Timeout reading from remote system.");
352
353   perror_with_name ("remote-monitor");
354 }
355
356
357 /* Read a character from the remote system, doing all the fancy
358    timeout stuff.  */
359
360 static int
361 readchar (timeout)
362      int timeout;
363 {
364   int c;
365   static enum { last_random, last_nl, last_cr, last_crnl } state = last_random;
366   int looping;
367
368   do
369     {
370       looping = 0;
371       c = SERIAL_READCHAR (monitor_desc, timeout);
372
373       if (c >= 0)
374         {
375           c &= 0x7f;
376 #if 0
377           /* This seems to interfere with proper function of the
378              input stream */
379           if (remote_debug > 0)
380             {
381               char buf[2];
382               buf[0] = c;
383               buf[1] = '\0';
384               puts_debug ("read -->", buf, "<--");
385             }
386           
387 #endif    
388         }
389
390       /* Canonicialize \n\r combinations into one \r */
391       if ((current_monitor->flags & MO_HANDLE_NL) != 0)
392         {
393           if ((c == '\r' && state == last_nl)
394               || (c == '\n' && state == last_cr))
395             {
396               state = last_crnl;
397               looping = 1;
398             }
399           else if (c == '\r')
400             state = last_cr;
401           else if (c != '\n')
402             state = last_random;
403           else
404             {
405               state = last_nl;
406               c = '\r';
407             }
408         }
409     }
410   while (looping);
411
412   if (c >= 0)
413     return c;
414
415   if (c == SERIAL_TIMEOUT)
416 #if 0 /* MAINTENANCE_CMDS */
417     /* I fail to see how detaching here can be useful
418     if (in_monitor_wait)        /* Watchdog went off */
419       {
420         target_mourn_inferior ();
421         error ("GDB serial timeout has expired.  Target detached.\n");
422       }
423     else
424 #endif
425       error ("Timeout reading from remote system.");
426
427   perror_with_name ("remote-monitor");
428 }
429
430 /* Scan input from the remote system, until STRING is found.  If BUF is non-
431    zero, then collect input until we have collected either STRING or BUFLEN-1
432    chars.  In either case we terminate BUF with a 0.  If input overflows BUF
433    because STRING can't be found, return -1, else return number of chars in BUF
434    (minus the terminating NUL).  Note that in the non-overflow case, STRING
435    will be at the end of BUF.  */
436
437 int
438 monitor_expect (string, buf, buflen)
439      char *string;
440      char *buf;
441      int buflen;
442 {
443   char *p = string;
444   int obuflen = buflen;
445   int c;
446   extern struct target_ops *targ_ops;
447   RDEBUG(("MON Expecting '%s'\n",string)) ;
448
449   immediate_quit = 1;
450   while (1)
451     {
452       if (buf)
453         {
454           if (buflen < 2)
455             {
456               *buf = '\000';
457               immediate_quit = 0;
458               return -1;
459             }
460
461           c = readchar (timeout);
462           if (c == '\000')
463             continue;
464           *buf++ = c;
465           buflen--;
466         }
467       else
468         c = readchar (timeout);
469
470       /* Don't expect any ^C sent to be echoed */
471         
472       if (*p == '\003' || c == *p)
473         {
474           p++;
475           if (*p == '\0')
476             {
477               immediate_quit = 0;
478
479               if (buf)
480                 {
481                   *buf++ = '\000';
482                   return obuflen - buflen;
483                 }
484               else
485                 return 0;
486             }
487         }
488       else if ((c == '\021' || c == '\023') &&
489                (strcmp(targ_ops->to_shortname, "m32r") == 0))
490         { /* m32r monitor emits random DC1/DC3 chars */
491           continue;
492         }
493       else
494         {
495           p = string;
496           if (c == *p)
497             p++;
498         }
499     }
500 }
501
502 /* Search for a regexp.  */
503
504 static int
505 monitor_expect_regexp (pat, buf, buflen)
506      struct re_pattern_buffer *pat;
507      char *buf;
508      int buflen;
509 {
510   char *mybuf;
511   char *p;
512   RDEBUG(("MON Expecting regexp\n")) ;
513   if (buf)
514     mybuf = buf;
515   else
516     {
517       mybuf = alloca (1024);
518       buflen = 1024;
519     }
520
521   p = mybuf;
522   while (1)
523     {
524       int retval;
525
526       if (p - mybuf >= buflen)
527         {                       /* Buffer about to overflow */
528
529 /* On overflow, we copy the upper half of the buffer to the lower half.  Not
530    great, but it usually works... */
531
532           memcpy (mybuf, mybuf + buflen / 2, buflen / 2);
533           p = mybuf + buflen / 2;
534         }
535
536       *p++ = readchar (timeout);
537
538       retval = re_search (pat, mybuf, p - mybuf, 0, p - mybuf, NULL);
539       if (retval >= 0)
540         return 1;
541     }
542 }
543
544 /* Keep discarding input until we see the MONITOR prompt.
545
546    The convention for dealing with the prompt is that you
547    o give your command
548    o *then* wait for the prompt.
549
550    Thus the last thing that a procedure does with the serial line will
551    be an monitor_expect_prompt().  Exception: monitor_resume does not
552    wait for the prompt, because the terminal is being handed over to
553    the inferior.  However, the next thing which happens after that is
554    a monitor_wait which does wait for the prompt.  Note that this
555    includes abnormal exit, e.g. error().  This is necessary to prevent
556    getting into states from which we can't recover.  */
557
558 int
559 monitor_expect_prompt (buf, buflen)
560      char *buf;
561      int buflen;
562 {
563   RDEBUG(("MON Expecting prompt\n"))
564   return monitor_expect (current_monitor->prompt, buf, buflen);
565 }
566
567 /* Get N 32-bit words from remote, each preceded by a space, and put
568    them in registers starting at REGNO.  */
569
570 #if 0
571 static unsigned long
572 get_hex_word ()
573 {
574   unsigned long val;
575   int i;
576   int ch;
577
578   do
579     ch = readchar (timeout);
580   while (isspace(ch));
581
582   val = from_hex (ch);
583
584   for (i = 7; i >= 1; i--)
585     {
586       ch = readchar (timeout);
587       if (!isxdigit (ch))
588         break;
589       val = (val << 4) | from_hex (ch);
590     }
591
592   return val;
593 }
594 #endif
595
596 static void
597 compile_pattern (pattern, compiled_pattern, fastmap)
598      char *pattern;
599      struct re_pattern_buffer *compiled_pattern;
600      char *fastmap;
601 {
602   int tmp;
603   char *val;
604
605   compiled_pattern->fastmap = fastmap;
606
607   tmp = re_set_syntax (RE_SYNTAX_EMACS);
608   val = re_compile_pattern (pattern,
609                             strlen (pattern),
610                             compiled_pattern);
611   re_set_syntax (tmp);
612
613   if (val)
614     error ("compile_pattern: Can't compile pattern string `%s': %s!", pattern, val);
615
616   if (fastmap)
617     re_compile_fastmap (compiled_pattern);
618 }
619
620 /* Open a connection to a remote debugger. NAME is the filename used
621    for communication.  */
622
623 void
624 monitor_open (args, mon_ops, from_tty)
625      char *args;
626      struct monitor_ops *mon_ops;
627      int from_tty;
628 {
629   char *name;
630   char **p;
631
632   if (mon_ops->magic != MONITOR_OPS_MAGIC)
633     error ("Magic number of monitor_ops struct wrong.");
634
635   targ_ops = mon_ops->target;
636   name = targ_ops->to_shortname;
637
638   if (!args)
639     error ("Use `target %s DEVICE-NAME' to use a serial port, or \n\
640 `target %s HOST-NAME:PORT-NUMBER' to use a network connection.", name, name);
641
642   target_preopen (from_tty);
643
644   /* Setup pattern for register dump */
645
646   if (mon_ops->register_pattern)
647     compile_pattern (mon_ops->register_pattern, &register_pattern,
648                      register_fastmap);
649
650   if (mon_ops->getmem.resp_delim)
651     compile_pattern (mon_ops->getmem.resp_delim, &getmem_resp_delim_pattern,
652                      getmem_resp_delim_fastmap);
653
654   unpush_target (targ_ops);
655
656   if (dev_name)
657     free (dev_name);
658   dev_name = strsave (args);
659
660   monitor_desc = SERIAL_OPEN (dev_name);
661
662   if (!monitor_desc)
663     perror_with_name (dev_name);
664
665   if (baud_rate != -1)
666     {
667       if (SERIAL_SETBAUDRATE (monitor_desc, baud_rate))
668         {
669           SERIAL_CLOSE (monitor_desc);
670           perror_with_name (dev_name);
671         }
672     }
673   
674   SERIAL_RAW (monitor_desc);
675
676   SERIAL_FLUSH_INPUT (monitor_desc);
677
678   /* some systems only work with 2 stop bits */
679
680   SERIAL_SETSTOPBITS (monitor_desc, mon_ops->stopbits);
681
682   current_monitor = mon_ops;
683
684   /* See if we can wake up the monitor.  First, try sending a stop sequence,
685      then send the init strings.  Last, remove all breakpoints.  */
686
687   if (current_monitor->stop)
688     {
689       monitor_stop ();
690       if ((current_monitor->flags & MO_NO_ECHO_ON_OPEN) == 0)
691         {
692           RDEBUG(("EXP Open echo\n")) ;
693           monitor_expect_prompt (NULL, 0); 
694       }
695     }
696
697   /* wake up the monitor and see if it's alive */
698   for (p = mon_ops->init; *p != NULL; p++)
699     {
700       /* Some of the characters we send may not be echoed,
701          but we hope to get a prompt at the end of it all. */
702          
703       if ((current_monitor->flags & MO_NO_ECHO_ON_OPEN) == 0)
704         monitor_printf(*p); 
705       else
706         monitor_printf_noecho (*p);
707       monitor_expect_prompt (NULL, 0);
708     }
709
710   SERIAL_FLUSH_INPUT (monitor_desc);
711
712   /* Remove all breakpoints */
713
714   if (mon_ops->clr_all_break)
715     {
716       monitor_printf (mon_ops->clr_all_break);
717       monitor_expect_prompt (NULL, 0);
718     }
719
720   if (from_tty)
721     printf_unfiltered ("Remote target %s connected to %s\n", name, dev_name);
722
723   push_target (targ_ops);
724
725   inferior_pid = 42000;         /* Make run command think we are busy... */
726
727   /* Give monitor_wait something to read */
728
729   monitor_printf (current_monitor->line_term);
730
731   if (current_monitor->flags & MO_HAS_BLOCKWRITES)
732     remote_dcache = dcache_init (monitor_read_memory, monitor_write_memory_block);
733   else
734     remote_dcache = dcache_init (monitor_read_memory, monitor_write_memory);
735   start_remote ();
736 }
737
738 /* Close out all files and local state before this target loses
739    control.  */
740
741 void
742 monitor_close (quitting)
743      int quitting;
744 {
745   if (monitor_desc)
746     SERIAL_CLOSE (monitor_desc);
747   monitor_desc = NULL;
748 }
749
750 /* Terminate the open connection to the remote debugger.  Use this
751    when you want to detach and do something else with your gdb.  */
752
753 static void
754 monitor_detach (args, from_tty)
755      char *args;
756      int from_tty;
757 {
758   pop_target ();                /* calls monitor_close to do the real work */
759   if (from_tty)
760     printf_unfiltered ("Ending remote %s debugging\n", target_shortname);
761 }
762
763 /* Convert VALSTR into the target byte-ordered value of REGNO and store it.  */
764
765 char *
766 monitor_supply_register (regno, valstr)
767      int regno;
768      char *valstr;
769 {
770   unsigned int val;
771   unsigned char regbuf[MAX_REGISTER_RAW_SIZE];
772   char *p;
773
774   val = strtoul (valstr, &p, 16);
775   RDEBUG(("Supplying Register %d %s\n",regno,valstr)) ;
776
777   if (val == 0 && valstr == p)
778     error ("monitor_supply_register (%d):  bad value from monitor: %s.",
779            regno, valstr);
780
781   /* supply register stores in target byte order, so swap here */
782
783   store_unsigned_integer (regbuf, REGISTER_RAW_SIZE (regno), val);
784
785   supply_register (regno, regbuf);
786
787   return p;
788 }
789
790 /* Tell the remote machine to resume.  */
791
792 int flush_monitor_dcache(void) {  dcache_flush (remote_dcache); }
793
794 static void
795 monitor_resume (pid, step, sig)
796      int pid, step;
797      enum target_signal sig;
798 {
799   /* Some monitors require a different command when starting a program */
800   RDEBUG(("MON resume\n")) ;
801   if (current_monitor->flags & MO_RUN_FIRST_TIME && first_time == 1)
802     {
803       first_time = 0;
804       monitor_printf ("run\r");
805       if (current_monitor->flags & MO_NEED_REGDUMP_AFTER_CONT)
806             dump_reg_flag = 1;
807       return;
808     }
809   dcache_flush (remote_dcache);
810   if (step)
811     monitor_printf (current_monitor->step);
812   else
813     {
814       if (current_monitor->continue_hook)
815         (*current_monitor->continue_hook)() ;
816       else monitor_printf (current_monitor->cont);
817       if (current_monitor->flags & MO_NEED_REGDUMP_AFTER_CONT)
818         dump_reg_flag = 1;
819     }
820 }
821
822 /* Parse the output of a register dump command.  A monitor specific
823    regexp is used to extract individual register descriptions of the
824    form REG=VAL.  Each description is split up into a name and a value
825    string which are passed down to monitor specific code.  */
826
827 static void
828 parse_register_dump (buf, len)
829      char *buf;
830      int len;
831 {
832   RDEBUG(("MON Parsing  register dump\n")) 
833   while (1)
834     {
835       int regnamelen, vallen;
836       char *regname, *val;
837       /* Element 0 points to start of register name, and element 1
838          points to the start of the register value.  */
839       struct re_registers register_strings;
840
841       if (re_search (&register_pattern, buf, len, 0, len,
842                      &register_strings) == -1)
843         break;
844
845       regnamelen = register_strings.end[1] - register_strings.start[1];
846       regname = buf + register_strings.start[1];
847       vallen = register_strings.end[2] - register_strings.start[2];
848       val = buf + register_strings.start[2];
849
850       current_monitor->supply_register (regname, regnamelen, val, vallen);
851
852       buf += register_strings.end[0];
853       len -= register_strings.end[0];
854     }
855 }
856
857 /* Send ^C to target to halt it.  Target will respond, and send us a
858    packet.  */
859
860 static void
861 monitor_interrupt (signo)
862      int signo;
863 {
864   /* If this doesn't work, try more severe steps.  */
865   signal (signo, monitor_interrupt_twice);
866   
867   if (remote_debug)
868     printf_unfiltered ("monitor_interrupt called\n");
869
870   target_stop ();
871 }
872
873 /* The user typed ^C twice.  */
874
875 static void
876 monitor_interrupt_twice (signo)
877      int signo;
878 {
879   signal (signo, ofunc);
880   
881   monitor_interrupt_query ();
882
883   signal (signo, monitor_interrupt);
884 }
885
886 /* Ask the user what to do when an interrupt is received.  */
887
888 static void
889 monitor_interrupt_query ()
890 {
891   target_terminal_ours ();
892
893   if (query ("Interrupted while waiting for the program.\n\
894 Give up (and stop debugging it)? "))
895     {
896       target_mourn_inferior ();
897       return_to_top_level (RETURN_QUIT);
898     }
899
900   target_terminal_inferior ();
901 }
902
903 static void
904 monitor_wait_cleanup (old_timeout)
905      int old_timeout;
906 {
907   timeout = old_timeout;
908   signal (SIGINT, ofunc);
909   in_monitor_wait = 0;
910 }
911
912
913
914 void monitor_wait_filter(char * buf,
915                          int bufmax,
916                          int * ext_resp_len, 
917                          struct target_waitstatus * status
918                          )
919 {
920   int resp_len ;
921   do
922     {
923       resp_len = monitor_expect_prompt (buf, bufmax);
924       * ext_resp_len =resp_len ;
925
926       if (resp_len <= 0)
927         fprintf_unfiltered (gdb_stderr, "monitor_wait:  excessive response from monitor: %s.", buf);
928     }
929   while (resp_len < 0);
930
931   /* Print any output characters that were preceded by ^O.  */
932   /* FIXME - This would be great as a user settabgle flag */
933   if (remote_debug ||
934       current_monitor->flags & MO_PRINT_PROGRAM_OUTPUT)
935     {
936       int i;
937
938       for (i = 0; i < resp_len - 1; i++)
939         if (buf[i] == 0x0f)
940           putchar_unfiltered (buf[++i]);
941     }
942 }
943
944
945
946 /* Wait until the remote machine stops, then return, storing status in
947    status just as `wait' would.  */
948
949 static int
950 monitor_wait (pid, status)
951      int pid;
952      struct target_waitstatus *status;
953 {
954   int old_timeout = timeout;
955   char buf[1024];
956   int resp_len;
957   struct cleanup *old_chain;
958
959   status->kind = TARGET_WAITKIND_EXITED;
960   status->value.integer = 0;
961
962   old_chain = make_cleanup (monitor_wait_cleanup, old_timeout);
963   RDEBUG(("MON wait\n"))
964
965 #if 0 /* MAINTENANCE_CMDS */
966     /* This is somthing other than a maintenance command */
967   in_monitor_wait = 1;
968   timeout = watchdog > 0 ? watchdog : -1;
969 #else
970   timeout = -1;         /* Don't time out -- user program is running. */
971 #endif
972
973   ofunc = (void (*)()) signal (SIGINT, monitor_interrupt);
974
975   if (current_monitor->wait_filter)
976     (*current_monitor->wait_filter)(buf,sizeof (buf),&resp_len,status) ;
977   else          monitor_wait_filter(buf,sizeof (buf),&resp_len,status) ;
978       
979 #if 0 /* Transferred to monitor wait filter */
980   do
981     {
982       resp_len = monitor_expect_prompt (buf, sizeof (buf));
983
984       if (resp_len <= 0)
985         fprintf_unfiltered (gdb_stderr, "monitor_wait:  excessive response from monitor: %s.", buf);
986     }
987   while (resp_len < 0);
988
989   /* Print any output characters that were preceded by ^O.  */
990   /* FIXME - This would be great as a user settabgle flag */
991   if (remote_debug ||
992       current_monitor->flags & MO_PRINT_PROGRAM_OUTPUT)
993     {
994       int i;
995
996       for (i = 0; i < resp_len - 1; i++)
997         if (buf[i] == 0x0f)
998           putchar_unfiltered (buf[++i]);
999     }
1000 #endif  
1001
1002   signal (SIGINT, ofunc);
1003
1004   timeout = old_timeout;
1005 #if 0
1006   if (dump_reg_flag && current_monitor->dump_registers)
1007     {
1008       dump_reg_flag = 0;
1009       monitor_printf (current_monitor->dump_registers);
1010       resp_len = monitor_expect_prompt (buf, sizeof (buf));
1011     }
1012
1013   if (current_monitor->register_pattern)
1014     parse_register_dump (buf, resp_len);
1015 #else
1016   RDEBUG(("Wait fetching registers after stop\n")) ;
1017   monitor_dump_regs() ;
1018 #endif  
1019
1020   status->kind = TARGET_WAITKIND_STOPPED;
1021   status->value.sig = TARGET_SIGNAL_TRAP;
1022
1023   discard_cleanups (old_chain);
1024
1025   in_monitor_wait = 0;
1026
1027   return inferior_pid;
1028 }
1029
1030 /* Fetch register REGNO, or all registers if REGNO is -1. Returns
1031    errno value.  */
1032
1033 static void
1034 monitor_fetch_register (regno)
1035      int regno;
1036 {
1037   char *name;
1038   static char zerobuf[MAX_REGISTER_RAW_SIZE] = {0};
1039   char regbuf[MAX_REGISTER_RAW_SIZE * 2 + 1];
1040   int i;
1041
1042   name = current_monitor->regnames[regno];
1043   RDEBUG(("MON fetchreg %d '%s'\n",regno,name)) 
1044
1045   if (!name || (*name == '\0'))
1046     { RDEBUG(("No register known for %d\n",regno))
1047       supply_register (regno, zerobuf);
1048       return;
1049     }
1050
1051   /* send the register examine command */
1052
1053   monitor_printf (current_monitor->getreg.cmd, name);
1054
1055   /* If RESP_DELIM is specified, we search for that as a leading
1056      delimiter for the register value.  Otherwise, we just start
1057      searching from the start of the buf.  */
1058
1059   if (current_monitor->getreg.resp_delim)
1060     {
1061       RDEBUG(("EXP getreg.resp_delim\n")) 
1062       monitor_expect (current_monitor->getreg.resp_delim, NULL, 0);
1063       /* Handle case of first 32 registers listed in pairs.  */
1064       if (current_monitor->flags & MO_32_REGS_PAIRED
1065           && regno & 1 == 1 && regno < 32)
1066         { RDEBUG(("EXP getreg.resp_delim\n")) ;
1067           monitor_expect (current_monitor->getreg.resp_delim, NULL, 0);
1068         }
1069     }
1070
1071   /* Skip leading spaces and "0x" if MO_HEX_PREFIX flag is set */
1072   if (current_monitor->flags & MO_HEX_PREFIX) 
1073     {
1074       int c;
1075       c = readchar (timeout);
1076       while (c == ' ')
1077         c = readchar (timeout);
1078       if ((c == '0') && ((c = readchar (timeout)) == 'x'))
1079         ;
1080       else
1081           error ("Bad value returned from monitor while fetching register %x.",
1082                  regno);
1083     }
1084
1085   /* Read upto the maximum number of hex digits for this register, skipping
1086      spaces, but stop reading if something else is seen.  Some monitors
1087      like to drop leading zeros.  */
1088
1089   for (i = 0; i < REGISTER_RAW_SIZE (regno) * 2; i++)
1090     {
1091       int c;
1092       c = readchar (timeout);
1093       while (c == ' ')
1094         c = readchar (timeout);
1095
1096       if (!isxdigit (c))
1097         break;
1098
1099       regbuf[i] = c;
1100     }
1101
1102   regbuf[i] = '\000';           /* terminate the number */
1103   RDEBUG(("REGVAL '%s'\n",regbuf)) ;
1104
1105   /* If TERM is present, we wait for that to show up.  Also, (if TERM
1106      is present), we will send TERM_CMD if that is present.  In any
1107      case, we collect all of the output into buf, and then wait for
1108      the normal prompt.  */
1109
1110   if (current_monitor->getreg.term)
1111     {
1112       RDEBUG(("EXP getreg.term\n"))
1113       monitor_expect (current_monitor->getreg.term, NULL, 0); /* get response */
1114     }
1115
1116   if (current_monitor->getreg.term_cmd)
1117     { RDEBUG(("EMIT getreg.term.cmd\n"))
1118         monitor_printf (current_monitor->getreg.term_cmd);
1119     }
1120   if (! current_monitor->getreg.term ||    /* Already expected or */
1121       current_monitor->getreg.term_cmd)    /* ack expected */
1122     monitor_expect_prompt (NULL, 0); /* get response */
1123
1124   monitor_supply_register (regno, regbuf);
1125 }
1126
1127 /* Sometimes, it takes several commands to dump the registers */
1128 /* This is a primitive for use by variations of monitor interfaces in
1129    case they need to compose the operation.
1130    */
1131 int monitor_dump_reg_block(char * block_cmd)
1132 {
1133   char buf[1024];
1134   int resp_len;
1135   monitor_printf (block_cmd);
1136   resp_len = monitor_expect_prompt (buf, sizeof (buf));
1137   parse_register_dump (buf, resp_len);
1138   return 1 ;
1139 }
1140
1141
1142 /* Read the remote registers into the block regs.  */
1143 /* Call the specific function if it has been provided */
1144
1145 static void
1146 monitor_dump_regs ()
1147 {
1148   char buf[1024];
1149   int resp_len;
1150   if (current_monitor->dumpregs)
1151      (*(current_monitor->dumpregs))() ; /* call supplied function */
1152   else
1153     if (current_monitor->dump_registers) /* default version */
1154     { monitor_printf (current_monitor->dump_registers);
1155       resp_len = monitor_expect_prompt (buf, sizeof (buf));
1156       parse_register_dump (buf, resp_len);
1157     }
1158   else
1159     abort(); /* Need some way to read registers */
1160 }
1161
1162 static void
1163 monitor_fetch_registers (regno)
1164      int regno;
1165 {
1166   RDEBUG(("MON fetchregs\n")) ;
1167   if (current_monitor->getreg.cmd) 
1168     {
1169       if (regno >= 0)
1170         {
1171           monitor_fetch_register (regno);
1172           return;
1173         }
1174
1175       for (regno = 0; regno < NUM_REGS; regno++)
1176         monitor_fetch_register (regno);
1177     }
1178   else {
1179     monitor_dump_regs ();
1180   }
1181 }
1182
1183 /* Store register REGNO, or all if REGNO == 0.  Return errno value.  */
1184
1185 static void
1186 monitor_store_register (regno)
1187      int regno;
1188 {
1189   char *name;
1190   unsigned int val;
1191
1192   name = current_monitor->regnames[regno];
1193   if (!name || (*name == '\0'))
1194     { RDEBUG(("MON Cannot store unknown register\n"))
1195       return;
1196     }
1197
1198   val = read_register (regno);
1199   RDEBUG(("MON storeg %d %08x\n",regno,(unsigned int)val))
1200
1201   /* send the register deposit command */
1202
1203   if (current_monitor->flags & MO_REGISTER_VALUE_FIRST)
1204     monitor_printf (current_monitor->setreg.cmd, val, name);
1205   else if (current_monitor->flags & MO_SETREG_INTERACTIVE)
1206     monitor_printf (current_monitor->setreg.cmd, name);
1207   else
1208     monitor_printf (current_monitor->setreg.cmd, name, val);
1209
1210   if (current_monitor->setreg.term)
1211     { RDEBUG(("EXP setreg.term\n"))
1212       monitor_expect (current_monitor->setreg.term, NULL, 0);
1213       if (current_monitor->flags & MO_SETREG_INTERACTIVE)
1214         monitor_printf ("%x\r", val);
1215       monitor_expect_prompt (NULL, 0);
1216     }
1217   else
1218     monitor_expect_prompt (NULL, 0);
1219   if (current_monitor->setreg.term_cmd) /* Mode exit required */
1220     { RDEBUG(("EXP setreg_termcmd\n")) ;
1221       monitor_printf("%s",current_monitor->setreg.term_cmd) ;
1222       monitor_expect_prompt(NULL,0) ;
1223     }
1224 } /* monitor_store_register */
1225
1226 /* Store the remote registers.  */
1227
1228 static void
1229 monitor_store_registers (regno)
1230      int regno;
1231 {
1232   if (regno >= 0)
1233     {
1234       monitor_store_register (regno);
1235       return;
1236     }
1237
1238   for (regno = 0; regno < NUM_REGS; regno++)
1239     monitor_store_register (regno);
1240 }
1241
1242 /* Get ready to modify the registers array.  On machines which store
1243    individual registers, this doesn't need to do anything.  On machines
1244    which store all the registers in one fell swoop, this makes sure
1245    that registers contains all the registers from the program being
1246    debugged.  */
1247
1248 static void
1249 monitor_prepare_to_store ()
1250 {
1251   /* Do nothing, since we can store individual regs */
1252 }
1253
1254 static void
1255 monitor_files_info (ops)
1256      struct target_ops *ops;
1257 {
1258   printf_unfiltered ("\tAttached to %s at %d baud.\n", dev_name, baud_rate);
1259 }
1260
1261 static int
1262 monitor_write_memory (memaddr, myaddr, len)
1263      CORE_ADDR memaddr;
1264      char *myaddr;
1265      int len;
1266 {
1267   unsigned int val, hostval ;
1268   char *cmd;
1269   int i;
1270
1271   RDEBUG(("MON write %d %08x\n",len,(unsigned long)memaddr))
1272
1273   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
1274     memaddr = ADDR_BITS_REMOVE (memaddr);
1275
1276   /* Use memory fill command for leading 0 bytes.  */
1277
1278   if (current_monitor->fill)
1279     {
1280       for (i = 0; i < len; i++)
1281         if (myaddr[i] != 0)
1282           break;
1283
1284       if (i > 4)                /* More than 4 zeros is worth doing */
1285         {
1286           RDEBUG(("MON FILL %d\n",i))
1287             if (current_monitor->flags & MO_FILL_USES_ADDR)
1288               monitor_printf (current_monitor->fill, memaddr, (memaddr + i)-1, 0);
1289             else
1290               monitor_printf (current_monitor->fill, memaddr, i, 0);
1291
1292           monitor_expect_prompt (NULL, 0);
1293
1294           return i;
1295         }
1296     }
1297
1298 #if 0
1299   /* Can't actually use long longs if VAL is an int (nice idea, though).  */
1300   if ((memaddr & 0x7) == 0 && len >= 8 && current_monitor->setmem.cmdll)
1301     {
1302       len = 8;
1303       cmd = current_monitor->setmem.cmdll;
1304     }
1305   else
1306 #endif
1307   if ((memaddr & 0x3) == 0 && len >= 4 && current_monitor->setmem.cmdl)
1308     {
1309       len = 4;
1310       cmd = current_monitor->setmem.cmdl;
1311     }
1312   else if ((memaddr & 0x1) == 0 && len >= 2 && current_monitor->setmem.cmdw)
1313     {
1314       len = 2;
1315       cmd = current_monitor->setmem.cmdw;
1316     }
1317   else
1318     {
1319       len = 1;
1320       cmd = current_monitor->setmem.cmdb;
1321     }
1322
1323   val = extract_unsigned_integer (myaddr, len);
1324   
1325   if (len == 4)
1326     { hostval = * (unsigned int *) myaddr ;
1327       RDEBUG(("Hostval(%08x) val(%08x)\n",hostval,val)) ;
1328     }
1329
1330
1331   if (current_monitor->flags & MO_NO_ECHO_ON_SETMEM)
1332     monitor_printf_noecho (cmd, memaddr, val);
1333   else if (current_monitor->flags & MO_SETMEM_INTERACTIVE)
1334     {
1335
1336       monitor_printf_noecho (cmd, memaddr);
1337
1338       if (current_monitor->setmem.term)
1339         { RDEBUG(("EXP setmem.term")) ;
1340           monitor_expect (current_monitor->setmem.term, NULL, 0);
1341           monitor_printf ("%x\r", val);
1342         }
1343       if (current_monitor->setmem.term_cmd)
1344         { /* Emit this to get out of the memory editing state */
1345           monitor_printf("%s",current_monitor->setmem.term_cmd) ;
1346           /* Drop through to expecting a prompt */
1347         }
1348     }
1349   else
1350     monitor_printf (cmd, memaddr, val);
1351
1352   monitor_expect_prompt (NULL, 0);
1353
1354   return len;
1355 }
1356
1357
1358 static monitor_write_even_block(memaddr,myaddr,len)
1359      CORE_ADDR memaddr ;
1360      char * myaddr ;
1361      int len ;
1362 {
1363   unsigned int val ;
1364   int written = 0 ;;
1365   /* Enter the sub mode */
1366   monitor_printf(current_monitor->setmem.cmdl,memaddr) ;
1367   monitor_expect_prompt(NULL,0) ;
1368  
1369   while (len)
1370     {
1371       val = extract_unsigned_integer(myaddr,4) ; /* REALLY */
1372       monitor_printf("%x\r",val) ;
1373       myaddr += 4 ;
1374       memaddr += 4 ;
1375       written += 4 ;
1376       RDEBUG((" @ %08x\n",memaddr))
1377       /* If we wanted to, here we could validate the address */
1378       monitor_expect_prompt(NULL,0) ;
1379     }
1380   /* Now exit the sub mode */
1381   monitor_printf (current_monitor->getreg.term_cmd);
1382   monitor_expect_prompt(NULL,0) ;
1383   return written ;
1384 }
1385
1386
1387 static int monitor_write_memory_bytes(memaddr,myaddr,len)
1388      CORE_ADDR memaddr ;
1389      char * myaddr ;
1390      int len ;
1391 {
1392   unsigned char val ;
1393   int written = 0 ;
1394   if (len == 0) return 0 ;
1395   /* Enter the sub mode */
1396   monitor_printf(current_monitor->setmem.cmdb,memaddr) ;
1397   monitor_expect_prompt(NULL,0) ;
1398   while (len)
1399     {
1400       val = *myaddr ;
1401       monitor_printf("%x\r",val) ;
1402       myaddr++ ;
1403       memaddr++ ;
1404       written++ ;
1405       /* If we wanted to, here we could validate the address */
1406       monitor_expect_prompt(NULL,0) ;
1407       len-- ;
1408     }
1409   /* Now exit the sub mode */
1410   monitor_printf (current_monitor->getreg.term_cmd);
1411   monitor_expect_prompt(NULL,0) ;
1412   return written ;
1413 }
1414
1415
1416 static longlongendswap(unsigned char * a)
1417 {
1418   int i,j ;
1419   unsigned char x ;
1420   i = 0 ; j = 7 ;
1421   while (i < 4)
1422     { x = *(a+i) ;
1423       *(a+i) = *(a+j) ;
1424       *(a+j) = x ;
1425       i++ , j-- ;
1426     }
1427 }
1428 /* Format 32 chars of long long value, advance the pointer */
1429 static char * hexlate = "0123456789abcdef" ;
1430 static char * longlong_hexchars(unsigned long long value,
1431                                  char * outbuff )
1432 {
1433   if (value == 0) { *outbuff++ = '0' ; return outbuff ; }
1434   else
1435     { static unsigned char disbuf[8] ; /* disassembly buffer */
1436       unsigned char * scan , * limit ; /* loop controls */
1437       unsigned char c , nib ;
1438       int leadzero = 1 ;
1439       scan = disbuf ; limit = scan + 8 ;
1440       { unsigned long long * dp ;
1441         dp = (unsigned long long *) scan ;
1442         *dp = value ;
1443       }
1444       longlongendswap(disbuf) ; /* FIXME: ONly on big endian hosts */
1445       while (scan < limit)
1446         { c = *scan++ ; /* a byte of our long long value */
1447           if (leadzero)
1448             if (c == 0) continue ;
1449             else leadzero = 0 ; /* henceforth we print even zeroes */
1450           nib = c >> 4 ;        /* high nibble bits */
1451           *outbuff++ = hexlate[nib] ;
1452           nib = c & 0x0f ;      /* low nibble bits */
1453           *outbuff++ = hexlate[nib] ;
1454         }
1455       return outbuff ;
1456     }
1457 } /* longlong_hexchars */
1458
1459
1460
1461 /* I am only going to call this when writing virtual byte streams.
1462    Which possably entails endian conversions
1463    */
1464 static int monitor_write_memory_longlongs(memaddr,myaddr,len)
1465      CORE_ADDR memaddr ;
1466      char * myaddr ;
1467      int len ;
1468 {
1469   static char hexstage[20] ; /* At least 16 digits required, plus null */
1470   char * endstring ;
1471   long long * llptr ;
1472   long long value ;
1473   int written = 0 ;
1474   llptr = (unsigned long long *) myaddr ;
1475   if (len == 0 ) return 0 ;
1476   monitor_printf(current_monitor->setmem.cmdll,memaddr) ;
1477   monitor_expect_prompt(NULL,0) ;
1478   while (len >= 8 )
1479     {
1480       value = *llptr ;
1481       endstring = longlong_hexchars(*llptr,hexstage) ;
1482       *endstring = '\0' ; /* NUll terminate for printf */
1483       monitor_printf("%s\r",hexstage) ;
1484       llptr++ ;
1485       memaddr += 8 ;
1486       written += 8 ;
1487       /* If we wanted to, here we could validate the address */
1488       monitor_expect_prompt(NULL,0) ;
1489       len -= 8 ;
1490     }
1491   /* Now exit the sub mode */
1492   monitor_printf (current_monitor->getreg.term_cmd);
1493   monitor_expect_prompt(NULL,0) ;
1494   return written ;
1495 } /* */
1496
1497
1498
1499 /* ----- MONITOR_WRITE_MEMORY_BLOCK ---------------------------- */
1500 /* This is for the large blocks of memory which may occur in downloading.
1501    And for monitors which use interactive entry,
1502    And for monitors which do not have other downloading methods.
1503    Without this, we will end up calling monitor_write_memory many times
1504    and do the entry and exit of the sub mode many times
1505    This currently assumes...
1506      MO_SETMEM_INTERACTIVE
1507      ! MO_NO_ECHO_ON_SETMEM
1508      To use this, the you have to patch the monitor_cmds block with
1509      this function. Otherwise, its not tuned up for use by all
1510      monitor variations.
1511    */
1512
1513 static int monitor_write_memory_block(memaddr,myaddr,len)
1514      CORE_ADDR memaddr ;
1515      char * myaddr ;
1516      int len ;
1517 {
1518   int written ;
1519   written = 0 ;
1520   /* FIXME: This would be a good place to put the zero test */
1521 #if 1 
1522   if ((len > 8) && (((len & 0x07)) == 0) && current_monitor->setmem.cmdll)
1523        {
1524          return monitor_write_memory_longlongs(memaddr,myaddr,len) ;
1525        }
1526 #endif  
1527 #if 0 
1528   if (len > 4)
1529     {
1530       int sublen ;
1531       written = monitor_write_even_block(memaddr,myaddr,len) ;
1532       /* Adjust calling parameters by written amount */
1533       memaddr += written ;
1534       myaddr += written ;
1535       len -= written ;
1536     }
1537 #endif
1538   written = monitor_write_memory_bytes(memaddr,myaddr,len) ;
1539   return written ;
1540 }
1541
1542 /* This is an alternate form of monitor_read_memory which is used for monitors
1543    which can only read a single byte/word/etc. at a time.  */
1544
1545 static int
1546 monitor_read_memory_single (memaddr, myaddr, len)
1547      CORE_ADDR memaddr;
1548      char *myaddr;
1549      int len;
1550 {
1551   unsigned int val;
1552   char membuf[sizeof(int) * 2 + 1];
1553   char *p;
1554   char *cmd;
1555   int i;
1556
1557   RDEBUG(("MON read single\n")) ;
1558 #if 0
1559   /* Can't actually use long longs (nice idea, though).  In fact, the
1560      call to strtoul below will fail if it tries to convert a value
1561      that's too big to fit in a long.  */
1562   if ((memaddr & 0x7) == 0 && len >= 8 && current_monitor->getmem.cmdll)
1563     {
1564       len = 8;
1565       cmd = current_monitor->getmem.cmdll;
1566     }
1567   else
1568 #endif
1569   if ((memaddr & 0x3) == 0 && len >= 4 && current_monitor->getmem.cmdl)
1570     {
1571       len = 4;
1572       cmd = current_monitor->getmem.cmdl;
1573     }
1574   else if ((memaddr & 0x1) == 0 && len >= 2 && current_monitor->getmem.cmdw)
1575     {
1576       len = 2;
1577       cmd = current_monitor->getmem.cmdw;
1578     }
1579   else
1580     {
1581       len = 1;
1582       cmd = current_monitor->getmem.cmdb;
1583     }
1584
1585   /* Send the examine command.  */
1586
1587   monitor_printf (cmd, memaddr);
1588
1589   /* If RESP_DELIM is specified, we search for that as a leading
1590      delimiter for the memory value.  Otherwise, we just start
1591      searching from the start of the buf.  */
1592
1593   if (current_monitor->getmem.resp_delim)
1594     { RDEBUG(("EXP getmem.resp_delim\n")) ;
1595       monitor_expect_regexp (&getmem_resp_delim_pattern, NULL, 0);
1596     }
1597
1598   /* Now, read the appropriate number of hex digits for this loc,
1599      skipping spaces.  */
1600
1601   /* Skip leading spaces and "0x" if MO_HEX_PREFIX flag is set. */
1602   if (current_monitor->flags & MO_HEX_PREFIX) 
1603     {
1604       int c;
1605
1606       c = readchar (timeout);
1607       while (c == ' ')
1608         c = readchar (timeout);
1609       if ((c == '0') && ((c = readchar (timeout)) == 'x'))
1610         ;
1611       else
1612         error ("monitor_read_memory_single (0x%x):  bad response from monitor: %.*s%c.",
1613                memaddr, i, membuf, c);
1614     }
1615   for (i = 0; i < len * 2; i++)
1616     {
1617       int c;
1618
1619       while (1)
1620         {
1621           c = readchar (timeout);
1622           if (isxdigit (c))
1623             break;
1624           if (c == ' ')
1625             continue;
1626
1627           error ("monitor_read_memory_single (0x%x):  bad response from monitor: %.*s%c.",
1628                  memaddr, i, membuf, c);
1629         }
1630
1631       membuf[i] = c;
1632     }
1633
1634   membuf[i] = '\000';           /* terminate the number */
1635
1636 /* If TERM is present, we wait for that to show up.  Also, (if TERM is
1637    present), we will send TERM_CMD if that is present.  In any case, we collect
1638    all of the output into buf, and then wait for the normal prompt.  */
1639
1640   if (current_monitor->getmem.term)
1641     {
1642       monitor_expect (current_monitor->getmem.term, NULL, 0); /* get response */
1643
1644       if (current_monitor->getmem.term_cmd)
1645         {
1646           monitor_printf (current_monitor->getmem.term_cmd);
1647           monitor_expect_prompt (NULL, 0);
1648         }
1649     }
1650   else
1651     monitor_expect_prompt (NULL, 0); /* get response */
1652
1653   p = membuf;
1654   val = strtoul (membuf, &p, 16);
1655
1656   if (val == 0 && membuf == p)
1657     error ("monitor_read_memory_single (0x%x):  bad value from monitor: %s.",
1658            memaddr, membuf);
1659
1660   /* supply register stores in target byte order, so swap here */
1661
1662   store_unsigned_integer (myaddr, len, val);
1663
1664   return len;
1665 }
1666
1667 /* Copy LEN bytes of data from debugger memory at MYADDR to inferior's
1668    memory at MEMADDR.  Returns length moved.  Currently, we do no more
1669    than 16 bytes at a time.  */
1670
1671 static int
1672 monitor_read_memory (memaddr, myaddr, len)
1673      CORE_ADDR memaddr;
1674      char *myaddr;
1675      int len;
1676 {
1677   unsigned int val;
1678   char buf[512];
1679   char *p, *p1;
1680   int resp_len;
1681   int i;
1682   CORE_ADDR dumpaddr;
1683
1684   if (remote_debug) printf("MON read block ta(%08x) ha(%08x) %d\n",
1685           (unsigned long) memaddr , (unsigned long)myaddr, len);
1686
1687   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
1688     memaddr = ADDR_BITS_REMOVE (memaddr);
1689
1690   if (current_monitor->flags & MO_GETMEM_READ_SINGLE)
1691     return monitor_read_memory_single (memaddr, myaddr, len);
1692
1693   len = min (len, 16);
1694
1695   /* Some dumpers align the first data with the preceeding 16
1696      byte boundary. Some print blanks and start at the
1697      requested boundary. EXACT_DUMPADDR
1698      */
1699
1700   dumpaddr = (current_monitor->flags & MO_EXACT_DUMPADDR)
1701     ? memaddr : memaddr & ~ 0x0f ;
1702
1703   /* See if xfer would cross a 16 byte boundary.  If so, clip it.  */
1704   if (((memaddr ^ (memaddr + len - 1)) & ~0xf) != 0)
1705     len = ((memaddr + len) & ~0xf) - memaddr;
1706
1707   /* send the memory examine command */
1708
1709   if (current_monitor->flags & MO_GETMEM_NEEDS_RANGE)
1710     monitor_printf (current_monitor->getmem.cmdb, memaddr, memaddr + len - 1);
1711   else if (current_monitor->flags & MO_GETMEM_16_BOUNDARY)
1712     monitor_printf (current_monitor->getmem.cmdb, dumpaddr);
1713   else
1714     monitor_printf (current_monitor->getmem.cmdb, memaddr, len);
1715
1716   /* If TERM is present, we wait for that to show up.  Also, (if TERM
1717      is present), we will send TERM_CMD if that is present.  In any
1718      case, we collect all of the output into buf, and then wait for
1719      the normal prompt.  */
1720
1721   if (current_monitor->getmem.term)
1722     {
1723       resp_len = monitor_expect (current_monitor->getmem.term, buf, sizeof buf); /* get response */
1724
1725       if (resp_len <= 0)
1726         error ("monitor_read_memory (0x%x):  excessive response from monitor: %.*s.",
1727                memaddr, resp_len, buf);
1728
1729       if (current_monitor->getmem.term_cmd)
1730         {
1731           SERIAL_WRITE (monitor_desc, current_monitor->getmem.term_cmd,
1732                         strlen (current_monitor->getmem.term_cmd));
1733           monitor_expect_prompt (NULL, 0);
1734         }
1735     }
1736   else
1737     resp_len = monitor_expect_prompt (buf, sizeof buf); /* get response */
1738
1739   p = buf;
1740
1741   /* If RESP_DELIM is specified, we search for that as a leading
1742      delimiter for the values.  Otherwise, we just start searching
1743      from the start of the buf.  */
1744
1745   if (current_monitor->getmem.resp_delim)
1746     {
1747       int retval, tmp;
1748       struct re_registers resp_strings;
1749       RDEBUG(("MON getmem.resp_delim %s\n",current_monitor->getmem.resp_delim)) ;
1750
1751       tmp = strlen (p);
1752       retval = re_search (&getmem_resp_delim_pattern, p, tmp, 0, tmp,
1753                           &resp_strings);
1754
1755       if (retval < 0)
1756         error ("monitor_read_memory (0x%x):  bad response from monitor: %.*s.",
1757                memaddr, resp_len, buf);
1758
1759       p += resp_strings.end[0];
1760 #if 0
1761       p = strstr (p, current_monitor->getmem.resp_delim);
1762       if (!p)
1763         error ("monitor_read_memory (0x%x):  bad response from monitor: %.*s.",
1764                memaddr, resp_len, buf);
1765       p += strlen (current_monitor->getmem.resp_delim);
1766 #endif
1767     }
1768   if (remote_debug) printf("MON scanning  %d ,%08x '%s'\n",len,p,p) ;
1769   if (current_monitor->flags & MO_GETMEM_16_BOUNDARY)
1770     {
1771       char c ;
1772       int fetched = 0 ;
1773       i = len;
1774       c = *p ;
1775
1776                             
1777       while (!(c  == '\000' || c == '\n' || c == '\r') && i > 0)
1778         { if (isxdigit (c))
1779             { if ((dumpaddr >= memaddr) && (i > 0))
1780                 { val = fromhex (c) * 16 + fromhex (*(p+1));
1781                   *myaddr++ = val;
1782                   if (remote_debug) printf("[%02x]",val) ;
1783                   --i;
1784                   fetched++ ;
1785                 }
1786               ++dumpaddr;
1787               ++p;
1788             }
1789           ++p; /* skip a blank or other non hex char */
1790           c = *p ;
1791         }
1792       if (fetched == 0) error("Failed to read via monitor") ;
1793       if (remote_debug) printf("\n") ;
1794       return fetched ; /* Return the number of bytes actually read */
1795     }
1796   RDEBUG(("MON scanning bytes\n")) ;
1797
1798   for (i = len; i > 0; i--)
1799     {
1800       /* Skip non-hex chars, but bomb on end of string and newlines */
1801
1802       while (1)
1803         {
1804           if (isxdigit (*p))
1805             break;
1806
1807           if (*p == '\000' || *p == '\n' || *p == '\r')
1808             error ("monitor_read_memory (0x%x):  badly terminated response from monitor: %.*s", memaddr, resp_len, buf);
1809           p++;
1810         }
1811
1812       val = strtoul (p, &p1, 16);
1813
1814       if (val == 0 && p == p1)
1815         error ("monitor_read_memory (0x%x):  bad value from monitor: %.*s.", memaddr,
1816                resp_len, buf);
1817
1818       *myaddr++ = val;
1819
1820       if (i == 1)
1821         break;
1822
1823       p = p1;
1824     }
1825
1826   return len;
1827 }
1828
1829 /* This version supports very large reads by looping on multiline
1830    dump bytes outputs. Beware of buffering limits.
1831    */
1832 static int monotor_read_memory_block(memaddr,myaddr,len)
1833      CORE_ADDR memaddr ;
1834      char * myaddr ;
1835      int len ;
1836 {
1837 }
1838
1839 static int
1840 monitor_xfer_memory (memaddr, myaddr, len, write, target)
1841      CORE_ADDR memaddr;
1842      char *myaddr;
1843      int len;
1844      int write;
1845      struct target_ops *target;         /* ignored */
1846 {
1847   return dcache_xfer_memory (remote_dcache, memaddr, myaddr, len, write);
1848 }
1849
1850 static void
1851 monitor_kill ()
1852 {
1853   return;               /* ignore attempts to kill target system */
1854 }
1855
1856 /* All we actually do is set the PC to the start address of exec_bfd, and start
1857    the program at that point.  */
1858
1859 static void
1860 monitor_create_inferior (exec_file, args, env)
1861      char *exec_file;
1862      char *args;
1863      char **env;
1864 {
1865   if (args && (*args != '\000'))
1866     error ("Args are not supported by the monitor.");
1867
1868   first_time = 1;
1869   clear_proceed_status ();
1870   proceed (bfd_get_start_address (exec_bfd), TARGET_SIGNAL_0, 0);
1871 }
1872
1873 /* Clean up when a program exits.
1874    The program actually lives on in the remote processor's RAM, and may be
1875    run again without a download.  Don't leave it full of breakpoint
1876    instructions.  */
1877
1878 static void
1879 monitor_mourn_inferior ()
1880 {
1881   unpush_target (targ_ops);
1882   generic_mourn_inferior ();    /* Do all the proper things now */
1883 }
1884
1885 #define NUM_MONITOR_BREAKPOINTS 8
1886
1887 static CORE_ADDR breakaddr[NUM_MONITOR_BREAKPOINTS] = {0};
1888
1889 /* Tell the monitor to add a breakpoint.  */
1890
1891 static int
1892 monitor_insert_breakpoint (addr, shadow)
1893      CORE_ADDR addr;
1894      char *shadow;
1895 {
1896   int i;
1897   unsigned char *bp;
1898   int bplen;
1899
1900   RDEBUG(("MON inst bkpt %08x\n",addr)) 
1901   if (current_monitor->set_break == NULL)
1902     error ("No set_break defined for this monitor");
1903
1904   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
1905     addr = ADDR_BITS_REMOVE (addr);
1906
1907   /* Determine appropriate breakpoint size for this address.  */
1908   bp = memory_breakpoint_from_pc (&addr, &bplen);
1909
1910   for (i = 0; i < NUM_MONITOR_BREAKPOINTS; i++)
1911     {
1912       if (breakaddr[i] == 0)
1913         {
1914           breakaddr[i] = addr;
1915           monitor_read_memory (addr, shadow, bplen);
1916           monitor_printf (current_monitor->set_break, addr);
1917           monitor_expect_prompt (NULL, 0);
1918           return 0;
1919         }
1920     }
1921
1922   error ("Too many breakpoints (> %d) for monitor.", NUM_MONITOR_BREAKPOINTS);
1923 }
1924
1925 /* Tell the monitor to remove a breakpoint.  */
1926
1927 static int
1928 monitor_remove_breakpoint (addr, shadow)
1929      CORE_ADDR addr;
1930      char *shadow;
1931 {
1932   int i;
1933
1934   RDEBUG(("MON rmbkpt %08x\n",addr))
1935   if (current_monitor->clr_break == NULL)
1936     error ("No clr_break defined for this monitor");
1937
1938   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
1939     addr = ADDR_BITS_REMOVE (addr);
1940
1941   for (i = 0; i < NUM_MONITOR_BREAKPOINTS; i++)
1942     {
1943       if (breakaddr[i] == addr)
1944         {
1945           breakaddr[i] = 0;
1946           /* some monitors remove breakpoints based on the address */
1947           if (current_monitor->flags & MO_CLR_BREAK_USES_ADDR)
1948             monitor_printf (current_monitor->clr_break, addr);
1949           else if (current_monitor->flags & MO_CLR_BREAK_1_BASED)
1950             monitor_printf (current_monitor->clr_break, i + 1);
1951           else
1952             monitor_printf (current_monitor->clr_break, i);
1953           monitor_expect_prompt (NULL, 0);
1954           return 0;
1955         }
1956     }
1957   fprintf_unfiltered (stderr, "Can't find breakpoint associated with 0x%x\n", addr);
1958   return 1;
1959 }
1960
1961 /* monitor_wait_srec_ack -- wait for the target to send an acknowledgement for
1962    an S-record.  Return non-zero if the ACK is received properly.  */
1963
1964 static int
1965 monitor_wait_srec_ack ()
1966 {
1967   int i, ch;
1968
1969   if (current_monitor->flags & MO_SREC_ACK_PLUS)
1970     {
1971       return (readchar (timeout) == '+');
1972     }
1973   else if (current_monitor->flags & MO_SREC_ACK_ROTATE)
1974     {
1975       /* Eat two backspaces, a "rotating" char (|/-\), and a space.  */
1976       if ((ch = readchar (1)) < 0)
1977         return 0;
1978       if ((ch = readchar (1)) < 0)
1979         return 0;
1980       if ((ch = readchar (1)) < 0)
1981         return 0;
1982       if ((ch = readchar (1)) < 0)
1983         return 0;
1984     }
1985   return 1;
1986 }
1987
1988 /* monitor_load -- download a file. */
1989
1990 static void
1991 monitor_load (file, from_tty)
1992     char *file;
1993     int  from_tty;
1994 {
1995   dcache_flush (remote_dcache);
1996   RDEBUG(("MON load\n"))
1997
1998   if (current_monitor->load_routine)
1999     current_monitor->load_routine (monitor_desc, file, hashmark);
2000   else
2001     {                           /* The default is ascii S-records */
2002       int n;
2003       unsigned long load_offset;
2004       char buf[128];
2005
2006       /* enable user to specify address for downloading as 2nd arg to load */
2007       n = sscanf (file, "%s 0x%lx", buf, &load_offset);
2008       if (n > 1)
2009         file = buf;
2010       else
2011         load_offset = 0;
2012
2013       monitor_printf (current_monitor->load);
2014       if (current_monitor->loadresp)
2015         monitor_expect (current_monitor->loadresp, NULL, 0);
2016
2017       load_srec (monitor_desc, file, (bfd_vma) load_offset,
2018                  32, SREC_ALL, hashmark,
2019                  current_monitor->flags & MO_SREC_ACK ?
2020                    monitor_wait_srec_ack : NULL);
2021
2022       monitor_expect_prompt (NULL, 0);
2023     }
2024
2025 /* Finally, make the PC point at the start address */
2026
2027   if (exec_bfd)
2028     write_pc (bfd_get_start_address (exec_bfd));
2029
2030   inferior_pid = 0;             /* No process now */
2031
2032 /* This is necessary because many things were based on the PC at the time that
2033    we attached to the monitor, which is no longer valid now that we have loaded
2034    new code (and just changed the PC).  Another way to do this might be to call
2035    normal_stop, except that the stack may not be valid, and things would get
2036    horribly confused... */
2037
2038   clear_symtab_users ();
2039 }
2040
2041 static void
2042 monitor_stop ()
2043 {
2044   RDEBUG(("MON stop\n")) ;
2045   if ((current_monitor->flags & MO_SEND_BREAK_ON_STOP) != 0)
2046     SERIAL_SEND_BREAK (monitor_desc);
2047   if (current_monitor->stop)
2048     monitor_printf_noecho (current_monitor->stop);
2049 }
2050
2051 /* Put a command string, in args, out to MONITOR.  Output from MONITOR
2052    is placed on the users terminal until the prompt is seen. FIXME: We
2053    read the characters ourseleves here cause of a nasty echo.  */
2054
2055 static void
2056 monitor_command (args, from_tty)
2057      char *args;
2058      int from_tty;
2059 {
2060   char *p;
2061   int resp_len;
2062   char buf[1000];
2063
2064   if (monitor_desc == NULL)
2065     error ("monitor target not open.");
2066
2067   p = current_monitor->prompt;
2068
2069   /* Send the command.  Note that if no args were supplied, then we're
2070      just sending the monitor a newline, which is sometimes useful.  */
2071
2072   monitor_printf ("%s\r", (args ? args : ""));
2073
2074   resp_len = monitor_expect_prompt (buf, sizeof buf);
2075
2076   fputs_unfiltered (buf, gdb_stdout); /* Output the response */
2077 }
2078
2079 /* Convert hex digit A to a number.  */
2080
2081 #if 0
2082 static int
2083 from_hex (a)
2084      int a;
2085 {  
2086   if (a >= '0' && a <= '9')
2087     return a - '0';
2088   if (a >= 'a' && a <= 'f')
2089     return a - 'a' + 10;
2090   if (a >= 'A' && a <= 'F')
2091     return a - 'A' + 10;
2092
2093   error ("Reply contains invalid hex digit 0x%x", a);
2094 }
2095 #endif
2096
2097 char *
2098 monitor_get_dev_name ()
2099 {
2100   return dev_name;
2101 }
2102
2103 static struct target_ops monitor_ops =
2104 {
2105   NULL,                         /* to_shortname */
2106   NULL,                         /* to_longname */
2107   NULL,                         /* to_doc */
2108   NULL,                         /* to_open */
2109   monitor_close,                /* to_close */
2110   NULL,                         /* to_attach */
2111   monitor_detach,               /* to_detach */
2112   monitor_resume,               /* to_resume */
2113   monitor_wait,                 /* to_wait */
2114   monitor_fetch_registers,      /* to_fetch_registers */
2115   monitor_store_registers,      /* to_store_registers */
2116   monitor_prepare_to_store,     /* to_prepare_to_store */
2117   monitor_xfer_memory,          /* to_xfer_memory */
2118   monitor_files_info,           /* to_files_info */
2119   monitor_insert_breakpoint,    /* to_insert_breakpoint */
2120   monitor_remove_breakpoint,    /* to_remove_breakpoint */
2121   0,                            /* to_terminal_init */
2122   0,                            /* to_terminal_inferior */
2123   0,                            /* to_terminal_ours_for_output */
2124   0,                            /* to_terminal_ours */
2125   0,                            /* to_terminal_info */
2126   monitor_kill,                 /* to_kill */
2127   monitor_load,                 /* to_load */
2128   0,                            /* to_lookup_symbol */
2129   monitor_create_inferior,      /* to_create_inferior */
2130   monitor_mourn_inferior,       /* to_mourn_inferior */
2131   0,                            /* to_can_run */
2132   0,                            /* to_notice_signals */
2133   0,                            /* to_thread_alive */
2134   monitor_stop,                 /* to_stop */
2135   process_stratum,              /* to_stratum */
2136   0,                            /* to_next */
2137   1,                            /* to_has_all_memory */
2138   1,                            /* to_has_memory */
2139   1,                            /* to_has_stack */
2140   1,                            /* to_has_registers */
2141   1,                            /* to_has_execution */
2142   0,                            /* sections */
2143   0,                            /* sections_end */
2144   OPS_MAGIC                     /* to_magic */
2145 };
2146
2147 /* Init the target_ops structure pointed at by OPS */
2148
2149 void
2150 init_monitor_ops (ops)
2151      struct target_ops *ops;
2152 {
2153   memcpy (ops, &monitor_ops, sizeof monitor_ops);
2154 }
2155
2156 /* Define additional commands that are usually only used by monitors.  */
2157
2158 void
2159 _initialize_remote_monitors ()
2160 {
2161   add_show_from_set (add_set_cmd ("hash", no_class, var_boolean,
2162                                   (char *)&hashmark,
2163                                   "Set display of activity while downloading a file.\n\
2164 When enabled, a hashmark \'#\' is displayed.",
2165                                   &setlist),
2166                      &showlist);
2167
2168   add_com ("monitor", class_obscure, monitor_command,
2169            "Send a command to the debug monitor."); 
2170 }