GDB (API)
/home/stan/gdb/src/gdb/monitor.c
Go to the documentation of this file.
00001 /* Remote debugging interface for boot monitors, for GDB.
00002 
00003    Copyright (C) 1990-2013 Free Software Foundation, Inc.
00004 
00005    Contributed by Cygnus Support.  Written by Rob Savoye for Cygnus.
00006    Resurrected from the ashes by Stu Grossman.
00007 
00008    This file is part of GDB.
00009 
00010    This program is free software; you can redistribute it and/or modify
00011    it under the terms of the GNU General Public License as published by
00012    the Free Software Foundation; either version 3 of the License, or
00013    (at your option) any later version.
00014 
00015    This program is distributed in the hope that it will be useful,
00016    but WITHOUT ANY WARRANTY; without even the implied warranty of
00017    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00018    GNU General Public License for more details.
00019 
00020    You should have received a copy of the GNU General Public License
00021    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00022 
00023 /* This file was derived from various remote-* modules.  It is a collection
00024    of generic support functions so GDB can talk directly to a ROM based
00025    monitor.  This saves use from having to hack an exception based handler
00026    into existence, and makes for quick porting.
00027 
00028    This module talks to a debug monitor called 'MONITOR', which
00029    We communicate with MONITOR via either a direct serial line, or a TCP
00030    (or possibly TELNET) stream to a terminal multiplexor,
00031    which in turn talks to the target board.  */
00032 
00033 /* FIXME 32x64: This code assumes that registers and addresses are at
00034    most 32 bits long.  If they can be larger, you will need to declare
00035    values as LONGEST and use %llx or some such to print values when
00036    building commands to send to the monitor.  Since we don't know of
00037    any actual 64-bit targets with ROM monitors that use this code,
00038    it's not an issue right now.  -sts 4/18/96  */
00039 
00040 #include "defs.h"
00041 #include "gdbcore.h"
00042 #include "target.h"
00043 #include "exceptions.h"
00044 #include <signal.h>
00045 #include <ctype.h>
00046 #include "gdb_string.h"
00047 #include <sys/types.h>
00048 #include "command.h"
00049 #include "serial.h"
00050 #include "monitor.h"
00051 #include "gdbcmd.h"
00052 #include "inferior.h"
00053 #include "gdb_regex.h"
00054 #include "srec.h"
00055 #include "regcache.h"
00056 #include "gdbthread.h"
00057 #include "readline/readline.h"
00058 
00059 static char *dev_name;
00060 static struct target_ops *targ_ops;
00061 
00062 static void monitor_interrupt_query (void);
00063 static void monitor_interrupt_twice (int);
00064 static void monitor_stop (ptid_t);
00065 static void monitor_dump_regs (struct regcache *regcache);
00066 
00067 #if 0
00068 static int from_hex (int a);
00069 #endif
00070 
00071 static struct monitor_ops *current_monitor;
00072 
00073 static int hashmark;            /* flag set by "set hash".  */
00074 
00075 static int timeout = 30;
00076 
00077 static int in_monitor_wait = 0; /* Non-zero means we are in monitor_wait().  */
00078 
00079 static void (*ofunc) ();        /* Old SIGINT signal handler.  */
00080 
00081 static CORE_ADDR *breakaddr;
00082 
00083 /* Descriptor for I/O to remote machine.  Initialize it to NULL so
00084    that monitor_open knows that we don't have a file open when the
00085    program starts.  */
00086 
00087 static struct serial *monitor_desc = NULL;
00088 
00089 /* Pointer to regexp pattern matching data.  */
00090 
00091 static struct re_pattern_buffer register_pattern;
00092 static char register_fastmap[256];
00093 
00094 static struct re_pattern_buffer getmem_resp_delim_pattern;
00095 static char getmem_resp_delim_fastmap[256];
00096 
00097 static struct re_pattern_buffer setmem_resp_delim_pattern;
00098 static char setmem_resp_delim_fastmap[256];
00099 
00100 static struct re_pattern_buffer setreg_resp_delim_pattern;
00101 static char setreg_resp_delim_fastmap[256];
00102 
00103 static int dump_reg_flag;       /* Non-zero means do a dump_registers cmd when
00104                                    monitor_wait wakes up.  */
00105 
00106 static int first_time = 0;      /* Is this the first time we're
00107                                    executing after gaving created the
00108                                    child proccess?  */
00109 
00110 
00111 /* This is the ptid we use while we're connected to a monitor.  Its
00112    value is arbitrary, as monitor targets don't have a notion of
00113    processes or threads, but we need something non-null to place in
00114    inferior_ptid.  */
00115 static ptid_t monitor_ptid;
00116 
00117 #define TARGET_BUF_SIZE 2048
00118 
00119 /* Monitor specific debugging information.  Typically only useful to
00120    the developer of a new monitor interface.  */
00121 
00122 static void monitor_debug (const char *fmt, ...) ATTRIBUTE_PRINTF (1, 2);
00123 
00124 static unsigned int monitor_debug_p = 0;
00125 
00126 /* NOTE: This file alternates between monitor_debug_p and remote_debug
00127    when determining if debug information is printed.  Perhaps this
00128    could be simplified.  */
00129 
00130 static void
00131 monitor_debug (const char *fmt, ...)
00132 {
00133   if (monitor_debug_p)
00134     {
00135       va_list args;
00136 
00137       va_start (args, fmt);
00138       vfprintf_filtered (gdb_stdlog, fmt, args);
00139       va_end (args);
00140     }
00141 }
00142 
00143 
00144 /* Convert a string into a printable representation, Return # byte in
00145    the new string.  When LEN is >0 it specifies the size of the
00146    string.  Otherwize strlen(oldstr) is used.  */
00147 
00148 static void
00149 monitor_printable_string (char *newstr, char *oldstr, int len)
00150 {
00151   int ch;
00152   int i;
00153 
00154   if (len <= 0)
00155     len = strlen (oldstr);
00156 
00157   for (i = 0; i < len; i++)
00158     {
00159       ch = oldstr[i];
00160       switch (ch)
00161         {
00162         default:
00163           if (isprint (ch))
00164             *newstr++ = ch;
00165 
00166           else
00167             {
00168               sprintf (newstr, "\\x%02x", ch & 0xff);
00169               newstr += 4;
00170             }
00171           break;
00172 
00173         case '\\':
00174           *newstr++ = '\\';
00175           *newstr++ = '\\';
00176           break;
00177         case '\b':
00178           *newstr++ = '\\';
00179           *newstr++ = 'b';
00180           break;
00181         case '\f':
00182           *newstr++ = '\\';
00183           *newstr++ = 't';
00184           break;
00185         case '\n':
00186           *newstr++ = '\\';
00187           *newstr++ = 'n';
00188           break;
00189         case '\r':
00190           *newstr++ = '\\';
00191           *newstr++ = 'r';
00192           break;
00193         case '\t':
00194           *newstr++ = '\\';
00195           *newstr++ = 't';
00196           break;
00197         case '\v':
00198           *newstr++ = '\\';
00199           *newstr++ = 'v';
00200           break;
00201         }
00202     }
00203 
00204   *newstr++ = '\0';
00205 }
00206 
00207 /* Print monitor errors with a string, converting the string to printable
00208    representation.  */
00209 
00210 static void
00211 monitor_error (char *function, char *message,
00212                CORE_ADDR memaddr, int len, char *string, int final_char)
00213 {
00214   int real_len = (len == 0 && string != (char *) 0) ? strlen (string) : len;
00215   char *safe_string = alloca ((real_len * 4) + 1);
00216 
00217   monitor_printable_string (safe_string, string, real_len);
00218 
00219   if (final_char)
00220     error (_("%s (%s): %s: %s%c"),
00221            function, paddress (target_gdbarch (), memaddr),
00222            message, safe_string, final_char);
00223   else
00224     error (_("%s (%s): %s: %s"),
00225            function, paddress (target_gdbarch (), memaddr),
00226            message, safe_string);
00227 }
00228 
00229 /* Convert hex digit A to a number.  */
00230 
00231 static int
00232 fromhex (int a)
00233 {
00234   if (a >= '0' && a <= '9')
00235     return a - '0';
00236   else if (a >= 'a' && a <= 'f')
00237     return a - 'a' + 10;
00238   else if (a >= 'A' && a <= 'F')
00239     return a - 'A' + 10;
00240   else
00241     error (_("Invalid hex digit %d"), a);
00242 }
00243 
00244 /* monitor_vsprintf - similar to vsprintf but handles 64-bit addresses
00245 
00246    This function exists to get around the problem that many host platforms
00247    don't have a printf that can print 64-bit addresses.  The %A format
00248    specification is recognized as a special case, and causes the argument
00249    to be printed as a 64-bit hexadecimal address.
00250 
00251    Only format specifiers of the form "[0-9]*[a-z]" are recognized.
00252    If it is a '%s' format, the argument is a string; otherwise the
00253    argument is assumed to be a long integer.
00254 
00255    %% is also turned into a single %.  */
00256 
00257 static void
00258 monitor_vsprintf (char *sndbuf, char *pattern, va_list args)
00259 {
00260   int addr_bit = gdbarch_addr_bit (target_gdbarch ());
00261   char format[10];
00262   char fmt;
00263   char *p;
00264   int i;
00265   long arg_int;
00266   CORE_ADDR arg_addr;
00267   char *arg_string;
00268 
00269   for (p = pattern; *p; p++)
00270     {
00271       if (*p == '%')
00272         {
00273           /* Copy the format specifier to a separate buffer.  */
00274           format[0] = *p++;
00275           for (i = 1; *p >= '0' && *p <= '9' && i < (int) sizeof (format) - 2;
00276                i++, p++)
00277             format[i] = *p;
00278           format[i] = fmt = *p;
00279           format[i + 1] = '\0';
00280 
00281           /* Fetch the next argument and print it.  */
00282           switch (fmt)
00283             {
00284             case '%':
00285               strcpy (sndbuf, "%");
00286               break;
00287             case 'A':
00288               arg_addr = va_arg (args, CORE_ADDR);
00289               strcpy (sndbuf, phex_nz (arg_addr, addr_bit / 8));
00290               break;
00291             case 's':
00292               arg_string = va_arg (args, char *);
00293               sprintf (sndbuf, format, arg_string);
00294               break;
00295             default:
00296               arg_int = va_arg (args, long);
00297               sprintf (sndbuf, format, arg_int);
00298               break;
00299             }
00300           sndbuf += strlen (sndbuf);
00301         }
00302       else
00303         *sndbuf++ = *p;
00304     }
00305   *sndbuf = '\0';
00306 }
00307 
00308 
00309 /* monitor_printf_noecho -- Send data to monitor, but don't expect an echo.
00310    Works just like printf.  */
00311 
00312 void
00313 monitor_printf_noecho (char *pattern,...)
00314 {
00315   va_list args;
00316   char sndbuf[2000];
00317   int len;
00318 
00319   va_start (args, pattern);
00320 
00321   monitor_vsprintf (sndbuf, pattern, args);
00322 
00323   len = strlen (sndbuf);
00324   if (len + 1 > sizeof sndbuf)
00325     internal_error (__FILE__, __LINE__,
00326                     _("failed internal consistency check"));
00327 
00328   if (monitor_debug_p)
00329     {
00330       char *safe_string = (char *) alloca ((strlen (sndbuf) * 4) + 1);
00331 
00332       monitor_printable_string (safe_string, sndbuf, 0);
00333       fprintf_unfiltered (gdb_stdlog, "sent[%s]\n", safe_string);
00334     }
00335 
00336   monitor_write (sndbuf, len);
00337 }
00338 
00339 /* monitor_printf -- Send data to monitor and check the echo.  Works just like
00340    printf.  */
00341 
00342 void
00343 monitor_printf (char *pattern,...)
00344 {
00345   va_list args;
00346   char sndbuf[2000];
00347   int len;
00348 
00349   va_start (args, pattern);
00350 
00351   monitor_vsprintf (sndbuf, pattern, args);
00352 
00353   len = strlen (sndbuf);
00354   if (len + 1 > sizeof sndbuf)
00355     internal_error (__FILE__, __LINE__,
00356                     _("failed internal consistency check"));
00357 
00358   if (monitor_debug_p)
00359     {
00360       char *safe_string = (char *) alloca ((len * 4) + 1);
00361 
00362       monitor_printable_string (safe_string, sndbuf, 0);
00363       fprintf_unfiltered (gdb_stdlog, "sent[%s]\n", safe_string);
00364     }
00365 
00366   monitor_write (sndbuf, len);
00367 
00368   /* We used to expect that the next immediate output was the
00369      characters we just output, but sometimes some extra junk appeared
00370      before the characters we expected, like an extra prompt, or a
00371      portmaster sending telnet negotiations.  So, just start searching
00372      for what we sent, and skip anything unknown.  */
00373   monitor_debug ("ExpectEcho\n");
00374   monitor_expect (sndbuf, (char *) 0, 0);
00375 }
00376 
00377 
00378 /* Write characters to the remote system.  */
00379 
00380 void
00381 monitor_write (char *buf, int buflen)
00382 {
00383   if (serial_write (monitor_desc, buf, buflen))
00384     fprintf_unfiltered (gdb_stderr, "serial_write failed: %s\n",
00385                         safe_strerror (errno));
00386 }
00387 
00388 
00389 /* Read a binary character from the remote system, doing all the fancy
00390    timeout stuff, but without interpreting the character in any way,
00391    and without printing remote debug information.  */
00392 
00393 int
00394 monitor_readchar (void)
00395 {
00396   int c;
00397   int looping;
00398 
00399   do
00400     {
00401       looping = 0;
00402       c = serial_readchar (monitor_desc, timeout);
00403 
00404       if (c >= 0)
00405         c &= 0xff;              /* don't lose bit 7 */
00406     }
00407   while (looping);
00408 
00409   if (c >= 0)
00410     return c;
00411 
00412   if (c == SERIAL_TIMEOUT)
00413     error (_("Timeout reading from remote system."));
00414 
00415   perror_with_name (_("remote-monitor"));
00416 }
00417 
00418 
00419 /* Read a character from the remote system, doing all the fancy
00420    timeout stuff.  */
00421 
00422 static int
00423 readchar (int timeout)
00424 {
00425   int c;
00426   static enum
00427     {
00428       last_random, last_nl, last_cr, last_crnl
00429     }
00430   state = last_random;
00431   int looping;
00432 
00433   do
00434     {
00435       looping = 0;
00436       c = serial_readchar (monitor_desc, timeout);
00437 
00438       if (c >= 0)
00439         {
00440           c &= 0x7f;
00441           /* This seems to interfere with proper function of the
00442              input stream.  */
00443           if (monitor_debug_p || remote_debug)
00444             {
00445               char buf[2];
00446 
00447               buf[0] = c;
00448               buf[1] = '\0';
00449               puts_debug ("read -->", buf, "<--");
00450             }
00451 
00452         }
00453 
00454       /* Canonicialize \n\r combinations into one \r.  */
00455       if ((current_monitor->flags & MO_HANDLE_NL) != 0)
00456         {
00457           if ((c == '\r' && state == last_nl)
00458               || (c == '\n' && state == last_cr))
00459             {
00460               state = last_crnl;
00461               looping = 1;
00462             }
00463           else if (c == '\r')
00464             state = last_cr;
00465           else if (c != '\n')
00466             state = last_random;
00467           else
00468             {
00469               state = last_nl;
00470               c = '\r';
00471             }
00472         }
00473     }
00474   while (looping);
00475 
00476   if (c >= 0)
00477     return c;
00478 
00479   if (c == SERIAL_TIMEOUT)
00480 #if 0
00481     /* I fail to see how detaching here can be useful.  */
00482     if (in_monitor_wait)        /* Watchdog went off.  */
00483       {
00484         target_mourn_inferior ();
00485         error (_("GDB serial timeout has expired.  Target detached."));
00486       }
00487     else
00488 #endif
00489       error (_("Timeout reading from remote system."));
00490 
00491   perror_with_name (_("remote-monitor"));
00492 }
00493 
00494 /* Scan input from the remote system, until STRING is found.  If BUF is non-
00495    zero, then collect input until we have collected either STRING or BUFLEN-1
00496    chars.  In either case we terminate BUF with a 0.  If input overflows BUF
00497    because STRING can't be found, return -1, else return number of chars in BUF
00498    (minus the terminating NUL).  Note that in the non-overflow case, STRING
00499    will be at the end of BUF.  */
00500 
00501 int
00502 monitor_expect (char *string, char *buf, int buflen)
00503 {
00504   char *p = string;
00505   int obuflen = buflen;
00506   int c;
00507 
00508   if (monitor_debug_p)
00509     {
00510       char *safe_string = (char *) alloca ((strlen (string) * 4) + 1);
00511       monitor_printable_string (safe_string, string, 0);
00512       fprintf_unfiltered (gdb_stdlog, "MON Expecting '%s'\n", safe_string);
00513     }
00514 
00515   immediate_quit++;
00516   QUIT;
00517   while (1)
00518     {
00519       if (buf)
00520         {
00521           if (buflen < 2)
00522             {
00523               *buf = '\000';
00524               immediate_quit--;
00525               return -1;
00526             }
00527 
00528           c = readchar (timeout);
00529           if (c == '\000')
00530             continue;
00531           *buf++ = c;
00532           buflen--;
00533         }
00534       else
00535         c = readchar (timeout);
00536 
00537       /* Don't expect any ^C sent to be echoed.  */
00538 
00539       if (*p == '\003' || c == *p)
00540         {
00541           p++;
00542           if (*p == '\0')
00543             {
00544               immediate_quit--;
00545 
00546               if (buf)
00547                 {
00548                   *buf++ = '\000';
00549                   return obuflen - buflen;
00550                 }
00551               else
00552                 return 0;
00553             }
00554         }
00555       else
00556         {
00557           /* We got a character that doesn't match the string.  We need to
00558              back up p, but how far?  If we're looking for "..howdy" and the
00559              monitor sends "...howdy"?  There's certainly a match in there,
00560              but when we receive the third ".", we won't find it if we just
00561              restart the matching at the beginning of the string.
00562 
00563              This is a Boyer-Moore kind of situation.  We want to reset P to
00564              the end of the longest prefix of STRING that is a suffix of
00565              what we've read so far.  In the example above, that would be
00566              ".." --- the longest prefix of "..howdy" that is a suffix of
00567              "...".  This longest prefix could be the empty string, if C
00568              is nowhere to be found in STRING.
00569 
00570              If this longest prefix is not the empty string, it must contain
00571              C, so let's search from the end of STRING for instances of C,
00572              and see if the portion of STRING before that is a suffix of
00573              what we read before C.  Actually, we can search backwards from
00574              p, since we know no prefix can be longer than that.
00575 
00576              Note that we can use STRING itself, along with C, as a record
00577              of what we've received so far.  :)  */
00578           int i;
00579 
00580           for (i = (p - string) - 1; i >= 0; i--)
00581             if (string[i] == c)
00582               {
00583                 /* Is this prefix a suffix of what we've read so far?
00584                    In other words, does
00585                      string[0 .. i-1] == string[p - i, p - 1]?  */
00586                 if (! memcmp (string, p - i, i))
00587                   {
00588                     p = string + i + 1;
00589                     break;
00590                   }
00591               }
00592           if (i < 0)
00593             p = string;
00594         }
00595     }
00596 }
00597 
00598 /* Search for a regexp.  */
00599 
00600 static int
00601 monitor_expect_regexp (struct re_pattern_buffer *pat, char *buf, int buflen)
00602 {
00603   char *mybuf;
00604   char *p;
00605 
00606   monitor_debug ("MON Expecting regexp\n");
00607   if (buf)
00608     mybuf = buf;
00609   else
00610     {
00611       mybuf = alloca (TARGET_BUF_SIZE);
00612       buflen = TARGET_BUF_SIZE;
00613     }
00614 
00615   p = mybuf;
00616   while (1)
00617     {
00618       int retval;
00619 
00620       if (p - mybuf >= buflen)
00621         {                       /* Buffer about to overflow.  */
00622 
00623 /* On overflow, we copy the upper half of the buffer to the lower half.  Not
00624    great, but it usually works...  */
00625 
00626           memcpy (mybuf, mybuf + buflen / 2, buflen / 2);
00627           p = mybuf + buflen / 2;
00628         }
00629 
00630       *p++ = readchar (timeout);
00631 
00632       retval = re_search (pat, mybuf, p - mybuf, 0, p - mybuf, NULL);
00633       if (retval >= 0)
00634         return 1;
00635     }
00636 }
00637 
00638 /* Keep discarding input until we see the MONITOR prompt.
00639 
00640    The convention for dealing with the prompt is that you
00641    o give your command
00642    o *then* wait for the prompt.
00643 
00644    Thus the last thing that a procedure does with the serial line will
00645    be an monitor_expect_prompt().  Exception: monitor_resume does not
00646    wait for the prompt, because the terminal is being handed over to
00647    the inferior.  However, the next thing which happens after that is
00648    a monitor_wait which does wait for the prompt.  Note that this
00649    includes abnormal exit, e.g. error().  This is necessary to prevent
00650    getting into states from which we can't recover.  */
00651 
00652 int
00653 monitor_expect_prompt (char *buf, int buflen)
00654 {
00655   monitor_debug ("MON Expecting prompt\n");
00656   return monitor_expect (current_monitor->prompt, buf, buflen);
00657 }
00658 
00659 /* Get N 32-bit words from remote, each preceded by a space, and put
00660    them in registers starting at REGNO.  */
00661 
00662 #if 0
00663 static unsigned long
00664 get_hex_word (void)
00665 {
00666   unsigned long val;
00667   int i;
00668   int ch;
00669 
00670   do
00671     ch = readchar (timeout);
00672   while (isspace (ch));
00673 
00674   val = from_hex (ch);
00675 
00676   for (i = 7; i >= 1; i--)
00677     {
00678       ch = readchar (timeout);
00679       if (!isxdigit (ch))
00680         break;
00681       val = (val << 4) | from_hex (ch);
00682     }
00683 
00684   return val;
00685 }
00686 #endif
00687 
00688 static void
00689 compile_pattern (char *pattern, struct re_pattern_buffer *compiled_pattern,
00690                  char *fastmap)
00691 {
00692   int tmp;
00693   const char *val;
00694 
00695   compiled_pattern->fastmap = fastmap;
00696 
00697   tmp = re_set_syntax (RE_SYNTAX_EMACS);
00698   val = re_compile_pattern (pattern,
00699                             strlen (pattern),
00700                             compiled_pattern);
00701   re_set_syntax (tmp);
00702 
00703   if (val)
00704     error (_("compile_pattern: Can't compile pattern string `%s': %s!"),
00705            pattern, val);
00706 
00707   if (fastmap)
00708     re_compile_fastmap (compiled_pattern);
00709 }
00710 
00711 /* Open a connection to a remote debugger.  NAME is the filename used
00712    for communication.  */
00713 
00714 void
00715 monitor_open (char *args, struct monitor_ops *mon_ops, int from_tty)
00716 {
00717   char *name;
00718   char **p;
00719   struct inferior *inf;
00720 
00721   if (mon_ops->magic != MONITOR_OPS_MAGIC)
00722     error (_("Magic number of monitor_ops struct wrong."));
00723 
00724   targ_ops = mon_ops->target;
00725   name = targ_ops->to_shortname;
00726 
00727   if (!args)
00728     error (_("Use `target %s DEVICE-NAME' to use a serial port, or\n\
00729 `target %s HOST-NAME:PORT-NUMBER' to use a network connection."), name, name);
00730 
00731   target_preopen (from_tty);
00732 
00733   /* Setup pattern for register dump.  */
00734 
00735   if (mon_ops->register_pattern)
00736     compile_pattern (mon_ops->register_pattern, &register_pattern,
00737                      register_fastmap);
00738 
00739   if (mon_ops->getmem.resp_delim)
00740     compile_pattern (mon_ops->getmem.resp_delim, &getmem_resp_delim_pattern,
00741                      getmem_resp_delim_fastmap);
00742 
00743   if (mon_ops->setmem.resp_delim)
00744     compile_pattern (mon_ops->setmem.resp_delim, &setmem_resp_delim_pattern,
00745                      setmem_resp_delim_fastmap);
00746 
00747   if (mon_ops->setreg.resp_delim)
00748     compile_pattern (mon_ops->setreg.resp_delim, &setreg_resp_delim_pattern,
00749                      setreg_resp_delim_fastmap);
00750   
00751   unpush_target (targ_ops);
00752 
00753   if (dev_name)
00754     xfree (dev_name);
00755   dev_name = xstrdup (args);
00756 
00757   monitor_desc = serial_open (dev_name);
00758 
00759   if (!monitor_desc)
00760     perror_with_name (dev_name);
00761 
00762   if (baud_rate != -1)
00763     {
00764       if (serial_setbaudrate (monitor_desc, baud_rate))
00765         {
00766           serial_close (monitor_desc);
00767           perror_with_name (dev_name);
00768         }
00769     }
00770 
00771   serial_raw (monitor_desc);
00772 
00773   serial_flush_input (monitor_desc);
00774 
00775   /* some systems only work with 2 stop bits.  */
00776 
00777   serial_setstopbits (monitor_desc, mon_ops->stopbits);
00778 
00779   current_monitor = mon_ops;
00780 
00781   /* See if we can wake up the monitor.  First, try sending a stop sequence,
00782      then send the init strings.  Last, remove all breakpoints.  */
00783 
00784   if (current_monitor->stop)
00785     {
00786       monitor_stop (inferior_ptid);
00787       if ((current_monitor->flags & MO_NO_ECHO_ON_OPEN) == 0)
00788         {
00789           monitor_debug ("EXP Open echo\n");
00790           monitor_expect_prompt (NULL, 0);
00791         }
00792     }
00793 
00794   /* wake up the monitor and see if it's alive.  */
00795   for (p = mon_ops->init; *p != NULL; p++)
00796     {
00797       /* Some of the characters we send may not be echoed,
00798          but we hope to get a prompt at the end of it all.  */
00799 
00800       if ((current_monitor->flags & MO_NO_ECHO_ON_OPEN) == 0)
00801         monitor_printf (*p);
00802       else
00803         monitor_printf_noecho (*p);
00804       monitor_expect_prompt (NULL, 0);
00805     }
00806 
00807   serial_flush_input (monitor_desc);
00808 
00809   /* Alloc breakpoints */
00810   if (mon_ops->set_break != NULL)
00811     {
00812       if (mon_ops->num_breakpoints == 0)
00813         mon_ops->num_breakpoints = 8;
00814 
00815       breakaddr = (CORE_ADDR *)
00816         xmalloc (mon_ops->num_breakpoints * sizeof (CORE_ADDR));
00817       memset (breakaddr, 0, mon_ops->num_breakpoints * sizeof (CORE_ADDR));
00818     }
00819 
00820   /* Remove all breakpoints.  */
00821 
00822   if (mon_ops->clr_all_break)
00823     {
00824       monitor_printf (mon_ops->clr_all_break);
00825       monitor_expect_prompt (NULL, 0);
00826     }
00827 
00828   if (from_tty)
00829     printf_unfiltered (_("Remote target %s connected to %s\n"),
00830                        name, dev_name);
00831 
00832   push_target (targ_ops);
00833 
00834   /* Start afresh.  */
00835   init_thread_list ();
00836 
00837   /* Make run command think we are busy...  */
00838   inferior_ptid = monitor_ptid;
00839   inf = current_inferior ();
00840   inferior_appeared (inf, ptid_get_pid (inferior_ptid));
00841   add_thread_silent (inferior_ptid);
00842 
00843   /* Give monitor_wait something to read.  */
00844 
00845   monitor_printf (current_monitor->line_term);
00846 
00847   init_wait_for_inferior ();
00848 
00849   start_remote (from_tty);
00850 }
00851 
00852 /* Close out all files and local state before this target loses
00853    control.  */
00854 
00855 void
00856 monitor_close (void)
00857 {
00858   if (monitor_desc)
00859     serial_close (monitor_desc);
00860 
00861   /* Free breakpoint memory.  */
00862   if (breakaddr != NULL)
00863     {
00864       xfree (breakaddr);
00865       breakaddr = NULL;
00866     }
00867 
00868   monitor_desc = NULL;
00869 
00870   delete_thread_silent (monitor_ptid);
00871   delete_inferior_silent (ptid_get_pid (monitor_ptid));
00872 }
00873 
00874 /* Terminate the open connection to the remote debugger.  Use this
00875    when you want to detach and do something else with your gdb.  */
00876 
00877 static void
00878 monitor_detach (struct target_ops *ops, char *args, int from_tty)
00879 {
00880   unpush_target (ops);          /* calls monitor_close to do the real work.  */
00881   if (from_tty)
00882     printf_unfiltered (_("Ending remote %s debugging\n"), target_shortname);
00883 }
00884 
00885 /* Convert VALSTR into the target byte-ordered value of REGNO and store it.  */
00886 
00887 char *
00888 monitor_supply_register (struct regcache *regcache, int regno, char *valstr)
00889 {
00890   struct gdbarch *gdbarch = get_regcache_arch (regcache);
00891   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
00892   ULONGEST val;
00893   unsigned char regbuf[MAX_REGISTER_SIZE];
00894   char *p;
00895 
00896   val = 0;
00897   p = valstr;
00898   while (p && *p != '\0')
00899     {
00900       if (*p == '\r' || *p == '\n')
00901         {
00902           while (*p != '\0') 
00903               p++;
00904           break;
00905         }
00906       if (isspace (*p))
00907         {
00908           p++;
00909           continue;
00910         }
00911       if (!isxdigit (*p) && *p != 'x')
00912         {
00913           break;
00914         }
00915 
00916       val <<= 4;
00917       val += fromhex (*p++);
00918     }
00919   monitor_debug ("Supplying Register %d %s\n", regno, valstr);
00920 
00921   if (val == 0 && valstr == p)
00922     error (_("monitor_supply_register (%d):  bad value from monitor: %s."),
00923            regno, valstr);
00924 
00925   /* supply register stores in target byte order, so swap here.  */
00926 
00927   store_unsigned_integer (regbuf, register_size (gdbarch, regno), byte_order,
00928                           val);
00929 
00930   regcache_raw_supply (regcache, regno, regbuf);
00931 
00932   return p;
00933 }
00934 
00935 /* Tell the remote machine to resume.  */
00936 
00937 static void
00938 monitor_resume (struct target_ops *ops,
00939                 ptid_t ptid, int step, enum gdb_signal sig)
00940 {
00941   /* Some monitors require a different command when starting a program.  */
00942   monitor_debug ("MON resume\n");
00943   if (current_monitor->flags & MO_RUN_FIRST_TIME && first_time == 1)
00944     {
00945       first_time = 0;
00946       monitor_printf ("run\r");
00947       if (current_monitor->flags & MO_NEED_REGDUMP_AFTER_CONT)
00948         dump_reg_flag = 1;
00949       return;
00950     }
00951   if (step)
00952     monitor_printf (current_monitor->step);
00953   else
00954     {
00955       if (current_monitor->continue_hook)
00956         (*current_monitor->continue_hook) ();
00957       else
00958         monitor_printf (current_monitor->cont);
00959       if (current_monitor->flags & MO_NEED_REGDUMP_AFTER_CONT)
00960         dump_reg_flag = 1;
00961     }
00962 }
00963 
00964 /* Parse the output of a register dump command.  A monitor specific
00965    regexp is used to extract individual register descriptions of the
00966    form REG=VAL.  Each description is split up into a name and a value
00967    string which are passed down to monitor specific code.  */
00968 
00969 static void
00970 parse_register_dump (struct regcache *regcache, char *buf, int len)
00971 {
00972   monitor_debug ("MON Parsing  register dump\n");
00973   while (1)
00974     {
00975       int regnamelen, vallen;
00976       char *regname, *val;
00977 
00978       /* Element 0 points to start of register name, and element 1
00979          points to the start of the register value.  */
00980       struct re_registers register_strings;
00981 
00982       memset (&register_strings, 0, sizeof (struct re_registers));
00983 
00984       if (re_search (&register_pattern, buf, len, 0, len,
00985                      &register_strings) == -1)
00986         break;
00987 
00988       regnamelen = register_strings.end[1] - register_strings.start[1];
00989       regname = buf + register_strings.start[1];
00990       vallen = register_strings.end[2] - register_strings.start[2];
00991       val = buf + register_strings.start[2];
00992 
00993       current_monitor->supply_register (regcache, regname, regnamelen,
00994                                         val, vallen);
00995 
00996       buf += register_strings.end[0];
00997       len -= register_strings.end[0];
00998     }
00999 }
01000 
01001 /* Send ^C to target to halt it.  Target will respond, and send us a
01002    packet.  */
01003 
01004 static void
01005 monitor_interrupt (int signo)
01006 {
01007   /* If this doesn't work, try more severe steps.  */
01008   signal (signo, monitor_interrupt_twice);
01009 
01010   if (monitor_debug_p || remote_debug)
01011     fprintf_unfiltered (gdb_stdlog, "monitor_interrupt called\n");
01012 
01013   target_stop (inferior_ptid);
01014 }
01015 
01016 /* The user typed ^C twice.  */
01017 
01018 static void
01019 monitor_interrupt_twice (int signo)
01020 {
01021   signal (signo, ofunc);
01022 
01023   monitor_interrupt_query ();
01024 
01025   signal (signo, monitor_interrupt);
01026 }
01027 
01028 /* Ask the user what to do when an interrupt is received.  */
01029 
01030 static void
01031 monitor_interrupt_query (void)
01032 {
01033   target_terminal_ours ();
01034 
01035   if (query (_("Interrupted while waiting for the program.\n\
01036 Give up (and stop debugging it)? ")))
01037     {
01038       target_mourn_inferior ();
01039       quit ();
01040     }
01041 
01042   target_terminal_inferior ();
01043 }
01044 
01045 static void
01046 monitor_wait_cleanup (void *old_timeout)
01047 {
01048   timeout = *(int *) old_timeout;
01049   signal (SIGINT, ofunc);
01050   in_monitor_wait = 0;
01051 }
01052 
01053 
01054 
01055 static void
01056 monitor_wait_filter (char *buf,
01057                      int bufmax,
01058                      int *ext_resp_len,
01059                      struct target_waitstatus *status)
01060 {
01061   int resp_len;
01062 
01063   do
01064     {
01065       resp_len = monitor_expect_prompt (buf, bufmax);
01066       *ext_resp_len = resp_len;
01067 
01068       if (resp_len <= 0)
01069         fprintf_unfiltered (gdb_stderr,
01070                             "monitor_wait:  excessive "
01071                             "response from monitor: %s.", buf);
01072     }
01073   while (resp_len < 0);
01074 
01075   /* Print any output characters that were preceded by ^O.  */
01076   /* FIXME - This would be great as a user settabgle flag.  */
01077   if (monitor_debug_p || remote_debug
01078       || current_monitor->flags & MO_PRINT_PROGRAM_OUTPUT)
01079     {
01080       int i;
01081 
01082       for (i = 0; i < resp_len - 1; i++)
01083         if (buf[i] == 0x0f)
01084           putchar_unfiltered (buf[++i]);
01085     }
01086 }
01087 
01088 
01089 
01090 /* Wait until the remote machine stops, then return, storing status in
01091    status just as `wait' would.  */
01092 
01093 static ptid_t
01094 monitor_wait (struct target_ops *ops,
01095               ptid_t ptid, struct target_waitstatus *status, int options)
01096 {
01097   int old_timeout = timeout;
01098   char buf[TARGET_BUF_SIZE];
01099   int resp_len;
01100   struct cleanup *old_chain;
01101 
01102   status->kind = TARGET_WAITKIND_EXITED;
01103   status->value.integer = 0;
01104 
01105   old_chain = make_cleanup (monitor_wait_cleanup, &old_timeout);
01106   monitor_debug ("MON wait\n");
01107 
01108 #if 0
01109   /* This is somthing other than a maintenance command.  */
01110     in_monitor_wait = 1;
01111   timeout = watchdog > 0 ? watchdog : -1;
01112 #else
01113   timeout = -1;         /* Don't time out -- user program is running.  */
01114 #endif
01115 
01116   ofunc = (void (*)()) signal (SIGINT, monitor_interrupt);
01117 
01118   if (current_monitor->wait_filter)
01119     (*current_monitor->wait_filter) (buf, sizeof (buf), &resp_len, status);
01120   else
01121     monitor_wait_filter (buf, sizeof (buf), &resp_len, status);
01122 
01123 #if 0                           /* Transferred to monitor wait filter.  */
01124   do
01125     {
01126       resp_len = monitor_expect_prompt (buf, sizeof (buf));
01127 
01128       if (resp_len <= 0)
01129         fprintf_unfiltered (gdb_stderr,
01130                             "monitor_wait:  excessive "
01131                             "response from monitor: %s.", buf);
01132     }
01133   while (resp_len < 0);
01134 
01135   /* Print any output characters that were preceded by ^O.  */
01136   /* FIXME - This would be great as a user settabgle flag.  */
01137   if (monitor_debug_p || remote_debug
01138       || current_monitor->flags & MO_PRINT_PROGRAM_OUTPUT)
01139     {
01140       int i;
01141 
01142       for (i = 0; i < resp_len - 1; i++)
01143         if (buf[i] == 0x0f)
01144           putchar_unfiltered (buf[++i]);
01145     }
01146 #endif
01147 
01148   signal (SIGINT, ofunc);
01149 
01150   timeout = old_timeout;
01151 #if 0
01152   if (dump_reg_flag && current_monitor->dump_registers)
01153     {
01154       dump_reg_flag = 0;
01155       monitor_printf (current_monitor->dump_registers);
01156       resp_len = monitor_expect_prompt (buf, sizeof (buf));
01157     }
01158 
01159   if (current_monitor->register_pattern)
01160     parse_register_dump (get_current_regcache (), buf, resp_len);
01161 #else
01162   monitor_debug ("Wait fetching registers after stop\n");
01163   monitor_dump_regs (get_current_regcache ());
01164 #endif
01165 
01166   status->kind = TARGET_WAITKIND_STOPPED;
01167   status->value.sig = GDB_SIGNAL_TRAP;
01168 
01169   discard_cleanups (old_chain);
01170 
01171   in_monitor_wait = 0;
01172 
01173   return inferior_ptid;
01174 }
01175 
01176 /* Fetch register REGNO, or all registers if REGNO is -1.  Returns
01177    errno value.  */
01178 
01179 static void
01180 monitor_fetch_register (struct regcache *regcache, int regno)
01181 {
01182   const char *name;
01183   char *zerobuf;
01184   char *regbuf;
01185   int i;
01186 
01187   regbuf  = alloca (MAX_REGISTER_SIZE * 2 + 1);
01188   zerobuf = alloca (MAX_REGISTER_SIZE);
01189   memset (zerobuf, 0, MAX_REGISTER_SIZE);
01190 
01191   if (current_monitor->regname != NULL)
01192     name = current_monitor->regname (regno);
01193   else
01194     name = current_monitor->regnames[regno];
01195   monitor_debug ("MON fetchreg %d '%s'\n", regno, name ? name : "(null name)");
01196 
01197   if (!name || (*name == '\0'))
01198     {
01199       monitor_debug ("No register known for %d\n", regno);
01200       regcache_raw_supply (regcache, regno, zerobuf);
01201       return;
01202     }
01203 
01204   /* Send the register examine command.  */
01205 
01206   monitor_printf (current_monitor->getreg.cmd, name);
01207 
01208   /* If RESP_DELIM is specified, we search for that as a leading
01209      delimiter for the register value.  Otherwise, we just start
01210      searching from the start of the buf.  */
01211 
01212   if (current_monitor->getreg.resp_delim)
01213     {
01214       monitor_debug ("EXP getreg.resp_delim\n");
01215       monitor_expect (current_monitor->getreg.resp_delim, NULL, 0);
01216       /* Handle case of first 32 registers listed in pairs.  */
01217       if (current_monitor->flags & MO_32_REGS_PAIRED
01218           && (regno & 1) != 0 && regno < 32)
01219         {
01220           monitor_debug ("EXP getreg.resp_delim\n");
01221           monitor_expect (current_monitor->getreg.resp_delim, NULL, 0);
01222         }
01223     }
01224 
01225   /* Skip leading spaces and "0x" if MO_HEX_PREFIX flag is set.  */
01226   if (current_monitor->flags & MO_HEX_PREFIX)
01227     {
01228       int c;
01229 
01230       c = readchar (timeout);
01231       while (c == ' ')
01232         c = readchar (timeout);
01233       if ((c == '0') && ((c = readchar (timeout)) == 'x'))
01234         ;
01235       else
01236         error (_("Bad value returned from monitor "
01237                  "while fetching register %x."),
01238                regno);
01239     }
01240 
01241   /* Read upto the maximum number of hex digits for this register, skipping
01242      spaces, but stop reading if something else is seen.  Some monitors
01243      like to drop leading zeros.  */
01244 
01245   for (i = 0; i < register_size (get_regcache_arch (regcache), regno) * 2; i++)
01246     {
01247       int c;
01248 
01249       c = readchar (timeout);
01250       while (c == ' ')
01251         c = readchar (timeout);
01252 
01253       if (!isxdigit (c))
01254         break;
01255 
01256       regbuf[i] = c;
01257     }
01258 
01259   regbuf[i] = '\000';           /* Terminate the number.  */
01260   monitor_debug ("REGVAL '%s'\n", regbuf);
01261 
01262   /* If TERM is present, we wait for that to show up.  Also, (if TERM
01263      is present), we will send TERM_CMD if that is present.  In any
01264      case, we collect all of the output into buf, and then wait for
01265      the normal prompt.  */
01266 
01267   if (current_monitor->getreg.term)
01268     {
01269       monitor_debug ("EXP getreg.term\n");
01270       monitor_expect (current_monitor->getreg.term, NULL, 0); /* Get
01271                                                                  response.  */
01272     }
01273 
01274   if (current_monitor->getreg.term_cmd)
01275     {
01276       monitor_debug ("EMIT getreg.term.cmd\n");
01277       monitor_printf (current_monitor->getreg.term_cmd);
01278     }
01279   if (!current_monitor->getreg.term ||  /* Already expected or */
01280       current_monitor->getreg.term_cmd)         /* ack expected.  */
01281     monitor_expect_prompt (NULL, 0);    /* Get response.  */
01282 
01283   monitor_supply_register (regcache, regno, regbuf);
01284 }
01285 
01286 /* Sometimes, it takes several commands to dump the registers.  */
01287 /* This is a primitive for use by variations of monitor interfaces in
01288    case they need to compose the operation.  */
01289 
01290 int
01291 monitor_dump_reg_block (struct regcache *regcache, char *block_cmd)
01292 {
01293   char buf[TARGET_BUF_SIZE];
01294   int resp_len;
01295 
01296   monitor_printf (block_cmd);
01297   resp_len = monitor_expect_prompt (buf, sizeof (buf));
01298   parse_register_dump (regcache, buf, resp_len);
01299   return 1;
01300 }
01301 
01302 
01303 /* Read the remote registers into the block regs.  */
01304 /* Call the specific function if it has been provided.  */
01305 
01306 static void
01307 monitor_dump_regs (struct regcache *regcache)
01308 {
01309   char buf[TARGET_BUF_SIZE];
01310   int resp_len;
01311 
01312   if (current_monitor->dumpregs)
01313     (*(current_monitor->dumpregs)) (regcache);  /* Call supplied function.  */
01314   else if (current_monitor->dump_registers)     /* Default version.  */
01315     {
01316       monitor_printf (current_monitor->dump_registers);
01317       resp_len = monitor_expect_prompt (buf, sizeof (buf));
01318       parse_register_dump (regcache, buf, resp_len);
01319     }
01320   else
01321     /* Need some way to read registers.  */
01322     internal_error (__FILE__, __LINE__,
01323                     _("failed internal consistency check"));
01324 }
01325 
01326 static void
01327 monitor_fetch_registers (struct target_ops *ops,
01328                          struct regcache *regcache, int regno)
01329 {
01330   monitor_debug ("MON fetchregs\n");
01331   if (current_monitor->getreg.cmd)
01332     {
01333       if (regno >= 0)
01334         {
01335           monitor_fetch_register (regcache, regno);
01336           return;
01337         }
01338 
01339       for (regno = 0; regno < gdbarch_num_regs (get_regcache_arch (regcache));
01340            regno++)
01341         monitor_fetch_register (regcache, regno);
01342     }
01343   else
01344     {
01345       monitor_dump_regs (regcache);
01346     }
01347 }
01348 
01349 /* Store register REGNO, or all if REGNO == 0.  Return errno value.  */
01350 
01351 static void
01352 monitor_store_register (struct regcache *regcache, int regno)
01353 {
01354   int reg_size = register_size (get_regcache_arch (regcache), regno);
01355   const char *name;
01356   ULONGEST val;
01357   
01358   if (current_monitor->regname != NULL)
01359     name = current_monitor->regname (regno);
01360   else
01361     name = current_monitor->regnames[regno];
01362   
01363   if (!name || (*name == '\0'))
01364     {
01365       monitor_debug ("MON Cannot store unknown register\n");
01366       return;
01367     }
01368 
01369   regcache_cooked_read_unsigned (regcache, regno, &val);
01370   monitor_debug ("MON storeg %d %s\n", regno, phex (val, reg_size));
01371 
01372   /* Send the register deposit command.  */
01373 
01374   if (current_monitor->flags & MO_REGISTER_VALUE_FIRST)
01375     monitor_printf (current_monitor->setreg.cmd, val, name);
01376   else if (current_monitor->flags & MO_SETREG_INTERACTIVE)
01377     monitor_printf (current_monitor->setreg.cmd, name);
01378   else
01379     monitor_printf (current_monitor->setreg.cmd, name, val);
01380 
01381   if (current_monitor->setreg.resp_delim)
01382     {
01383       monitor_debug ("EXP setreg.resp_delim\n");
01384       monitor_expect_regexp (&setreg_resp_delim_pattern, NULL, 0);
01385       if (current_monitor->flags & MO_SETREG_INTERACTIVE)
01386         monitor_printf ("%s\r", phex_nz (val, reg_size));
01387     }
01388   if (current_monitor->setreg.term)
01389     {
01390       monitor_debug ("EXP setreg.term\n");
01391       monitor_expect (current_monitor->setreg.term, NULL, 0);
01392       if (current_monitor->flags & MO_SETREG_INTERACTIVE)
01393         monitor_printf ("%s\r", phex_nz (val, reg_size));
01394       monitor_expect_prompt (NULL, 0);
01395     }
01396   else
01397     monitor_expect_prompt (NULL, 0);
01398   if (current_monitor->setreg.term_cmd)         /* Mode exit required.  */
01399     {
01400       monitor_debug ("EXP setreg_termcmd\n");
01401       monitor_printf ("%s", current_monitor->setreg.term_cmd);
01402       monitor_expect_prompt (NULL, 0);
01403     }
01404 }                               /* monitor_store_register */
01405 
01406 /* Store the remote registers.  */
01407 
01408 static void
01409 monitor_store_registers (struct target_ops *ops,
01410                          struct regcache *regcache, int regno)
01411 {
01412   if (regno >= 0)
01413     {
01414       monitor_store_register (regcache, regno);
01415       return;
01416     }
01417 
01418   for (regno = 0; regno < gdbarch_num_regs (get_regcache_arch (regcache));
01419        regno++)
01420     monitor_store_register (regcache, regno);
01421 }
01422 
01423 /* Get ready to modify the registers array.  On machines which store
01424    individual registers, this doesn't need to do anything.  On machines
01425    which store all the registers in one fell swoop, this makes sure
01426    that registers contains all the registers from the program being
01427    debugged.  */
01428 
01429 static void
01430 monitor_prepare_to_store (struct regcache *regcache)
01431 {
01432   /* Do nothing, since we can store individual regs.  */
01433 }
01434 
01435 static void
01436 monitor_files_info (struct target_ops *ops)
01437 {
01438   printf_unfiltered (_("\tAttached to %s at %d baud.\n"), dev_name, baud_rate);
01439 }
01440 
01441 static int
01442 monitor_write_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
01443 {
01444   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
01445   unsigned int val, hostval;
01446   char *cmd;
01447   int i;
01448 
01449   monitor_debug ("MON write %d %s\n", len, paddress (target_gdbarch (), memaddr));
01450 
01451   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
01452     memaddr = gdbarch_addr_bits_remove (target_gdbarch (), memaddr);
01453 
01454   /* Use memory fill command for leading 0 bytes.  */
01455 
01456   if (current_monitor->fill)
01457     {
01458       for (i = 0; i < len; i++)
01459         if (myaddr[i] != 0)
01460           break;
01461 
01462       if (i > 4)                /* More than 4 zeros is worth doing.  */
01463         {
01464           monitor_debug ("MON FILL %d\n", i);
01465           if (current_monitor->flags & MO_FILL_USES_ADDR)
01466             monitor_printf (current_monitor->fill, memaddr,
01467                             (memaddr + i) - 1, 0);
01468           else
01469             monitor_printf (current_monitor->fill, memaddr, i, 0);
01470 
01471           monitor_expect_prompt (NULL, 0);
01472 
01473           return i;
01474         }
01475     }
01476 
01477 #if 0
01478   /* Can't actually use long longs if VAL is an int (nice idea, though).  */
01479   if ((memaddr & 0x7) == 0 && len >= 8 && current_monitor->setmem.cmdll)
01480     {
01481       len = 8;
01482       cmd = current_monitor->setmem.cmdll;
01483     }
01484   else
01485 #endif
01486   if ((memaddr & 0x3) == 0 && len >= 4 && current_monitor->setmem.cmdl)
01487     {
01488       len = 4;
01489       cmd = current_monitor->setmem.cmdl;
01490     }
01491   else if ((memaddr & 0x1) == 0 && len >= 2 && current_monitor->setmem.cmdw)
01492     {
01493       len = 2;
01494       cmd = current_monitor->setmem.cmdw;
01495     }
01496   else
01497     {
01498       len = 1;
01499       cmd = current_monitor->setmem.cmdb;
01500     }
01501 
01502   val = extract_unsigned_integer (myaddr, len, byte_order);
01503 
01504   if (len == 4)
01505     {
01506       hostval = *(unsigned int *) myaddr;
01507       monitor_debug ("Hostval(%08x) val(%08x)\n", hostval, val);
01508     }
01509 
01510 
01511   if (current_monitor->flags & MO_NO_ECHO_ON_SETMEM)
01512     monitor_printf_noecho (cmd, memaddr, val);
01513   else if (current_monitor->flags & MO_SETMEM_INTERACTIVE)
01514     {
01515       monitor_printf_noecho (cmd, memaddr);
01516 
01517       if (current_monitor->setmem.resp_delim)
01518         {
01519           monitor_debug ("EXP setmem.resp_delim");
01520           monitor_expect_regexp (&setmem_resp_delim_pattern, NULL, 0); 
01521           monitor_printf ("%x\r", val);
01522        }
01523       if (current_monitor->setmem.term)
01524         {
01525           monitor_debug ("EXP setmem.term");
01526           monitor_expect (current_monitor->setmem.term, NULL, 0);
01527           monitor_printf ("%x\r", val);
01528         }
01529       if (current_monitor->setmem.term_cmd)
01530         {       /* Emit this to get out of the memory editing state.  */
01531           monitor_printf ("%s", current_monitor->setmem.term_cmd);
01532           /* Drop through to expecting a prompt.  */
01533         }
01534     }
01535   else
01536     monitor_printf (cmd, memaddr, val);
01537 
01538   monitor_expect_prompt (NULL, 0);
01539 
01540   return len;
01541 }
01542 
01543 
01544 static int
01545 monitor_write_memory_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
01546 {
01547   unsigned char val;
01548   int written = 0;
01549 
01550   if (len == 0)
01551     return 0;
01552   /* Enter the sub mode.  */
01553   monitor_printf (current_monitor->setmem.cmdb, memaddr);
01554   monitor_expect_prompt (NULL, 0);
01555   while (len)
01556     {
01557       val = *myaddr;
01558       monitor_printf ("%x\r", val);
01559       myaddr++;
01560       memaddr++;
01561       written++;
01562       /* If we wanted to, here we could validate the address.  */
01563       monitor_expect_prompt (NULL, 0);
01564       len--;
01565     }
01566   /* Now exit the sub mode.  */
01567   monitor_printf (current_monitor->getreg.term_cmd);
01568   monitor_expect_prompt (NULL, 0);
01569   return written;
01570 }
01571 
01572 
01573 static void
01574 longlongendswap (unsigned char *a)
01575 {
01576   int i, j;
01577   unsigned char x;
01578 
01579   i = 0;
01580   j = 7;
01581   while (i < 4)
01582     {
01583       x = *(a + i);
01584       *(a + i) = *(a + j);
01585       *(a + j) = x;
01586       i++, j--;
01587     }
01588 }
01589 /* Format 32 chars of long long value, advance the pointer.  */
01590 static char *hexlate = "0123456789abcdef";
01591 static char *
01592 longlong_hexchars (unsigned long long value,
01593                    char *outbuff)
01594 {
01595   if (value == 0)
01596     {
01597       *outbuff++ = '0';
01598       return outbuff;
01599     }
01600   else
01601     {
01602       static unsigned char disbuf[8];   /* disassembly buffer */
01603       unsigned char *scan, *limit;      /* loop controls */
01604       unsigned char c, nib;
01605       int leadzero = 1;
01606 
01607       scan = disbuf;
01608       limit = scan + 8;
01609       {
01610         unsigned long long *dp;
01611 
01612         dp = (unsigned long long *) scan;
01613         *dp = value;
01614       }
01615       longlongendswap (disbuf); /* FIXME: ONly on big endian hosts.  */
01616       while (scan < limit)
01617         {
01618           c = *scan++;          /* A byte of our long long value.  */
01619           if (leadzero)
01620             {
01621               if (c == 0)
01622                 continue;
01623               else
01624                 leadzero = 0;   /* Henceforth we print even zeroes.  */
01625             }
01626           nib = c >> 4;         /* high nibble bits */
01627           *outbuff++ = hexlate[nib];
01628           nib = c & 0x0f;       /* low nibble bits */
01629           *outbuff++ = hexlate[nib];
01630         }
01631       return outbuff;
01632     }
01633 }                               /* longlong_hexchars */
01634 
01635 
01636 
01637 /* I am only going to call this when writing virtual byte streams.
01638    Which possably entails endian conversions.  */
01639 
01640 static int
01641 monitor_write_memory_longlongs (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
01642 {
01643   static char hexstage[20];     /* At least 16 digits required, plus null.  */
01644   char *endstring;
01645   long long *llptr;
01646   long long value;
01647   int written = 0;
01648 
01649   llptr = (long long *) myaddr;
01650   if (len == 0)
01651     return 0;
01652   monitor_printf (current_monitor->setmem.cmdll, memaddr);
01653   monitor_expect_prompt (NULL, 0);
01654   while (len >= 8)
01655     {
01656       value = *llptr;
01657       endstring = longlong_hexchars (*llptr, hexstage);
01658       *endstring = '\0';        /* NUll terminate for printf.  */
01659       monitor_printf ("%s\r", hexstage);
01660       llptr++;
01661       memaddr += 8;
01662       written += 8;
01663       /* If we wanted to, here we could validate the address.  */
01664       monitor_expect_prompt (NULL, 0);
01665       len -= 8;
01666     }
01667   /* Now exit the sub mode.  */
01668   monitor_printf (current_monitor->getreg.term_cmd);
01669   monitor_expect_prompt (NULL, 0);
01670   return written;
01671 }                               /* */
01672 
01673 
01674 
01675 /* ----- MONITOR_WRITE_MEMORY_BLOCK ---------------------------- */
01676 /* This is for the large blocks of memory which may occur in downloading.
01677    And for monitors which use interactive entry,
01678    And for monitors which do not have other downloading methods.
01679    Without this, we will end up calling monitor_write_memory many times
01680    and do the entry and exit of the sub mode many times
01681    This currently assumes...
01682    MO_SETMEM_INTERACTIVE
01683    ! MO_NO_ECHO_ON_SETMEM
01684    To use this, the you have to patch the monitor_cmds block with
01685    this function.  Otherwise, its not tuned up for use by all
01686    monitor variations.  */
01687 
01688 static int
01689 monitor_write_memory_block (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
01690 {
01691   int written;
01692 
01693   written = 0;
01694   /* FIXME: This would be a good place to put the zero test.  */
01695 #if 1
01696   if ((len > 8) && (((len & 0x07)) == 0) && current_monitor->setmem.cmdll)
01697     {
01698       return monitor_write_memory_longlongs (memaddr, myaddr, len);
01699     }
01700 #endif
01701   written = monitor_write_memory_bytes (memaddr, myaddr, len);
01702   return written;
01703 }
01704 
01705 /* This is an alternate form of monitor_read_memory which is used for monitors
01706    which can only read a single byte/word/etc. at a time.  */
01707 
01708 static int
01709 monitor_read_memory_single (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
01710 {
01711   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
01712   unsigned int val;
01713   char membuf[sizeof (int) * 2 + 1];
01714   char *p;
01715   char *cmd;
01716 
01717   monitor_debug ("MON read single\n");
01718 #if 0
01719   /* Can't actually use long longs (nice idea, though).  In fact, the
01720      call to strtoul below will fail if it tries to convert a value
01721      that's too big to fit in a long.  */
01722   if ((memaddr & 0x7) == 0 && len >= 8 && current_monitor->getmem.cmdll)
01723     {
01724       len = 8;
01725       cmd = current_monitor->getmem.cmdll;
01726     }
01727   else
01728 #endif
01729   if ((memaddr & 0x3) == 0 && len >= 4 && current_monitor->getmem.cmdl)
01730     {
01731       len = 4;
01732       cmd = current_monitor->getmem.cmdl;
01733     }
01734   else if ((memaddr & 0x1) == 0 && len >= 2 && current_monitor->getmem.cmdw)
01735     {
01736       len = 2;
01737       cmd = current_monitor->getmem.cmdw;
01738     }
01739   else
01740     {
01741       len = 1;
01742       cmd = current_monitor->getmem.cmdb;
01743     }
01744 
01745   /* Send the examine command.  */
01746 
01747   monitor_printf (cmd, memaddr);
01748 
01749   /* If RESP_DELIM is specified, we search for that as a leading
01750      delimiter for the memory value.  Otherwise, we just start
01751      searching from the start of the buf.  */
01752 
01753   if (current_monitor->getmem.resp_delim)
01754     {
01755       monitor_debug ("EXP getmem.resp_delim\n");
01756       monitor_expect_regexp (&getmem_resp_delim_pattern, NULL, 0);
01757     }
01758 
01759   /* Now, read the appropriate number of hex digits for this loc,
01760      skipping spaces.  */
01761 
01762   /* Skip leading spaces and "0x" if MO_HEX_PREFIX flag is set.  */
01763   if (current_monitor->flags & MO_HEX_PREFIX)
01764     {
01765       int c;
01766 
01767       c = readchar (timeout);
01768       while (c == ' ')
01769         c = readchar (timeout);
01770       if ((c == '0') && ((c = readchar (timeout)) == 'x'))
01771         ;
01772       else
01773         monitor_error ("monitor_read_memory_single", 
01774                        "bad response from monitor",
01775                        memaddr, 0, NULL, 0);
01776     }
01777 
01778   {
01779     int i;
01780 
01781     for (i = 0; i < len * 2; i++)
01782       {
01783         int c;
01784 
01785         while (1)
01786           {
01787             c = readchar (timeout);
01788             if (isxdigit (c))
01789               break;
01790             if (c == ' ')
01791               continue;
01792             
01793             monitor_error ("monitor_read_memory_single",
01794                            "bad response from monitor",
01795                            memaddr, i, membuf, 0);
01796           }
01797       membuf[i] = c;
01798     }
01799     membuf[i] = '\000';         /* Terminate the number.  */
01800   }
01801 
01802 /* If TERM is present, we wait for that to show up.  Also, (if TERM is
01803    present), we will send TERM_CMD if that is present.  In any case, we collect
01804    all of the output into buf, and then wait for the normal prompt.  */
01805 
01806   if (current_monitor->getmem.term)
01807     {
01808       monitor_expect (current_monitor->getmem.term, NULL, 0); /* Get
01809                                                                  response.  */
01810 
01811       if (current_monitor->getmem.term_cmd)
01812         {
01813           monitor_printf (current_monitor->getmem.term_cmd);
01814           monitor_expect_prompt (NULL, 0);
01815         }
01816     }
01817   else
01818     monitor_expect_prompt (NULL, 0);    /* Get response.  */
01819 
01820   p = membuf;
01821   val = strtoul (membuf, &p, 16);
01822 
01823   if (val == 0 && membuf == p)
01824     monitor_error ("monitor_read_memory_single",
01825                    "bad value from monitor",
01826                    memaddr, 0, membuf, 0);
01827 
01828   /* supply register stores in target byte order, so swap here.  */
01829 
01830   store_unsigned_integer (myaddr, len, byte_order, val);
01831 
01832   return len;
01833 }
01834 
01835 /* Copy LEN bytes of data from debugger memory at MYADDR to inferior's
01836    memory at MEMADDR.  Returns length moved.  Currently, we do no more
01837    than 16 bytes at a time.  */
01838 
01839 static int
01840 monitor_read_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
01841 {
01842   unsigned int val;
01843   char buf[512];
01844   char *p, *p1;
01845   int resp_len;
01846   int i;
01847   CORE_ADDR dumpaddr;
01848 
01849   if (len <= 0)
01850     {
01851       monitor_debug ("Zero length call to monitor_read_memory\n");
01852       return 0;
01853     }
01854 
01855   monitor_debug ("MON read block ta(%s) ha(%s) %d\n",
01856                  paddress (target_gdbarch (), memaddr),
01857                  host_address_to_string (myaddr), len);
01858 
01859   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
01860     memaddr = gdbarch_addr_bits_remove (target_gdbarch (), memaddr);
01861 
01862   if (current_monitor->flags & MO_GETMEM_READ_SINGLE)
01863     return monitor_read_memory_single (memaddr, myaddr, len);
01864 
01865   len = min (len, 16);
01866 
01867   /* Some dumpers align the first data with the preceding 16
01868      byte boundary.  Some print blanks and start at the
01869      requested boundary.  EXACT_DUMPADDR  */
01870 
01871   dumpaddr = (current_monitor->flags & MO_EXACT_DUMPADDR)
01872     ? memaddr : memaddr & ~0x0f;
01873 
01874   /* See if xfer would cross a 16 byte boundary.  If so, clip it.  */
01875   if (((memaddr ^ (memaddr + len - 1)) & ~0xf) != 0)
01876     len = ((memaddr + len) & ~0xf) - memaddr;
01877 
01878   /* Send the memory examine command.  */
01879 
01880   if (current_monitor->flags & MO_GETMEM_NEEDS_RANGE)
01881     monitor_printf (current_monitor->getmem.cmdb, memaddr, memaddr + len);
01882   else if (current_monitor->flags & MO_GETMEM_16_BOUNDARY)
01883     monitor_printf (current_monitor->getmem.cmdb, dumpaddr);
01884   else
01885     monitor_printf (current_monitor->getmem.cmdb, memaddr, len);
01886 
01887   /* If TERM is present, we wait for that to show up.  Also, (if TERM
01888      is present), we will send TERM_CMD if that is present.  In any
01889      case, we collect all of the output into buf, and then wait for
01890      the normal prompt.  */
01891 
01892   if (current_monitor->getmem.term)
01893     {
01894       resp_len = monitor_expect (current_monitor->getmem.term,
01895                                  buf, sizeof buf);      /* Get response.  */
01896 
01897       if (resp_len <= 0)
01898         monitor_error ("monitor_read_memory",
01899                        "excessive response from monitor",
01900                        memaddr, resp_len, buf, 0);
01901 
01902       if (current_monitor->getmem.term_cmd)
01903         {
01904           serial_write (monitor_desc, current_monitor->getmem.term_cmd,
01905                         strlen (current_monitor->getmem.term_cmd));
01906           monitor_expect_prompt (NULL, 0);
01907         }
01908     }
01909   else
01910     resp_len = monitor_expect_prompt (buf, sizeof buf);  /* Get response.  */
01911 
01912   p = buf;
01913 
01914   /* If RESP_DELIM is specified, we search for that as a leading
01915      delimiter for the values.  Otherwise, we just start searching
01916      from the start of the buf.  */
01917 
01918   if (current_monitor->getmem.resp_delim)
01919     {
01920       int retval, tmp;
01921       struct re_registers resp_strings;
01922 
01923       monitor_debug ("MON getmem.resp_delim %s\n",
01924                      current_monitor->getmem.resp_delim);
01925 
01926       memset (&resp_strings, 0, sizeof (struct re_registers));
01927       tmp = strlen (p);
01928       retval = re_search (&getmem_resp_delim_pattern, p, tmp, 0, tmp,
01929                           &resp_strings);
01930 
01931       if (retval < 0)
01932         monitor_error ("monitor_read_memory",
01933                        "bad response from monitor",
01934                        memaddr, resp_len, buf, 0);
01935 
01936       p += resp_strings.end[0];
01937 #if 0
01938       p = strstr (p, current_monitor->getmem.resp_delim);
01939       if (!p)
01940         monitor_error ("monitor_read_memory",
01941                        "bad response from monitor",
01942                        memaddr, resp_len, buf, 0);
01943       p += strlen (current_monitor->getmem.resp_delim);
01944 #endif
01945     }
01946   monitor_debug ("MON scanning  %d ,%s '%s'\n", len,
01947                  host_address_to_string (p), p);
01948   if (current_monitor->flags & MO_GETMEM_16_BOUNDARY)
01949     {
01950       char c;
01951       int fetched = 0;
01952       i = len;
01953       c = *p;
01954 
01955 
01956       while (!(c == '\000' || c == '\n' || c == '\r') && i > 0)
01957         {
01958           if (isxdigit (c))
01959             {
01960               if ((dumpaddr >= memaddr) && (i > 0))
01961                 {
01962                   val = fromhex (c) * 16 + fromhex (*(p + 1));
01963                   *myaddr++ = val;
01964                   if (monitor_debug_p || remote_debug)
01965                     fprintf_unfiltered (gdb_stdlog, "[%02x]", val);
01966                   --i;
01967                   fetched++;
01968                 }
01969               ++dumpaddr;
01970               ++p;
01971             }
01972           ++p;                  /* Skip a blank or other non hex char.  */
01973           c = *p;
01974         }
01975       if (fetched == 0)
01976         error (_("Failed to read via monitor"));
01977       if (monitor_debug_p || remote_debug)
01978         fprintf_unfiltered (gdb_stdlog, "\n");
01979       return fetched;           /* Return the number of bytes actually
01980                                    read.  */
01981     }
01982   monitor_debug ("MON scanning bytes\n");
01983 
01984   for (i = len; i > 0; i--)
01985     {
01986       /* Skip non-hex chars, but bomb on end of string and newlines.  */
01987 
01988       while (1)
01989         {
01990           if (isxdigit (*p))
01991             break;
01992 
01993           if (*p == '\000' || *p == '\n' || *p == '\r')
01994             monitor_error ("monitor_read_memory",
01995                            "badly terminated response from monitor",
01996                            memaddr, resp_len, buf, 0);
01997           p++;
01998         }
01999 
02000       val = strtoul (p, &p1, 16);
02001 
02002       if (val == 0 && p == p1)
02003         monitor_error ("monitor_read_memory",
02004                        "bad value from monitor",
02005                        memaddr, resp_len, buf, 0);
02006 
02007       *myaddr++ = val;
02008 
02009       if (i == 1)
02010         break;
02011 
02012       p = p1;
02013     }
02014 
02015   return len;
02016 }
02017 
02018 /* Helper for monitor_xfer_partial that handles memory transfers.
02019    Arguments are like target_xfer_partial.  */
02020 
02021 static LONGEST
02022 monitor_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
02023                      ULONGEST memaddr, LONGEST len)
02024 {
02025   int res;
02026 
02027   if (writebuf != NULL)
02028     {
02029       if (current_monitor->flags & MO_HAS_BLOCKWRITES)
02030         res = monitor_write_memory_block (memaddr, writebuf, len);
02031       else
02032         res = monitor_write_memory (memaddr, writebuf, len);
02033     }
02034   else
02035     {
02036       res = monitor_read_memory (memaddr, readbuf, len);
02037     }
02038 
02039   if (res == 0)
02040     return TARGET_XFER_E_IO;
02041   return res;
02042 }
02043 
02044 /* Target to_xfer_partial implementation.  */
02045 
02046 static LONGEST
02047 monitor_xfer_partial (struct target_ops *ops, enum target_object object,
02048                       const char *annex, gdb_byte *readbuf,
02049                       const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
02050 {
02051   switch (object)
02052     {
02053     case TARGET_OBJECT_MEMORY:
02054       return monitor_xfer_memory (readbuf, writebuf, offset, len);
02055 
02056     default:
02057       return TARGET_XFER_E_IO;
02058     }
02059 }
02060 
02061 static void
02062 monitor_kill (struct target_ops *ops)
02063 {
02064   return;                       /* Ignore attempts to kill target system.  */
02065 }
02066 
02067 /* All we actually do is set the PC to the start address of exec_bfd.  */
02068 
02069 static void
02070 monitor_create_inferior (struct target_ops *ops, char *exec_file,
02071                          char *args, char **env, int from_tty)
02072 {
02073   if (args && (*args != '\000'))
02074     error (_("Args are not supported by the monitor."));
02075 
02076   first_time = 1;
02077   clear_proceed_status ();
02078   regcache_write_pc (get_current_regcache (),
02079                      bfd_get_start_address (exec_bfd));
02080 }
02081 
02082 /* Clean up when a program exits.
02083    The program actually lives on in the remote processor's RAM, and may be
02084    run again without a download.  Don't leave it full of breakpoint
02085    instructions.  */
02086 
02087 static void
02088 monitor_mourn_inferior (struct target_ops *ops)
02089 {
02090   unpush_target (targ_ops);
02091   generic_mourn_inferior ();    /* Do all the proper things now.  */
02092   delete_thread_silent (monitor_ptid);
02093 }
02094 
02095 /* Tell the monitor to add a breakpoint.  */
02096 
02097 static int
02098 monitor_insert_breakpoint (struct gdbarch *gdbarch,
02099                            struct bp_target_info *bp_tgt)
02100 {
02101   CORE_ADDR addr = bp_tgt->placed_address;
02102   int i;
02103   int bplen;
02104 
02105   monitor_debug ("MON inst bkpt %s\n", paddress (gdbarch, addr));
02106   if (current_monitor->set_break == NULL)
02107     error (_("No set_break defined for this monitor"));
02108 
02109   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
02110     addr = gdbarch_addr_bits_remove (gdbarch, addr);
02111 
02112   /* Determine appropriate breakpoint size for this address.  */
02113   gdbarch_breakpoint_from_pc (gdbarch, &addr, &bplen);
02114   bp_tgt->placed_address = addr;
02115   bp_tgt->placed_size = bplen;
02116 
02117   for (i = 0; i < current_monitor->num_breakpoints; i++)
02118     {
02119       if (breakaddr[i] == 0)
02120         {
02121           breakaddr[i] = addr;
02122           monitor_printf (current_monitor->set_break, addr);
02123           monitor_expect_prompt (NULL, 0);
02124           return 0;
02125         }
02126     }
02127 
02128   error (_("Too many breakpoints (> %d) for monitor."),
02129          current_monitor->num_breakpoints);
02130 }
02131 
02132 /* Tell the monitor to remove a breakpoint.  */
02133 
02134 static int
02135 monitor_remove_breakpoint (struct gdbarch *gdbarch,
02136                            struct bp_target_info *bp_tgt)
02137 {
02138   CORE_ADDR addr = bp_tgt->placed_address;
02139   int i;
02140 
02141   monitor_debug ("MON rmbkpt %s\n", paddress (gdbarch, addr));
02142   if (current_monitor->clr_break == NULL)
02143     error (_("No clr_break defined for this monitor"));
02144 
02145   for (i = 0; i < current_monitor->num_breakpoints; i++)
02146     {
02147       if (breakaddr[i] == addr)
02148         {
02149           breakaddr[i] = 0;
02150           /* Some monitors remove breakpoints based on the address.  */
02151           if (current_monitor->flags & MO_CLR_BREAK_USES_ADDR)
02152             monitor_printf (current_monitor->clr_break, addr);
02153           else if (current_monitor->flags & MO_CLR_BREAK_1_BASED)
02154             monitor_printf (current_monitor->clr_break, i + 1);
02155           else
02156             monitor_printf (current_monitor->clr_break, i);
02157           monitor_expect_prompt (NULL, 0);
02158           return 0;
02159         }
02160     }
02161   fprintf_unfiltered (gdb_stderr,
02162                       "Can't find breakpoint associated with %s\n",
02163                       paddress (gdbarch, addr));
02164   return 1;
02165 }
02166 
02167 /* monitor_wait_srec_ack -- wait for the target to send an acknowledgement for
02168    an S-record.  Return non-zero if the ACK is received properly.  */
02169 
02170 static int
02171 monitor_wait_srec_ack (void)
02172 {
02173   int ch;
02174 
02175   if (current_monitor->flags & MO_SREC_ACK_PLUS)
02176     {
02177       return (readchar (timeout) == '+');
02178     }
02179   else if (current_monitor->flags & MO_SREC_ACK_ROTATE)
02180     {
02181       /* Eat two backspaces, a "rotating" char (|/-\), and a space.  */
02182       if ((ch = readchar (1)) < 0)
02183         return 0;
02184       if ((ch = readchar (1)) < 0)
02185         return 0;
02186       if ((ch = readchar (1)) < 0)
02187         return 0;
02188       if ((ch = readchar (1)) < 0)
02189         return 0;
02190     }
02191   return 1;
02192 }
02193 
02194 /* monitor_load -- download a file.  */
02195 
02196 static void
02197 monitor_load (char *args, int from_tty)
02198 {
02199   CORE_ADDR load_offset = 0;
02200   char **argv;
02201   struct cleanup *old_cleanups;
02202   char *filename;
02203 
02204   monitor_debug ("MON load\n");
02205 
02206   if (args == NULL)
02207     error_no_arg (_("file to load"));
02208 
02209   argv = gdb_buildargv (args);
02210   old_cleanups = make_cleanup_freeargv (argv);
02211 
02212   filename = tilde_expand (argv[0]);
02213   make_cleanup (xfree, filename);
02214 
02215   /* Enable user to specify address for downloading as 2nd arg to load.  */
02216   if (argv[1] != NULL)
02217     {
02218       const char *endptr;
02219 
02220       load_offset = strtoulst (argv[1], &endptr, 0);
02221 
02222       /* If the last word was not a valid number then
02223          treat it as a file name with spaces in.  */
02224       if (argv[1] == endptr)
02225         error (_("Invalid download offset:%s."), argv[1]);
02226 
02227       if (argv[2] != NULL)
02228         error (_("Too many parameters."));
02229     }
02230 
02231   monitor_printf (current_monitor->load);
02232   if (current_monitor->loadresp)
02233     monitor_expect (current_monitor->loadresp, NULL, 0);
02234 
02235   load_srec (monitor_desc, filename, load_offset,
02236              32, SREC_ALL, hashmark,
02237              current_monitor->flags & MO_SREC_ACK ?
02238              monitor_wait_srec_ack : NULL);
02239 
02240   monitor_expect_prompt (NULL, 0);
02241 
02242   do_cleanups (old_cleanups);
02243 
02244   /* Finally, make the PC point at the start address.  */
02245   if (exec_bfd)
02246     regcache_write_pc (get_current_regcache (),
02247                        bfd_get_start_address (exec_bfd));
02248 
02249   /* There used to be code here which would clear inferior_ptid and
02250      call clear_symtab_users.  None of that should be necessary:
02251      monitor targets should behave like remote protocol targets, and
02252      since generic_load does none of those things, this function
02253      shouldn't either.
02254 
02255      Furthermore, clearing inferior_ptid is *incorrect*.  After doing
02256      a load, we still have a valid connection to the monitor, with a
02257      live processor state to fiddle with.  The user can type
02258      `continue' or `jump *start' and make the program run.  If they do
02259      these things, however, GDB will be talking to a running program
02260      while inferior_ptid is null_ptid; this makes things like
02261      reinit_frame_cache very confused.  */
02262 }
02263 
02264 static void
02265 monitor_stop (ptid_t ptid)
02266 {
02267   monitor_debug ("MON stop\n");
02268   if ((current_monitor->flags & MO_SEND_BREAK_ON_STOP) != 0)
02269     serial_send_break (monitor_desc);
02270   if (current_monitor->stop)
02271     monitor_printf_noecho (current_monitor->stop);
02272 }
02273 
02274 /* Put a COMMAND string out to MONITOR.  Output from MONITOR is placed
02275    in OUTPUT until the prompt is seen.  FIXME: We read the characters
02276    ourseleves here cause of a nasty echo.  */
02277 
02278 static void
02279 monitor_rcmd (char *command,
02280               struct ui_file *outbuf)
02281 {
02282   char *p;
02283   int resp_len;
02284   char buf[1000];
02285 
02286   if (monitor_desc == NULL)
02287     error (_("monitor target not open."));
02288 
02289   p = current_monitor->prompt;
02290 
02291   /* Send the command.  Note that if no args were supplied, then we're
02292      just sending the monitor a newline, which is sometimes useful.  */
02293 
02294   monitor_printf ("%s\r", (command ? command : ""));
02295 
02296   resp_len = monitor_expect_prompt (buf, sizeof buf);
02297 
02298   fputs_unfiltered (buf, outbuf);       /* Output the response.  */
02299 }
02300 
02301 /* Convert hex digit A to a number.  */
02302 
02303 #if 0
02304 static int
02305 from_hex (int a)
02306 {
02307   if (a >= '0' && a <= '9')
02308     return a - '0';
02309   if (a >= 'a' && a <= 'f')
02310     return a - 'a' + 10;
02311   if (a >= 'A' && a <= 'F')
02312     return a - 'A' + 10;
02313 
02314   error (_("Reply contains invalid hex digit 0x%x"), a);
02315 }
02316 #endif
02317 
02318 char *
02319 monitor_get_dev_name (void)
02320 {
02321   return dev_name;
02322 }
02323 
02324 /* Check to see if a thread is still alive.  */
02325 
02326 static int
02327 monitor_thread_alive (struct target_ops *ops, ptid_t ptid)
02328 {
02329   if (ptid_equal (ptid, monitor_ptid))
02330     /* The monitor's task is always alive.  */
02331     return 1;
02332 
02333   return 0;
02334 }
02335 
02336 /* Convert a thread ID to a string.  Returns the string in a static
02337    buffer.  */
02338 
02339 static char *
02340 monitor_pid_to_str (struct target_ops *ops, ptid_t ptid)
02341 {
02342   static char buf[64];
02343 
02344   if (ptid_equal (monitor_ptid, ptid))
02345     {
02346       xsnprintf (buf, sizeof buf, "Thread <main>");
02347       return buf;
02348     }
02349 
02350   return normal_pid_to_str (ptid);
02351 }
02352 
02353 static struct target_ops monitor_ops;
02354 
02355 static void
02356 init_base_monitor_ops (void)
02357 {
02358   monitor_ops.to_close = monitor_close;
02359   monitor_ops.to_detach = monitor_detach;
02360   monitor_ops.to_resume = monitor_resume;
02361   monitor_ops.to_wait = monitor_wait;
02362   monitor_ops.to_fetch_registers = monitor_fetch_registers;
02363   monitor_ops.to_store_registers = monitor_store_registers;
02364   monitor_ops.to_prepare_to_store = monitor_prepare_to_store;
02365   monitor_ops.to_xfer_partial = monitor_xfer_partial;
02366   monitor_ops.to_files_info = monitor_files_info;
02367   monitor_ops.to_insert_breakpoint = monitor_insert_breakpoint;
02368   monitor_ops.to_remove_breakpoint = monitor_remove_breakpoint;
02369   monitor_ops.to_kill = monitor_kill;
02370   monitor_ops.to_load = monitor_load;
02371   monitor_ops.to_create_inferior = monitor_create_inferior;
02372   monitor_ops.to_mourn_inferior = monitor_mourn_inferior;
02373   monitor_ops.to_stop = monitor_stop;
02374   monitor_ops.to_rcmd = monitor_rcmd;
02375   monitor_ops.to_log_command = serial_log_command;
02376   monitor_ops.to_thread_alive = monitor_thread_alive;
02377   monitor_ops.to_pid_to_str = monitor_pid_to_str;
02378   monitor_ops.to_stratum = process_stratum;
02379   monitor_ops.to_has_all_memory = default_child_has_all_memory;
02380   monitor_ops.to_has_memory = default_child_has_memory;
02381   monitor_ops.to_has_stack = default_child_has_stack;
02382   monitor_ops.to_has_registers = default_child_has_registers;
02383   monitor_ops.to_has_execution = default_child_has_execution;
02384   monitor_ops.to_magic = OPS_MAGIC;
02385 }                               /* init_base_monitor_ops */
02386 
02387 /* Init the target_ops structure pointed at by OPS.  */
02388 
02389 void
02390 init_monitor_ops (struct target_ops *ops)
02391 {
02392   if (monitor_ops.to_magic != OPS_MAGIC)
02393     init_base_monitor_ops ();
02394 
02395   memcpy (ops, &monitor_ops, sizeof monitor_ops);
02396 }
02397 
02398 /* Define additional commands that are usually only used by monitors.  */
02399 
02400 /* -Wmissing-prototypes */
02401 extern initialize_file_ftype _initialize_remote_monitors;
02402 
02403 void
02404 _initialize_remote_monitors (void)
02405 {
02406   init_base_monitor_ops ();
02407   add_setshow_boolean_cmd ("hash", no_class, &hashmark, _("\
02408 Set display of activity while downloading a file."), _("\
02409 Show display of activity while downloading a file."), _("\
02410 When enabled, a hashmark \'#\' is displayed."),
02411                            NULL,
02412                            NULL, /* FIXME: i18n: */
02413                            &setlist, &showlist);
02414 
02415   add_setshow_zuinteger_cmd ("monitor", no_class, &monitor_debug_p, _("\
02416 Set debugging of remote monitor communication."), _("\
02417 Show debugging of remote monitor communication."), _("\
02418 When enabled, communication between GDB and the remote monitor\n\
02419 is displayed."),
02420                              NULL,
02421                              NULL, /* FIXME: i18n: */
02422                              &setdebuglist, &showdebuglist);
02423 
02424   /* Yes, 42000 is arbitrary.  The only sense out of it, is that it
02425      isn't 0.  */
02426   monitor_ptid = ptid_build (42000, 0, 42000);
02427 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines